{"input": "\n\nfunc twoSum(nums []int, target int) []int ", "output": "{\n mymap := make(map[int]int)\n for i := 0; i < len(nums); i++ {\n j, ok := mymap[target-nums[i]]\n if ok {\n result := []int{j, i}\n return result\n }\n mymap[nums[i]] = i\n }\n result := []int{-1, -1}\n return result\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\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) WriteTo(buffer *bytes.Buffer) error ", "output": "{\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}"} {"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\n\n\n\n\nfunc New(key string, value interface{}) *Data {\n\treturn &Data{key, value, time.Now()}\n}\n\nfunc (d *Data) String() string ", "output": "{\n\treturn fmt.Sprintf(\"%s/%v\", d.Key, d.Value)\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\n\n\n\nfunc (*Server) GetAllowlist(ctx context.Context, request *rpcpb.GetAllowlistRequest) (*rpcpb.Allowlist, error) {\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}\n\nfunc (*Server) ListAllowlists(ctx context.Context, _ *emptypb.Empty) (*rpcpb.ListAllowlistsResponse, error) ", "output": "{\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}"} {"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\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\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) SetRoutees(routees *actor.PIDSet) ", "output": "{\n\tstate.routees = routees\n\tstate.values = routees.Values()\n}"} {"input": "package xml\n\nimport (\n\t\"encoding/xml\"\n\t\"github.com/graniticio/granitic/v2/ws\"\n\t\"net/http\"\n)\n\n\n\ntype MarshalingWriter struct {\n\tPrettyPrint bool\n\n\tIndentString string\n\n\tPrefixString string\n}\n\n\nfunc (mw *MarshalingWriter) MarshalAndWrite(data interface{}, w http.ResponseWriter) error {\n\n\tvar b []byte\n\tvar err error\n\n\tif mw.PrettyPrint {\n\t\tb, err = xml.MarshalIndent(data, mw.PrefixString, mw.IndentString)\n\t} else {\n\t\tb, err = xml.Marshal(data)\n\t}\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t_, err = w.Write(b)\n\n\treturn err\n\n}\n\n\ntype GraniticXMLResponseWrapper struct {\n}\n\n\nfunc (rw *GraniticXMLResponseWrapper) WrapResponse(body interface{}, errors interface{}) interface{} {\n\n\tw := new(GraniticXMLWrapper)\n\n\tw.XMLName = xml.Name{Space: \"\", Local: \"response\"}\n\tw.Body = body\n\tw.Errors = errors\n\n\treturn w\n\n}\n\n\ntype GraniticXMLWrapper struct {\n\tXMLName xml.Name\n\tErrors interface{}\n\tBody interface{} `xml:\"body\"`\n}\n\n\ntype GraniticXMLErrorFormatter struct{}\n\n\n\n\n\ntype Errors struct {\n\tXMLName xml.Name\n\tErrors interface{}\n}\n\n\ntype GraniticError struct {\n\tXMLName xml.Name\n\tError string `xml:\",chardata\"`\n\tField string `xml:\"field,attr,omitempty\"`\n\tCode string `xml:\"code,attr,omitempty\"`\n\tCategory string `xml:\"category,attr,omitempty\"`\n}\n\nfunc (ef *GraniticXMLErrorFormatter) FormatErrors(errors *ws.ServiceErrors) interface{} ", "output": "{\n\n\tif errors == nil || !errors.HasErrors() {\n\t\treturn nil\n\t}\n\n\tes := new(Errors)\n\tes.XMLName = xml.Name{Space: \"\", Local: \"errors\"}\n\n\tfe := make([]*GraniticError, len(errors.Errors))\n\n\tfor i, se := range errors.Errors {\n\n\t\te := new(GraniticError)\n\t\te.XMLName = xml.Name{Space: \"\", Local: \"error\"}\n\n\t\tfe[i] = e\n\t\te.Error = se.Message\n\t\te.Field = se.Field\n\t\te.Category = ws.CategoryToName(se.Category)\n\t\te.Code = se.Code\n\n\t}\n\n\tes.Errors = fe\n\n\treturn es\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\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 (this *requestAuthenticateCodec) Decode(reader io.Reader) (request Request, err error) ", "output": "{\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}"} {"input": "package buckettree\n\nimport (\n\t\"testing\"\n\n\t\"github.com/TarantulaTechnology/fabric/core/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 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\n\n\nfunc (u User) Role() string {\n\treturn u.role\n}\n\nfunc (u User) Lastname() string ", "output": "{\n\treturn u.lastname\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\nfunc NewDestination(serverName string, sourceIp string, destIp string) *Destination {\n\tdestination := &Destination{ServerName: serverName, SourceIp: sourceIp, DestinationIp: destIp}\n\treturn destination\n}\n\n\n\nfunc (self *Destination) Save(db GarinDB) ", "output": "{\n\tLogger().Debugf(\"Saving destination - %s\", self.Hash())\n\tdb.RecordDestination(self)\n\tLogger().Debugf(\"Destination saved - %s\", self.Hash())\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\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\n\n\nfunc (self *CmdAccountAddTriggers) RpcResult() interface{} {\n\tvar s string\n\treturn &s\n}\n\nfunc (self *CmdAccountAddTriggers) PostprocessRpcParams() error ", "output": "{\n\treturn nil\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\nfunc (s *Stack) Push(value interface{}) {\n\ts.top = &Element{value, s.top}\n\ts.size++\n}\n \n\n\n\n\nfunc (s *Stack) Pop() (value interface{}) ", "output": "{\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}"} {"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\n\n\nfunc (a *ApplicationParams) Validate() (bool, error) {\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}\n\nfunc (a *ApplicationParams) SetFlagsOptions(command *cobra.Command) ", "output": "{\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}"} {"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\nfunc NewReloadBookHandler(books *types.Books, index string) *ReloadBook {\n\treturn &ReloadBook{books: books, index: index}\n}\n\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 (rb *ReloadBook) ServeHTTP(w http.ResponseWriter, r *http.Request) ", "output": "{\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}"} {"input": "package architecture\n\nimport \"strings\"\n\ntype Architecture struct {\n\tRoot *Directory\n}\n\n\n\nfunc (arch *Architecture) FindDirectory(path string) *Directory {\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}\n\nfunc NewArchitecture() *Architecture ", "output": "{\n\treturn &Architecture{\n\t\tRoot: NewDirectory(),\n\t}\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\n\n\nfunc (c *CaptureHandler) Name() string {\n\treturn \"capture\"\n}\n\nfunc (c *Capture) ID() string {\n\treturn c.ProbePath\n}\n\nfunc (c *CaptureHandler) New() ApiResource ", "output": "{\n\treturn &Capture{}\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\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\n\n\nfunc (*valuesNode) Err() error ", "output": "{\n\treturn nil\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 source\nimport (\n\t\"fmt\"\n\t\"time\"\n)\n\nfunc f(from string) {\n\tfor i := 0; i<3; i++ {\n\t\tfmt.Println(from, \":\", i)\n\t\ttime.Sleep(time.Second)\n\t}\n}\n\n\n\nfunc Goroutines() ", "output": "{\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}"} {"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\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\n\n\nfunc (bc *bc) Quit() ", "output": "{\n\tbc.stdin.Close()\n\tbc.cmd.Wait()\n\tbc.stdout.Close()\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\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\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 ExampleErrIfNotJSONSchemaType() ", "output": "{\n\tfmt.Println(\"Good is nil:\", ErrIfNotJSONSchemaType(\"string\", \"my-field\") == nil)\n\tfmt.Println(\"Bad:\", ErrIfNotJSONSchemaType(\"str\", \"my-field\"))\n\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\n\n\nfunc debugDraw(result []image.Point, oldfile, newfile string, what color.Color) {\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}\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 panicIfErr(err error) ", "output": "{\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}"} {"input": "package core\n\n\ntype Clients []*Client\n\n\nfunc (cs *Clients) RLockRecursive() {\n\tfor _, client := range *cs {\n\t\tclient.RLockAnon()\n\t}\n}\n\n\n\n\nfunc (cs *Clients) RUnlockRecursive() ", "output": "{\n\tfor _, client := range *cs {\n\t\tclient.RUnlockAnon()\n\t}\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\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) WriteGo(w io.Writer, pac string) ", "output": "{\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}"} {"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\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\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) Preprocess(ctx *app.Context) error ", "output": "{\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}"} {"input": "package main\n\nvar nf int\nvar ng int\n\nfunc f() (int, int, int) {\n\tnf++\n\treturn 1, 2, 3\n}\n\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 g() int ", "output": "{\n\tng++\n\treturn 4\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\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) Close() error ", "output": "{\n\to.t.Kill(nil)\n\treturn o.t.Wait()\n}"} {"input": "package cloudatcost\n\nimport (\n\t\"fmt\"\n\t\"net/http\"\n\t\"net/url\"\n)\n\ntype CloudProService struct {\n\tclient *Client\n}\n\nfunc (s *CloudProService) Resources() (*CloudProResourcesData, *http.Response, error) {\n\tu := fmt.Sprintf(\"/api/v1/cloudpro/resources.php?key=%s&login=%s\", s.client.Option.Key, s.client.Option.Login)\n\n\treq, err := s.client.NewRequest(\"GET\", u, nil)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\trr := new(CloudProResourcesResponse)\n\tresp, err := s.client.Do(req, rr)\n\tif err != nil {\n\t\treturn nil, resp, err\n\t}\n\treturn &rr.Data, resp, err\n}\n\nfunc (s *CloudProService) Create(opt *CreateServerOptions) (*CloudProServerResponse, *http.Response, error) {\n\tu := \"/api/v1/cloudpro/build.php\"\n\n\tparameters := url.Values{}\n\tparameters.Add(\"key\", s.client.Option.Key)\n\tparameters.Add(\"login\", s.client.Option.Login)\n\tparameters.Add(\"cpu\", opt.Cpu)\n\tparameters.Add(\"os\", opt.OS)\n\tparameters.Add(\"ram\", opt.Ram)\n\tparameters.Add(\"storage\", opt.Storage)\n\tparameters.Add(\"datacenter\", opt.Datacenter)\n\n\treq, err := s.client.NewFormRequest(\"POST\", u, parameters)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tsr := new(CloudProServerResponse)\n\tresp, err := s.client.Do(req, sr)\n\tif err != nil {\n\t\treturn nil, resp, err\n\t}\n\treturn sr, resp, err\n}\n\n\n\nfunc (s *CloudProService) Delete(sid string) (*CloudProServerResponse, *http.Response, error) ", "output": "{\n\tu := \"/api/v1/cloudpro/delete.php\"\n\n\tparameters := url.Values{}\n\tparameters.Add(\"key\", s.client.Option.Key)\n\tparameters.Add(\"login\", s.client.Option.Login)\n\tparameters.Add(\"sid\", sid)\n\n\treq, err := s.client.NewFormRequest(\"POST\", u, parameters)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tsr := new(CloudProServerResponse)\n\tresp, err := s.client.Do(req, sr)\n\tif err != nil {\n\t\treturn nil, resp, err\n\t}\n\treturn sr, resp, err\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\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 ReverseNest1(s string) string ", "output": "{\n\tr := []rune(s)\n\tswitchHeadTail(r)\n\treturn string(r)\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}\nfunc (d *DatabaseComponent)Error()string{\n if d.err == nil{\n return \"\"\n }\n return d.err.Error()\n}\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)SetError(e error)", "output": "{\n d.err = e\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\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) Key() string ", "output": "{\n\treturn \"/system/reconsile_summaries\"\n}"} {"input": "package main\n\nimport (\n\t\"testing\"\n\n\t. \"github.com/atlassian/git-lob/Godeps/_workspace/src/github.com/onsi/ginkgo\"\n\t. \"github.com/atlassian/git-lob/Godeps/_workspace/src/github.com/onsi/gomega\"\n\t. \"github.com/atlassian/git-lob/util\"\n)\n\n\n\nfunc TestAll(t *testing.T) ", "output": "{\n\tRegisterFailHandler(Fail)\n\n\tloggingOff := true\n\tif loggingOff {\n\t\tLogSuppressAllConsoleOutput()\n\t}\n\n\tRunSpecs(t, \"Git Lob Root Test Suite\")\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\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 (s *SyslogPluginCommand) Synopsis() string ", "output": "{\n\treturn \"internal - lanch a syslog collector plugin\"\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\n\n\nfunc Succ(msg string) {\n\tfmt.Printf(\"\\033[1;32m[DONE]\\033[0m %s\\n\", msg)\n}\n\nfunc Warn(msg string) ", "output": "{\n\tfmt.Printf(\"\\033[1;33m[WARNING]\\033[0m %s\\n\", msg)\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\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 Infof(format string, args ...interface{}) ", "output": "{\n\tfmt.Print(\"\\033[1m-----> \")\n\tfmt.Printf(format+\"\\033[0m\", args...)\n}"} {"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\nfunc NewQueue() blocks.BlockInterface {\n\treturn &Queue{}\n}\n\n\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 (b *Queue) Setup() ", "output": "{\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}"} {"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\n\n\nfunc (c *Configuration) parseNetrc() (netrcfinder, error) {\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}\n\nfunc (n *noNetrc) FindMachine(host string) *netrc.Machine ", "output": "{\n\treturn nil\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\nfunc (r *FieldValueSetRequest) Get(ctx context.Context) (resObj *FieldValueSet, err error) {\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}\n\n\nfunc (r *FieldValueSetRequest) Update(ctx context.Context, reqObj *FieldValueSet) error {\n\treturn r.JSONRequest(ctx, \"PATCH\", \"\", reqObj, nil)\n}\n\n\n\n\nfunc (r *FieldValueSetRequest) Delete(ctx context.Context) error ", "output": "{\n\treturn r.JSONRequest(ctx, \"DELETE\", \"\", nil, nil)\n}"} {"input": "package middleware\n\nimport (\n\t\"github.com/drone/drone/bus\"\n\n\t\"github.com/codegangsta/cli\"\n\t\"github.com/gin-gonic/gin\"\n)\n\n\n\n\n\nfunc Bus(cli *cli.Context) gin.HandlerFunc ", "output": "{\n\tv := bus.New()\n\treturn func(c *gin.Context) {\n\t\tbus.ToContext(c, v)\n\t}\n}"} {"input": "package homehub\n\nimport (\n\t\"reflect\"\n\t\"strconv\"\n\t\"strings\"\n)\n\n\ntype NatRule struct {\n\tUID int `json:\"uid\"`\n\tEnable bool `json:\"Enable\"`\n\tAlias string `json:\"Alias\"`\n\tExternalInterface string `json:\"ExternalInterface\"`\n\tAllExternalInterfaces bool `json:\"AllExternalInterfaces\"`\n\tLeaseDuration int `json:\"LeaseDuration\"`\n\tRemoteHost string `json:\"RemoteHost\"`\n\tExternalPort int `json:\"ExternalPort\"`\n\tExternalPortEndRange int `json:\"ExternalPortEndRange\"`\n\tInternalInterface string `json:\"InternalInterface\"`\n\tInternalPort int `json:\"InternalPort\"`\n\tProtocol string `json:\"Protocol\"`\n\tService string `json:\"Service\"`\n\tInternalClient string `json:\"InternalClient\"`\n\tDescription string `json:\"Description\"`\n\tCreator string `json:\"Creator\"`\n\tTarget string `json:\"Target\"`\n\tLeaseStart string `json:\"LeaseStart\"`\n}\n\ntype portMapping struct {\n\tNatRule `json:\"PortMapping,omitempty\"`\n}\n\n\n\nfunc (n *NatRule) getUpdateActions(xpath string) []action ", "output": "{\n\tvar actions []action\n\tr := reflect.TypeOf(n).Elem()\n\tv := reflect.ValueOf(n).Elem()\n\tuid := v.FieldByName(\"UID\").Int()\n\n\tid := 0\n\tfor i := 0; i < v.NumField(); i++ {\n\t\tif r.Field(i).Name != \"UID\" &&\n\t\t\tr.Field(i).Name != \"Creator\" &&\n\t\t\tr.Field(i).Name != \"Target\" &&\n\t\t\tr.Field(i).Name != \"LeaseStart\" {\n\t\t\taction := action{\n\t\t\t\tID: id,\n\t\t\t\tMethod: methodSetValue,\n\t\t\t\tXPath: strings.Replace(xpath, \"#\", strconv.Itoa(int(uid)), 1) + \"/\" + r.Field(i).Name,\n\t\t\t\tParameters: ¶meters{\n\t\t\t\t\tValue: v.Field(i).Interface(),\n\t\t\t\t},\n\t\t\t}\n\t\t\tactions = append(actions, action)\n\t\t\tid++\n\t\t}\n\t}\n\n\treturn actions\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\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\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 SetMgoDb(mgoDatabase *mgo.Database) ", "output": "{\n\tdb = mgoDatabase\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\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) Push(x byte) ", "output": "{\n\t*s = append(*s, x)\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\nfunc availableTransports() string {\n\tvar transports = transportList()\n\treturn strings.Join(transports, \",\")\n}\n\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 firstTransport() string ", "output": "{\n\tvar transports = transportList()\n\treturn transports[0]\n}"} {"input": "package esx\n\nimport (\n\t\"log\"\n\n\t\"github.com/vmware/vsphere-storage-for-docker/tests/constants/esx\"\n\t\"github.com/vmware/vsphere-storage-for-docker/tests/constants/properties\"\n\t\"github.com/vmware/vsphere-storage-for-docker/tests/utils/misc\"\n\t\"github.com/vmware/vsphere-storage-for-docker/tests/utils/ssh\"\n)\n\ntype getVMPowerStatus func(string) string\n\n\n\nfunc GetVMProcessID(esxHostIP, vmName string) string {\n\tcmd := esx.ListVMProcess + \"| grep -e \" + vmName + \" -C 1 | grep 'World ID:' | awk '{print $3}'\"\n\tout, err := ssh.InvokeCommand(esxHostIP, cmd)\n\tif err != nil {\n\t\tlog.Fatalf(\"Failed to invoke command [%s]: %v\", cmd, err)\n\t}\n\treturn out\n}\n\n\n\nfunc KillVM(esxHostIP, vmName string) bool {\n\n\tprocessID := GetVMProcessID(esxHostIP, vmName)\n\n\tcmd := esx.KillVMProcess + processID\n\t_, err := ssh.InvokeCommand(esxHostIP, cmd)\n\tif err != nil {\n\t\tlog.Printf(\"Failed to invoke command [%s]: %v\", cmd, err)\n\t\treturn false\n\t}\n\treturn true\n}\n\n\nfunc WaitForExpectedState(fn getVMPowerStatus, vmName, expectedState string) bool {\n\tmaxAttempt := 20\n\twaitTime := 5\n\tfor attempt := 0; attempt < maxAttempt; attempt++ {\n\t\tmisc.SleepForSec(waitTime)\n\t\tstatus := fn(vmName)\n\t\tif status == expectedState {\n\t\t\treturn true\n\t\t}\n\t}\n\tlog.Printf(\"Timed out to poll status\\n\")\n\treturn false\n}\n\n\n\n\nfunc IsVDVSRunningAfterVMRestart(vmIP, vmName string) bool ", "output": "{\n\tisStatusOnline := WaitForExpectedState(GetVMPowerState, vmName, properties.PowerOnState)\n\tif !isStatusOnline {\n\t\tlog.Printf(\"VM %s is not in PoweredOn state\", vmName)\n\t\treturn false\n\t}\n\n\tisVDVSRunning := IsVDVSRunning(vmIP)\n\tif !isVDVSRunning {\n\t\tlog.Printf(\"VDVS is not running on VM [%s]. Please check if the previous VM IP [%s] has changed.\", vmName, vmIP)\n\t\treturn false\n\t}\n\n\treturn true\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\n\nfunc (p *statePack) Items() int { return len(p.states) }\nfunc (p *statePack) Stats() string { return fmt.Sprintf(\"%d\", len(p.states)) }\n\nfunc (p *statePack) PeerId() string ", "output": "{ return p.peerId }"} {"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\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) Warn(args ...interface{}) ", "output": "{\n\tl.Warnln(args...)\n}"} {"input": "package geo\n\n\n\ntype Polygon [][]Point\n\n\nfunc NewPolygon(points ...Point) Polygon {\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}\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\n\n\nfunc (p Polygon) Geo() *GeoJSON ", "output": "{\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}"} {"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\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\n\n\nfunc init() {\n\trevel.InterceptMethod(PortalController.Authorized, revel.BEFORE)\n}\n\nfunc (c PortalController) Authorized() revel.Result ", "output": "{\n\tif _, ok := c.authorized(); !ok {\n\t\treturn c.Redirect(routes.AuthController.Login())\n\t}\n\treturn nil\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\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\n\n\nfunc (xp XP) As_ArrayXP(key string) (data []XP) ", "output": "{\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}"} {"input": "package wicore\n\nimport \"fmt\"\n\nconst _BorderType_name = \"BorderNoneBorderSingleBorderDouble\"\n\nvar _BorderType_index = [...]uint8{0, 10, 22, 34}\n\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\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 BorderType) String() string ", "output": "{\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}"} {"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\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\nfunc (r *AWSIoTAnalyticsPipeline_Channel) SetDeletionPolicy(policy policies.DeletionPolicy) {\n\tr._deletionPolicy = policy\n}\n\nfunc (r *AWSIoTAnalyticsPipeline_Channel) AWSCloudFormationType() string ", "output": "{\n\treturn \"AWS::IoTAnalytics::Pipeline.Channel\"\n}"} {"input": "package tpl\n\nimport (\n\t\"html/template\"\n\t\"sync\"\n)\n\n\n\n\n\n\ntype cachingContext struct {\n\tbaseDir string\n\tmut *sync.Mutex\n\tcache map[filesMapKey]*template.Template\n\tfuncs template.FuncMap\n}\n\nfunc (c *cachingContext) Prepare(tplFiles Files) (*template.Template, error) {\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}\n\nfunc NewCachingContext(baseDir string, funcs template.FuncMap) Context ", "output": "{\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}"} {"input": "package sysutil\n\nimport \"golang.org/x/sys/unix\"\n\n\n\n\nfunc RlimitStack() (cur uint64, err error) ", "output": "{\n\tvar r unix.Rlimit\n\terr = unix.Getrlimit(unix.RLIMIT_STACK, &r)\n\treturn uint64(r.Cur), err \n}"} {"input": "package network\n\nimport (\n\tbosherr \"github.com/cloudfoundry/bosh-utils/errors\"\n\n\t\"github.com/rackspace/gophercloud\"\n\t\"github.com/rackspace/gophercloud/openstack/networking/v2/networks\"\n)\n\n\n\nfunc (n OpenStackNetworkNetworkService) Find(id string) (Network, bool, error) ", "output": "{\n\tn.logger.Debug(openstackNetworkNetworkServiceLogTag, \"Finding OpenStack Network '%s'\", id)\n\tnetworkItem, err := networks.Get(n.networkService, id).Extract()\n\tif err != nil {\n\t\terrCode, _ := err.(*gophercloud.UnexpectedResponseCodeError)\n\t\tif errCode.Actual == 404 {\n\t\t\treturn Network{}, false, nil\n\t\t}\n\n\t\treturn Network{}, false, bosherr.WrapErrorf(err, \"Failed to find OpenStack Network '%s'\", id)\n\t}\n\n\tnetwork := Network{\n\t\tID: networkItem.ID,\n\t\tName: networkItem.Name,\n\t}\n\treturn network, true, nil\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\nfunc (o *Offset) IECString() string {\n\treturn iecSizeString(int64(*o))\n}\n\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) UnmarshalYAML(unmarshal func(interface{}) error) error ", "output": "{\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}"} {"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\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 Info(args ...interface{}) ", "output": "{\n\tlogger.Info(args...)\n}"} {"input": "package main\n\nimport (\n\t\"net/http\"\n\t\"time\"\n)\n\n\n\nfunc NewClient() http.Client ", "output": "{\n\ttimeout := time.Duration(5 * time.Second)\n\treturn http.Client{\n\t\tTimeout: timeout,\n\t}\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\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 *errorReader) Read(p []byte) (n int, err error) ", "output": "{\n\treturn 0, fmt.Errorf(r.err)\n}"} {"input": "package cmd_test\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"github.com/pilosa/pilosa/cmd\"\n)\n\nfunc TestImportHelp(t *testing.T) {\n\toutput, err := ExecNewRootCommand(t, \"import\", \"--help\")\n\tif !strings.Contains(output, \"Usage:\") ||\n\t\t!strings.Contains(output, \"Flags:\") ||\n\t\t!strings.Contains(output, \"pilosa import\") || err != nil {\n\t\tt.Fatalf(\"Command 'import --help' not working, err: '%v', output: '%s'\", err, output)\n\t}\n}\n\n\n\nfunc TestImportConfig(t *testing.T) ", "output": "{\n\ttests := []commandTest{\n\t\t{\n\t\t\targs: []string{\"import\"},\n\t\t\tenv: map[string]string{\"PILOSA_HOST\": \"localhost:12345\"},\n\t\t\tcfgFileContent: `\nindex = \"myindex\"\nframe = \"f1\"\n`,\n\t\t\tvalidation: func() error {\n\t\t\t\tv := validator{}\n\t\t\t\tv.Check(cmd.Importer.Host, \"localhost:12345\")\n\t\t\t\tv.Check(cmd.Importer.Index, \"myindex\")\n\t\t\t\tv.Check(cmd.Importer.Frame, \"f1\")\n\t\t\t\treturn v.Error()\n\t\t\t},\n\t\t},\n\t}\n\texecuteDry(t, tests)\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\nfunc Cleanup() {\n\tfor _, f := range cleanupFuncs {\n\t\tf()\n\t}\n\tcleanupFuncs = []func(){}\n}\n\n\n\n\nfunc Exit(status int) ", "output": "{\n\tCleanup()\n\tos.Exit(status)\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\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 NewGetEndpointNotFound() *GetEndpointNotFound ", "output": "{\n\n\treturn &GetEndpointNotFound{}\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\nfunc (p PrefixTransform) ConvertKey(k ds.Key) ds.Key {\n\treturn p.Prefix.Child(k)\n}\n\n\n\n\nvar _ KeyTransform = (*PrefixTransform)(nil)\n\nfunc (p PrefixTransform) InvertKey(k ds.Key) ds.Key ", "output": "{\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}"} {"input": "package main\n\nimport (\n\t\"log\"\n\n\t\"github.com/zeromq/goczmq\"\n)\n\n\n\n\n\nfunc SimpleHelloWorldClient() {\n\tlog.Printf(\"client starting...\")\n\n\n\tclient, err := goczmq.NewReq(\"tcp://localhost:5555\")\n\tif err != nil {\n\t\tlog.Fatalf(\"client.NewReq error: %s\", err)\n\t}\n\n\n\tdefer client.Destroy()\n\n\n\trequest := [][]byte{[]byte(\"Hello\")}\n\n\n\terr = client.SendMessage(request)\n\tif err != nil {\n\t\tlog.Fatalf(\"client.SendMessage error: %s\", err)\n\t}\n\n\tlog.Printf(\"client.SendMessage '%s'\", request)\n\n\n\treply, err := client.RecvMessage()\n\tif err != nil {\n\t\tlog.Fatalf(\"client.RecvMessage error: %s\", err)\n\t}\n\n\tlog.Printf(\"client.RecvMessage: '%s'\", reply)\n}\n\n\n\n\n\n\n\n\n\nfunc main() {\n\tgo SimpleHelloWorldServer()\n\tSimpleHelloWorldClient()\n}\n\nfunc SimpleHelloWorldServer() ", "output": "{\n\tlog.Printf(\"server starting...\")\n\n\n\tserver, err := goczmq.NewRep(\"tcp://*:5555\")\n\tif err != nil {\n\t\tlog.Fatalf(\"server.NewRep error: %s\", err)\n\t}\n\n\n\tdefer server.Destroy()\n\n\n\trequest, err := server.RecvMessage()\n\tif err != nil {\n\t\tlog.Fatalf(\"server.RecvMessage error: %s\", err)\n\t}\n\n\tlog.Printf(\"server.RecvMessage: '%s'\", request)\n\n\n\treply := [][]byte{[]byte(\"World\")}\n\n\n\terr = server.SendMessage(reply)\n\tif err != nil {\n\t\tlog.Fatalf(\"server.SendMessage error: %s\", err)\n\t}\n\n\tlog.Printf(\"server.SendMessage: '%s'\", reply)\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\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) Pop() interface{} ", "output": "{\n\theapSize := len(*h)\n\tlastVertex := (*h)[heapSize-1]\n\t*h = (*h)[0 : heapSize-1]\n\treturn lastVertex\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\nfunc (s *Sender) write(data []byte) {\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}\n\n\n\nfunc (s *Sender) Send(data []byte) (err error) ", "output": "{\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}"} {"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\nfunc (self *ConstantDoubleInfo) readInfo(reader *ClassReader) {\n\tbytes := reader.readUint64()\n\tself.val = math.Float64frombits(bytes)\n}\n\n\n\nfunc (self *ConstantDoubleInfo) Value() float64 ", "output": "{\n\treturn self.val\n}"} {"input": "package edit\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"os\"\n\t\"os/exec\"\n\n\t\"github.com/bazelbuild/buildtools/build\"\n)\n\ntype defaultBuildifier struct{}\n\n\n\n\n\n\nfunc (b *defaultBuildifier) Buildify(opts *Options, f *build.File) ([]byte, error) ", "output": "{\n\tif opts.Buildifier == \"\" {\n\t\tcontents := build.Format(f)\n\t\tnewF, err := build.ParseBuild(f.Path, []byte(contents))\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn build.Format(newF), nil\n\t}\n\n\tcmd := exec.Command(opts.Buildifier, \"--type=build\")\n\tdata := build.Format(f)\n\tcmd.Stdin = bytes.NewBuffer(data)\n\tstdout := bytes.NewBuffer(nil)\n\tstderr := bytes.NewBuffer(nil)\n\tcmd.Stdout = stdout\n\tcmd.Stderr = stderr\n\tcmd.Env = append(\n \tos.Environ(),\n\t \n\t)\n\terr := cmd.Run()\n\tif stderr.Len() > 0 {\n\t\treturn nil, fmt.Errorf(\"%s\", stderr.Bytes())\n\t}\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn stdout.Bytes(), nil\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\nfunc PushMessage(channel string, message interface{}) {\n\tPushCenter.Pub(message, channel)\n}\n\n\n\nfunc Subscribe(channel string, callback func(message interface{})) ", "output": "{\n\tch := PushCenter.Sub(channel)\n\tfor {\n\t\tout := <-ch\n\t\tcallback(out)\n\t}\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\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\n\n\nfunc DeserializeBytes(b []byte, m interface{}) error ", "output": "{\n\tdec := gob.NewDecoder(bytes.NewBuffer(b))\n\treturn dec.Decode(m) \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\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 ParseFilePublicPEM(filename string) (pub *rsa.PublicKey, err error) ", "output": "{\n\n\tb, err := ioutil.ReadFile(filename)\n\tif err != nil {\n\n\t\treturn\n\t}\n\n\treturn ParsePublicPEM(b)\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\nfunc (s *validatingWebhookConfigurationLister) List(selector labels.Selector) (ret []*admissionregistration.ValidatingWebhookConfiguration, err error) {\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}\n\n\n\n\nfunc (s *validatingWebhookConfigurationLister) Get(name string) (*admissionregistration.ValidatingWebhookConfiguration, 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(\"validatingwebhookconfiguration\"), name)\n\t}\n\treturn obj.(*admissionregistration.ValidatingWebhookConfiguration), nil\n}"} {"input": "package distro\n\nimport (\n\t\"encoding/json\"\n\t\"io\"\n\t\"io/ioutil\"\n\t\"net/http\"\n\n\t\"github.com/drasko/edgex-export\"\n\t\"github.com/go-zoo/bone\"\n\t\"go.uber.org/zap\"\n)\n\nfunc replyPing(w http.ResponseWriter, r *http.Request) {\n\tw.Header().Set(\"Content-Type\", \"application/text; charset=utf-8\")\n\tw.WriteHeader(http.StatusOK)\n\tstr := `pong`\n\tio.WriteString(w, str)\n}\n\nfunc replyNotifyRegistrations(w http.ResponseWriter, r *http.Request) {\n\tdata, err := ioutil.ReadAll(r.Body)\n\tif err != nil {\n\t\tlogger.Error(\"Failed read body\", zap.Error(err))\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\tio.WriteString(w, err.Error())\n\t\treturn\n\t}\n\n\tupdate := export.NotifyUpdate{}\n\tif err := json.Unmarshal(data, &update); err != nil {\n\t\tlogger.Error(\"Failed to parse\", zap.ByteString(\"json\", data))\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\tio.WriteString(w, err.Error())\n\t\treturn\n\t}\n\tif update.Name == \"\" || update.Operation == \"\" {\n\t\tlogger.Error(\"Missing json field\", zap.Any(\"update\", update))\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\treturn\n\t}\n\tif update.Operation != export.NotifyUpdateAdd &&\n\t\tupdate.Operation != export.NotifyUpdateUpdate &&\n\t\tupdate.Operation != export.NotifyUpdateDelete {\n\t\tlogger.Error(\"Invalid value for operation\",\n\t\t\tzap.String(\"operation\", update.Operation))\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tw.WriteHeader(http.StatusOK)\n\tRefreshRegistrations(update)\n}\n\n\n\n\nfunc httpServer() http.Handler ", "output": "{\n\tmux := bone.New()\n\n\tmux.Get(\"/api/v1/ping\", http.HandlerFunc(replyPing))\n\tmux.Put(\"/api/v1/notify/registrations\", http.HandlerFunc(replyNotifyRegistrations))\n\n\treturn mux\n}"} {"input": "package eventgrid\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() + \" eventgrid/2019-02-01-preview\"\n}\n\n\n\n\nfunc Version() string ", "output": "{\n\treturn version.Number\n}"} {"input": "package hc256_test\n\nimport (\n\t\"bytes\"\n\t\"testing\"\n\n\t\"github.com/ebfe/estream/hc256\"\n)\n\n\n\nfunc TestKeyStream(t *testing.T) {\n\tfor i, tc := range tests {\n\t\tc, err := hc256.NewCipher(tc.key, tc.iv)\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"tests[%d]: NewCipher() err: %s\\n\", i, err)\n\t\t}\n\n\t\tlastchunk := tc.chunks[len(tc.chunks)-1]\n\t\tmlen := lastchunk.offset + len(lastchunk.val)\n\t\tks := make([]byte, mlen)\n\n\t\tc.XORKeyStream(ks, ks)\n\n\t\tfor j, chunk := range tc.chunks {\n\t\t\tkschunk := ks[chunk.offset : chunk.offset+len(chunk.val)]\n\t\t\tif !bytes.Equal(kschunk, chunk.val) {\n\t\t\t\tt.Errorf(\"tests[%d] chunk[%d]:\\n\\tks = %x\\n\\twant %x\\n\", i, j, kschunk, chunk.val)\n\t\t\t}\n\t\t}\n\n\t\tdigest := xordigest(ks, len(tc.xor))\n\t\tif !bytes.Equal(digest, tc.xor) {\n\t\t\tt.Errorf(\"tests[%d] xor-digest = %x want %x\\n\", i, digest, tc.xor)\n\t\t}\n\t}\n}\n\nfunc xordigest(msg []byte, n int) []byte ", "output": "{\n\td := make([]byte, n)\n\n\tfor i := range msg {\n\t\td[i%len(d)] ^= msg[i]\n\t}\n\n\treturn d\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\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\n\n\nfunc TestMaxReturnsLargestArgWhenGivenMultipleArgs(t *testing.T) ", "output": "{\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}"} {"input": "package elastic\n\nimport (\n\t\"encoding/json\"\n\t\"testing\"\n)\n\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\nfunc TestRangeFilterWithFormat(t *testing.T) {\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}\n\nfunc TestRangeFilter(t *testing.T) ", "output": "{\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}"} {"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\nfunc getReverse(metadata string) bool {\n data := strings.Fields(metadata)\n return len(data) > 6 && data[6] == reverseFlag\n}\n\n\n\nfunc lastCharLine(text string, height int) bool ", "output": "{\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}"} {"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\n\n\n\n\nfunc NewR11nQueueSet(d sous.Deployer, r sous.Registry, rf *sous.ResolveFilter, sm *ServerStateManager) *sous.R11nQueueSet {\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}\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 ", "output": "{\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}"} {"input": "package beegoplus\n\nconst (\n\tHEADLOCATION ParamLocation = \"HEAD\"\n\tQUERYLOCATION = \"QUERY\"\n\tBODYLOCATION = \"BODY\"\n\tPATHLOCATION = \"PATH\"\n)\n\nconst (\n\tSTRINGTYPE ParamType = \"String\"\n\tNUMBERTYPE = \"Number\"\n\tBOOLEANTYPE = \"boolean\"\n\tOBJECTTYPE = \"object\"\n)\n\n\ntype ParamLocation string\n\n\ntype ParamType string\n\n\ntype Param struct {\n\tLocation ParamLocation \n\tName string\n\tType ParamType\n\tMaxLen int\n\tEnum []interface{}\n\tDefautValue interface{}\n\tMuilti bool \n\tMust bool\n\tPattern string\n\tDescription string\n}\n\n\ntype ParamValues map[string][]interface{}\n\n\n\n\nfunc (p ParamType) Empty() interface{} ", "output": "{\n\tswitch p {\n\tcase BOOLEANTYPE:\n\t\treturn false\n\tcase STRINGTYPE:\n\t\treturn \"\"\n\tcase NUMBERTYPE:\n\t\treturn 0\n\t}\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\n\n\n\n\nfunc CallHttp(param1, param2 string) (string, error) {\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}\n\nfunc SetHttpUrl(url string) ", "output": "{\n url = strings.Trim(url, \"/\")\n url = fmt.Sprintf(\"%s/\", url)\n httpUrl = url\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\n\n\nfunc (h Struct) ServeHTTP(\n\tw http.ResponseWriter,\n\tr *http.Request) {\n\tfmt.Fprint(w, fmt.Sprintf(\"%s%s%s\", h.Greeting, h.Punct, h.Who))\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 String) ServeHTTP(\n\tw http.ResponseWriter,\n\tr *http.Request) ", "output": "{\n\tfmt.Fprint(w, h)\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\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_Invalid(t *testing.T) ", "output": "{\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}"} {"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\nfunc (msg *MsgFilterClear) MaxPayloadLength(pver uint32) uint32 {\n\treturn 0\n}\n\n\n\n\n\nfunc NewMsgFilterClear() *MsgFilterClear ", "output": "{\n\treturn &MsgFilterClear{}\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\nfunc ExampleDump() {\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}\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\n\n\nfunc ExampleConfigState_Dump() ", "output": "{\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}"} {"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\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 removeFile(fname string) error ", "output": "{\n\terr := os.Remove(fname)\n\tif (err != nil) && !os.IsNotExist(err) {\n\t\treturn err\n\t}\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\nfunc NewPodSecurityPolicyLister(indexer cache.Indexer) PodSecurityPolicyLister {\n\treturn &podSecurityPolicyLister{indexer: indexer}\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\n\n\nfunc (s *podSecurityPolicyLister) Get(name string) (*v1beta1.PodSecurityPolicy, 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(\"podsecuritypolicy\"), name)\n\t}\n\treturn obj.(*v1beta1.PodSecurityPolicy), nil\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\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 NewUDPPool(address string, workerNumber int) *UDPPool ", "output": "{\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}"} {"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\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\n\n\nfunc Supported() bool ", "output": "{\n\treturn true\n}"} {"input": "package command\n\nimport (\n\t\"path/filepath\"\n)\n\n\n\nfunc fixtureDir(n string) string ", "output": "{\n\treturn filepath.Join(\"./test-fixtures\", n)\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\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\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) Validate(v int64) error ", "output": "{\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}"} {"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\n\n\nfunc (w *reconsileSummaries) BackendType() string {\n\treturn \"nomad\"\n}\n\nfunc (w *reconsileSummaries) IsMutable() bool ", "output": "{\n\treturn true\n}"} {"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\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 (interceptor *outputInterceptor) StartInterceptingOutput() error ", "output": "{\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}"} {"input": "package v3\n\nimport (\n\t\"github.com/apache/servicecomb-service-center/pkg/rest\"\n\t\"github.com/apache/servicecomb-service-center/server/rest/controller/v4\"\n)\n\ntype TagService struct {\n\tv4.TagService\n}\n\n\n\nfunc (this *TagService) URLPatterns() []rest.Route ", "output": "{\n\treturn []rest.Route{\n\t\t{rest.HTTP_METHOD_POST, \"/registry/v3/microservices/:serviceId/tags\", this.AddTags},\n\t\t{rest.HTTP_METHOD_PUT, \"/registry/v3/microservices/:serviceId/tags/:key\", this.UpdateTag},\n\t\t{rest.HTTP_METHOD_GET, \"/registry/v3/microservices/:serviceId/tags\", this.GetTags},\n\t\t{rest.HTTP_METHOD_DELETE, \"/registry/v3/microservices/:serviceId/tags/:key\", this.DeleteTags},\n\t}\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\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 ExpectNoError(err error, explain ...interface{}) ", "output": "{\n\tif err != nil {\n\t\tLogf(\"Unexpected error occurred: %v\", err)\n\t}\n\tExpectWithOffset(1, err).NotTo(HaveOccurred(), explain...)\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\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\nfunc newFIFOSet(bundleDir, containerID, processID string, withStdin, withTerminal bool) *containerd.FIFOSet {\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}\n\nfunc summaryFromInterface(i interface{}) (*Summary, error) ", "output": "{\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}"} {"input": "package pf\n\nimport (\n\t\"os\"\n\t\"time\"\n)\n\n\n\n\nfunc GetPremiumFriday(y int, m time.Month) (int, error) ", "output": "{\n\tif y < 2017 || m < time.January || m > time.December {\n\t\treturn 0, os.ErrInvalid\n\t}\n\tif y == 2017 && m < time.February { \n\t\treturn 0, os.ErrInvalid\n\t}\n\n\ttm := time.Date(y, m+1, 0, 0, 0, 0, 0, time.UTC) \n\n\tw := tm.Weekday() - time.Friday\n\tif w < 0 {\n\t\tw += 7\n\t}\n\treturn tm.Day() - (int)(w), nil\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\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\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 NewUserService(r number.NumberRepository) UserService ", "output": "{\n\treturn &service{repository: r}\n}"} {"input": "package timeutil\n\nimport (\n\t\"time\"\n)\n\n\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\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 SetTimeout(t time.Duration, callback func()) ", "output": "{\n\tgo func() {\n\t\ttime.Sleep(t)\n\t\tcallback()\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\n\n\nfunc (ast *IndexExpr) Dump(indent int) {\n\tfmt.Printf(\"%s- index_expr:\\n\", strings.Repeat(\" \", indent))\n\tast.Operand.Dump(indent + 4)\n\tast.Index.Dump(indent + 4)\n}\n\nfunc (ast *IndexExpr) Exec(ctx *exec.Context) (bool, interface{}, error) ", "output": "{\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}"} {"input": "package drum\n\nimport (\n\t\"fmt\"\n\t\"os\"\n)\n\n\n\n\n\n\n\n\ntype Pattern struct {\n\tVersion string\n\tTempo float32\n\tTracks []Track\n}\n\nfunc (p Pattern) String() string {\n\ts := fmt.Sprintln(\"Saved with HW Version:\", p.Version)\n\ts += fmt.Sprintln(\"Tempo:\", p.Tempo)\n\tfor _, t := range p.Tracks {\n\t\ts += fmt.Sprint(t)\n\t}\n\treturn s\n}\n\nfunc DecodeFile(path string) (*Pattern, error) ", "output": "{\n\tf, err := os.Open(path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar p *Pattern\n\tif p, err = decode(f); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn p, f.Close()\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\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\n\n\nfunc NewConfigs(r io.Reader) (Configs, error) ", "output": "{\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}"} {"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\n\n\n\n\n\nfunc clearReferenceMask(obj contrail.IObject) {\n\tvalue := reflect.ValueOf(obj).Elem()\n\tfield := value.FieldByName(\"valid\")\n\tmaskptr := (*uint64)(unsafe.Pointer(field.UnsafeAddr()))\n\t*maskptr = 0\n}\n\nfunc getReferenceList(obj contrail.IObject) UIDList ", "output": "{\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}"} {"input": "package neurgo\n\nimport (\n\t\"bufio\"\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n)\n\n\n\nfunc JsonString(v interface{}) string {\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}\n\nfunc WriteStringToFile(value string, filepath string) error ", "output": "{\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}"} {"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\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 TestBadRequest_Error(t *testing.T) ", "output": "{\n\tif client.BadRequest.Error() != \"Bad request\" {\n\t\tt.FailNow()\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}\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\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) unauthorized(r *http.Request, w http.ResponseWriter, err error, msg string) ", "output": "{\n\ts.serveError(w, err, msg, \"Unauthorized\", http.StatusUnauthorized)\n}"} {"input": "package router\n\nimport (\n\t\"log\"\n\t\"net/http\"\n\t\"net/http/httptest\"\n\t\"net/url\"\n\t\"testing\"\n\n\t\"github.com/fission/fission\"\n)\n\n\n\n\nfunc TestFunctionProxying(t *testing.T) {\n\ttestResponseString := \"hi\"\n\tbackendURL := createBackendService(testResponseString)\n\tlog.Printf(\"Created backend svc at %v\", backendURL)\n\n\tfn := &fission.Metadata{Name: \"foo\", Uid: \"xxx\"}\n\tfmap := makeFunctionServiceMap(0)\n\tfmap.assign(fn, backendURL)\n\n\tfh := &functionHandler{fmap: fmap, Function: *fn}\n\tfunctionHandlerServer := httptest.NewServer(http.HandlerFunc(fh.handler))\n\tfhURL := functionHandlerServer.URL\n\n\ttestRequest(fhURL, testResponseString)\n}\n\nfunc createBackendService(testResponseString string) *url.URL ", "output": "{\n\tbackendServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tw.Write([]byte(testResponseString))\n\t}))\n\n\tbackendURL, err := url.Parse(backendServer.URL)\n\tif err != nil {\n\t\tpanic(\"error parsing url\")\n\t}\n\treturn backendURL\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\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\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 defaultAddr(addr string) string ", "output": "{\n\treturn fmt.Sprintf(\"%s://%s\", firstTransport(), 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\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\nfunc (h *hostNS) Set(s *specs.Spec) error {\n\treturn oci.WithHostNamespace(specs.NetworkNamespace)(nil, nil, nil, s)\n}\n\n\n\nfunc (h *hostNS) Close() error ", "output": "{\n\treturn nil\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\nfunc (b *memBatch) Put(key, value []byte) error {\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}\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\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) Write() error ", "output": "{\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}"} {"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\nfunc endpointClient() *gophercloud.ServiceClient {\n\treturn &gophercloud.ServiceClient{Endpoint: endpoint}\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\n\n\nfunc TestListDetailURL(t *testing.T) ", "output": "{\n\tactual := listDetailURL(endpointClient())\n\texpected := endpoint + \"images/detail\"\n\tth.CheckEquals(t, expected, actual)\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\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 (*Artifact) BuilderId() string ", "output": "{\n\treturn BuilderId\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\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) CopyDeliveryServices() map[DeliveryServiceName]CRStatesDeliveryService ", "output": "{\n\tb := map[DeliveryServiceName]CRStatesDeliveryService{}\n\tfor k, v := range a.DeliveryService {\n\t\tb[k] = v\n\t}\n\treturn b\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\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 Tweet() ", "output": "{\n\tPostTweet(\"Testing now\")\n}"} {"input": "package mysql\n\nimport (\n\t\"encoding/binary\"\n\n\t\"github.com/berkaroad/saashard/errors\"\n)\n\n\nfunc (p *PacketIO) WriteError(capability uint32, e error) error {\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}\n\n\n\nfunc (p *PacketIO) handleErrorPacket(capability uint32, data []byte) error ", "output": "{\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}"} {"input": "package iso20022\n\n\ntype Party24Choice struct {\n\n\tOrganisation *Organisation17 `xml:\"Org\"`\n\n\tIndividualPerson *IndividualPerson24 `xml:\"IndvPrsn\"`\n}\n\nfunc (p *Party24Choice) AddOrganisation() *Organisation17 {\n\tp.Organisation = new(Organisation17)\n\treturn p.Organisation\n}\n\n\n\nfunc (p *Party24Choice) AddIndividualPerson() *IndividualPerson24 ", "output": "{\n\tp.IndividualPerson = new(IndividualPerson24)\n\treturn p.IndividualPerson\n}"} {"input": "package leetcode\n\nimport \"testing\"\n\n\n\nfunc TestNumJewelsInStones(t *testing.T) ", "output": "{\n\tif numJewelsInStones(\"aA\", \"aAAbbbb\") != 3 {\n\t\tt.Fatal()\n\t}\n\tif numJewelsInStones(\"z\", \"ZZ\") != 0 {\n\t\tt.Fatal()\n\t}\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\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\n\n\nfunc mkzcgo(dir, file string) ", "output": "{\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}"} {"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\n\n\n\nfunc getGoFilesFromPackage(pkg *build.Package, err error) ([]string, error) {\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}\n\nfunc GetGoFilesFromDirectoryRecursive(dirname string) ([]string, error) ", "output": "{\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}"} {"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\tcluster \"k8s.io/kube-deploy/ext-apiserver/pkg/apis/cluster\"\n)\n\n\ntype ClusterLister interface {\n\tList(selector labels.Selector) (ret []*cluster.Cluster, err error)\n\tClusters(namespace string) ClusterNamespaceLister\n\tClusterListerExpansion\n}\n\n\ntype clusterLister struct {\n\tindexer cache.Indexer\n}\n\n\nfunc NewClusterLister(indexer cache.Indexer) ClusterLister {\n\treturn &clusterLister{indexer: indexer}\n}\n\n\nfunc (s *clusterLister) List(selector labels.Selector) (ret []*cluster.Cluster, err error) {\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*cluster.Cluster))\n\t})\n\treturn ret, err\n}\n\n\nfunc (s *clusterLister) Clusters(namespace string) ClusterNamespaceLister {\n\treturn clusterNamespaceLister{indexer: s.indexer, namespace: namespace}\n}\n\n\ntype ClusterNamespaceLister interface {\n\tList(selector labels.Selector) (ret []*cluster.Cluster, err error)\n\tGet(name string) (*cluster.Cluster, error)\n\tClusterNamespaceListerExpansion\n}\n\n\n\ntype clusterNamespaceLister struct {\n\tindexer cache.Indexer\n\tnamespace string\n}\n\n\nfunc (s clusterNamespaceLister) List(selector labels.Selector) (ret []*cluster.Cluster, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*cluster.Cluster))\n\t})\n\treturn ret, err\n}\n\n\n\n\nfunc (s clusterNamespaceLister) Get(name string) (*cluster.Cluster, 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(cluster.Resource(\"cluster\"), name)\n\t}\n\treturn obj.(*cluster.Cluster), nil\n}"} {"input": "package matrix\n\nimport \"github.com/hebl/gosl/errors\"\n\n\n\n\nfunc Product(A, B *Matrix) (*Matrix, error) ", "output": "{\n\tif A.size2 != B.size1 {\n\t\treturn nil, errors.ErrBADLEN\n\t}\n\n\tC := Zeros(A.size1, B.size2)\n\n\tfor i := 0; i < A.size1; i++ {\n\t\tfor j := 0; j < B.size2; j++ {\n\t\t\tv := 0.0\n\t\t\tfor k := 0; k < A.size2; k++ {\n\t\t\t\tv += A.At(i, k) * B.At(k, j)\n\t\t\t}\n\t\t\tC.Set(i, j, v)\n\t\t}\n\t}\n\n\treturn C, nil\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\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\nfunc networkAsChild(arg interface{}) interface{} {\n\tnetwork := arg.(models.Network)\n\treturn networkIdxElem{Network: network}\n}\n\nfunc NetworkIndex(args interface{}) interface{} ", "output": "{\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}"} {"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\nfunc TestSimple(t *testing.T) {\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}\n\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 TestTiny(t *testing.T) ", "output": "{\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}"} {"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\nfunc (e *ParseError) GetInnerErr() error {\n\treturn e.err\n}\n\n\n\n\n\n\n\nfunc NewParseError(locatorField string, err error) error ", "output": "{\n\treturn &ParseError{\n\t\tLocatorField: locatorField,\n\t\terr: err,\n\t}\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\nfunc TestTestConfigure(t *testing.T) {\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}\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\n\n\nfunc TestTestCollect(t *testing.T) ", "output": "{\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}"} {"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\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\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 NewMenu(name string, lw *display.LineWriter) (*Menu, error) ", "output": "{\n\treturn &Menu{\n\t\tName: name,\n\t\tlw: lw,\n\t}, 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}\nfunc BenchmarkTableEmoji(b *testing.B) {\n\tbenchSink = benchTable(b, emoji)\n}\n\nfunc BenchmarkTableNeutral(b *testing.B) {\n\tbenchSink = benchTable(b, neutral)\n}\n\nfunc BenchmarkTableNotassigned(b *testing.B) ", "output": "{\n\tbenchSink = benchTable(b, notassigned)\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\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) GetDefaultDecision() FilterDecision ", "output": "{\n\treturn Fail\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\n\n\nfunc NewLightDataNone() *LightData {\n\treturn &LightData{false, core.NewVec3Zero()}\n}\n\nfunc (light *LightData) IsLight() bool {\n\treturn light.isLight\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 NewLightData(pos core.Vec3) *LightData ", "output": "{\n\treturn &LightData{false, pos}\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\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\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) String() string ", "output": "{\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}"} {"input": "package null\n\nimport (\n\t\"database/sql\"\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"reflect\"\n\t\"strconv\"\n)\n\n\n\ntype String struct {\n\tsql.NullString\n}\n\n\nfunc StringFrom(s string) String {\n\treturn NewString(s, true)\n}\n\n\nfunc StringFromPtr(s *string) String {\n\tif s == nil {\n\t\treturn NewString(\"\", false)\n\t}\n\treturn NewString(*s, true)\n}\n\n\nfunc NewString(s string, valid bool) String {\n\treturn String{\n\t\tNullString: sql.NullString{\n\t\t\tString: s,\n\t\t\tValid: valid,\n\t\t},\n\t}\n}\n\n\n\n\n\n\n\n\nfunc (s String) MarshalJSON() ([]byte, error) {\n\tif !s.Valid {\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn json.Marshal(s.String)\n}\n\n\n\nfunc (s *String) UnmarshalText(text []byte) error {\n\ts.String = string(text)\n\ts.Valid = s.String != \"\" \n\treturn nil\n}\n\n\nfunc (s *String) SetValid(v string) {\n\ts.String = v\n\ts.Valid = true\n}\n\n\nfunc (s String) Ptr() *string {\n\tif !s.Valid {\n\t\treturn nil\n\t}\n\treturn &s.String\n}\n\n\n\nfunc (s String) IsZero() bool {\n\treturn !s.Valid\n}\n\nfunc (s *String) UnmarshalJSON(data []byte) error ", "output": "{\n\tvar err error\n\tvar v interface{}\n\tjson.Unmarshal(data, &v)\n\tswitch x := v.(type) {\n\tcase string:\n\t\ts.String = x\n\tcase map[string]interface{}:\n\t\terr = json.Unmarshal(data, &s.NullString)\n\tcase nil:\n\t\ts.Valid = false\n\t\treturn nil\n\tcase float64:\n\t\ts.String = strconv.FormatFloat(v.(float64), 'f', -1, 64)\n\tcase bool:\n\t\ts.String = strconv.FormatBool(v.(bool))\n\tdefault:\n\t\terr = fmt.Errorf(\"json: cannot unmarshal %v into Go value of type null.String\", reflect.TypeOf(v).Name())\n\t}\n\ts.Valid = err == nil\n\treturn err\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\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 TestNotifyUnlockAlreadyUnlocked(t *testing.T) ", "output": "{\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}"} {"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\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 *countingWriter) Write(bs []byte) (int, error) ", "output": "{\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}"} {"input": "package externalcontrollerupdater_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 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\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 TestMarshalEncoderFactory(t *testing.T) ", "output": "{\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}"} {"input": "package iso20022\n\n\ntype Party24Choice struct {\n\n\tOrganisation *Organisation17 `xml:\"Org\"`\n\n\tIndividualPerson *IndividualPerson24 `xml:\"IndvPrsn\"`\n}\n\n\n\nfunc (p *Party24Choice) AddIndividualPerson() *IndividualPerson24 {\n\tp.IndividualPerson = new(IndividualPerson24)\n\treturn p.IndividualPerson\n}\n\nfunc (p *Party24Choice) AddOrganisation() *Organisation17 ", "output": "{\n\tp.Organisation = new(Organisation17)\n\treturn p.Organisation\n}"} {"input": "package iotcentral\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() + \" iotcentral/2021-06-01\"\n}\n\n\n\n\nfunc Version() string ", "output": "{\n\treturn version.Number\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\nfunc (self *CacheParamCfg) loadFromJsonCfg(jsnCfg *CacheParamJsonCfg) error {\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}\n\ntype CacheCfg map[string]*CacheParamCfg\n\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 CacheCfg) loadFromJsonCfg(jsnCfg *CacheJsonCfg) (err error) ", "output": "{\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}"} {"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\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) GetAll() ([][]byte, error) ", "output": "{\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}"} {"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\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\n\n\nfunc (d Disks) Type() string ", "output": "{\n\treturn \"disk\"\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\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 Tracks) String() string ", "output": "{\n\tpretty := \"\"\n\tfor _, track := range t {\n\t\tpretty = fmt.Sprintf(\"%s%s\\n\", pretty, track.String())\n\t}\n\treturn pretty\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\nfunc (m *CreateIamTokenResponse) SetIamToken(v string) {\n\tm.IamToken = v\n}\n\n\n\nfunc (m *CreateIamTokenResponse) SetExpiresAt(v *timestamp.Timestamp) ", "output": "{\n\tm.ExpiresAt = v\n}"} {"input": "package helpers\n\nimport (\n\t\"fmt\"\n\n\t. \"github.com/onsi/ginkgo\"\n)\n\nconst V7 = true\n\n\n\nfunc SkipIfV7AndVersionLessThan(minVersion string) {\n\tSkipIfVersionLessThan(minVersion)\n}\n\n\n\n\nfunc SkipIfV7() ", "output": "{\n\tSkip(fmt.Sprintf(\"Not implemented for V7 yet\"))\n}"} {"input": "package machinelearningservices\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() + \" machinelearningservices/2021-07-01\"\n}\n\n\n\n\nfunc Version() string ", "output": "{\n\treturn version.Number\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\n\n\nfunc (f *FakeCache) List(s labels.Selector) ([]*api.Pod, error) { return nil, nil }\n\nfunc (f *FakeCache) UpdateNodeNameToInfoMap(infoMap map[string]*schedulercache.NodeInfo) error ", "output": "{\n\treturn nil\n}"} {"input": "package dom\n\n\n\nimport (\n \"xml\"\n)\n\ntype _text struct {\n _cdata\n}\n\n\n\nfunc newText(token xml.CharData) (*_text) {\n n := newNode(TEXT_NODE)\n t := &_text{ _cdata{n, token.Copy()} }\n n.self = Node(t)\n return t\n}\n\nfunc (t *_text) NodeName() (s string) ", "output": "{\n return \"#text\"\n}"} {"input": "package wal\n\nimport (\n\t\"bufio\"\n\t\"encoding/binary\"\n\t\"hash\"\n\t\"io\"\n\t\"sync\"\n\n\t\"github.com/coreos/mantle/Godeps/_workspace/src/github.com/coreos/etcd/pkg/crc\"\n\t\"github.com/coreos/mantle/Godeps/_workspace/src/github.com/coreos/etcd/wal/walpb\"\n)\n\ntype encoder struct {\n\tmu sync.Mutex\n\tbw *bufio.Writer\n\n\tcrc hash.Hash32\n\tbuf []byte\n\tuint64buf []byte\n}\n\nfunc newEncoder(w io.Writer, prevCrc uint32) *encoder {\n\treturn &encoder{\n\t\tbw: bufio.NewWriter(w),\n\t\tcrc: crc.New(prevCrc, crcTable),\n\t\tbuf: make([]byte, 1024*1024),\n\t\tuint64buf: make([]byte, 8),\n\t}\n}\n\n\n\nfunc (e *encoder) flush() error {\n\te.mu.Lock()\n\tdefer e.mu.Unlock()\n\treturn e.bw.Flush()\n}\n\nfunc writeInt64(w io.Writer, n int64, buf []byte) error {\n\tbinary.LittleEndian.PutUint64(buf, uint64(n))\n\t_, err := w.Write(buf)\n\treturn err\n}\n\nfunc (e *encoder) encode(rec *walpb.Record) error ", "output": "{\n\te.mu.Lock()\n\tdefer e.mu.Unlock()\n\n\te.crc.Write(rec.Data)\n\trec.Crc = e.crc.Sum32()\n\tvar (\n\t\tdata []byte\n\t\terr error\n\t\tn int\n\t)\n\n\tif rec.Size() > len(e.buf) {\n\t\tdata, err = rec.Marshal()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t} else {\n\t\tn, err = rec.MarshalTo(e.buf)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tdata = e.buf[:n]\n\t}\n\tif err := writeInt64(e.bw, int64(len(data)), e.uint64buf); err != nil {\n\t\treturn err\n\t}\n\t_, err = e.bw.Write(data)\n\treturn err\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\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 (m OptionManager) Query(ctx context.Context, name string) ([]types.BaseOptionValue, error) ", "output": "{\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}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/DataDog/datadog-go/statsd\"\n\n\tlog \"github.com/sirupsen/logrus\"\n)\n\n\n\nfunc (a *autographer) addStats(conf configuration) (err error) {\n\ta.stats, err = loadStatsd(conf)\n\tlog.Infof(\"Statsd enabled at %s with namespace %s\", conf.Statsd.Addr, conf.Statsd.Namespace)\n\treturn err\n}\n\nfunc loadStatsd(conf configuration) (*statsd.Client, error) ", "output": "{\n\tstatsdClient, err := statsd.NewBuffered(conf.Statsd.Addr, conf.Statsd.Buflen)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error constructing statsdClient: %w\", err)\n\t}\n\tstatsdClient.Namespace = conf.Statsd.Namespace\n\n\treturn statsdClient, 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\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 (c *Cooccurrence) EncodedMatrix() map[uint64]float64 ", "output": "{\n\treturn c.ma\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\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 (l Lists) Keep(filter func([]int) bool) Lists ", "output": "{\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}"} {"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\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\n\n\nfunc Test_container_fetch_gauge(t *testing.T) ", "output": "{\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}"} {"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\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\n\n\n\nfunc (response UpdateManagedListResponse) HTTPResponse() *http.Response {\n\treturn response.RawResponse\n}\n\nfunc (response UpdateManagedListResponse) String() string ", "output": "{\n\treturn common.PointerString(response)\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\n\n\n\nfunc (c *Config) GetNatsURI() string {\n\treturn os.Getenv(\"NATS_URI\")\n}\n\n\nfunc (c *Config) GetServerPort() (token string) {\n\treturn \"8080\"\n}\n\nfunc (c *Config) GetJWTToken() (token string, err error) ", "output": "{\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}"} {"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\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\n\n\n\nfunc (m *Mob) X_Process(delta gd.Double) {\n}\n\nfunc (m *Mob) X_OnVisibilityScreenExited() ", "output": "{\n\tm.QueueFree()\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\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\n\n\nfunc getClusterDomainName(r io.Reader) string ", "output": "{\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}"} {"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\n\n\n\nfunc (m *fake) GetSysctl(sysctl string) (int, error) {\n\tv, found := m.Settings[sysctl]\n\tif !found {\n\t\treturn -1, os.ErrNotExist\n\t}\n\treturn v, nil\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 NewFake() *fake ", "output": "{\n\treturn &fake{\n\t\tSettings: make(map[string]int),\n\t}\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\nfunc MountAt(prefix string, app *lib.SpruceApp) http.Handler {\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}\n\n\n\nfunc (m cmsManager) handler(w http.ResponseWriter, r *http.Request) ", "output": "{\n\n\tfmt.Fprintf(w, \"No rendering features enabled yet. Path: '%s'\", r.URL.Path)\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\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) PostprocessRpcParams() error ", "output": "{\n\treturn nil\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/kubernetes/pkg/apis/extensions\"\n\t\"k8s.io/kubernetes/pkg/genericapiserver/registry/generic\"\n\tgenericregistry \"k8s.io/kubernetes/pkg/genericapiserver/registry/generic/registry\"\n\t\"k8s.io/kubernetes/pkg/genericapiserver/registry/rest\"\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\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\tNewFunc: func() runtime.Object { return &extensions.Ingress{} },\n\t\tNewListFunc: func() runtime.Object { return &extensions.IngressList{} },\n\t\tObjectNameFunc: func(obj runtime.Object) (string, error) {\n\t\t\treturn obj.(*extensions.Ingress).Name, nil\n\t\t},\n\t\tPredicateFunc: ingress.MatchIngress,\n\t\tQualifiedResource: 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 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\nfunc NewErrorWithStatusCode(ae *proto.ActionableErr) *ErrDef {\n\treturn &ErrDef{\n\t\tae: ae,\n\t}\n}\n\n\n\nfunc IsSkaffoldErr(err error) bool ", "output": "{\n\tif _, ok := err.(Error); ok {\n\t\treturn true\n\t}\n\treturn false\n}"} {"input": "package util\n\nimport (\n\t\"github.com/astaxie/beego/cache\"\n)\n\n\n\nfunc CacheFile() ", "output": "{\n\tbm, err = cache.NewCache(\"file\", `{\"CachePath\":\"cache\",\"FileSuffix\":\".cache\",\"DirectoryLevel\":2,\"EmbedExpiry\":120}`)\n\tif nil != err {\n\t\tlog.Info(\"creat cache object is fail \")\n\t}\n\tbm.Put(\"astaxie\", 1, 120)\n\tlog.Info(\"----------xxxx---------\", bm.Get(\"astaxie\"))\n\tbm.IsExist(\"astaxie\")\n\tbm.Delete(\"astaxie\")\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\nfunc (impl) one() int {\n\treturn 1\n}\n\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) two() string ", "output": "{\n\treturn \"two\"\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\nfunc (n NoColorString) String() string {\n\treturn n.s\n}\n\n\n\nfunc (n NoColorString) ColorString() string ", "output": "{\n\treturn n.s\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\n\n\n\nfunc (d *Dao) SendMailAttach(filename string, subject string, send []string) (err error) {\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}\n\nfunc (d *Dao) SendMail(date time.Time, body string, subject string, send ...string) (err error) ", "output": "{\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}"} {"input": "package v1alpha2\n\nimport (\n\t\"k8s.io/kubernetes/pkg/api/v1\"\n\tmeta_v1 \"k8s.io/kubernetes/pkg/apis/meta/v1\"\n)\n\n\ntype Federation struct {\n\tmeta_v1.TypeMeta `json:\",inline\"`\n\tObjectMeta v1.ObjectMeta `json:\"metadata,omitempty\"`\n\n\tSpec FederationSpec `json:\"spec,omitempty\"`\n}\n\ntype FederationSpec struct {\n\tControllers []string `json:\"controllers,omitempty\"`\n\tMembers []string `json:\"members,omitempty\"`\n\n\tDNSName string `json:\"dnsName,omitempty\"`\n}\n\ntype FederationList struct {\n\tmeta_v1.TypeMeta `json:\",inline\"`\n\tmeta_v1.ListMeta `json:\"metadata,omitempty\"`\n\n\tItems []Federation `json:\"items\"`\n}\n\n\n\nfunc (f *Federation) Validate() error ", "output": "{\n\treturn nil\n}"} {"input": "package scriptbenchmark\n\nimport (\n\t\"github.com/robertkrimen/otto\"\n\t\"testing\"\n)\n\nfunc BenchmarkOttoCallAdd(b *testing.B) {\n\to := otto.New()\n\t_, err := o.Run(`\n\tfunction add(x, y) {\n\t\treturn x+y;\n\t}\n\t`)\n\tassert(b, err)\n\n\tb.ResetTimer()\n\tfor i := 0; i < b.N; i++ {\n\t\tvalue, err := o.Call(\"add\", nil, 21, 21)\n\t\tassert(b, err)\n\t\tfv, err := value.ToFloat()\n\t\tassert(b, err)\n\t\tassert(b, isTrue(\"add(21,21) == 42\", fv == 42))\n\t}\n}\n\n\n\nfunc BenchmarkOttoCallAddN(b *testing.B) ", "output": "{\n\to := otto.New()\n\t_, err := o.Run(`\n\tfunction add(x, y) {\n\t\treturn x+y;\n\t}\n\n\tfunction addn(n, x, y) {\n\t\tfor (var i = 0; i < n; i++) {\n\t\t\tadd(x, y);\n\t\t}\n\t\treturn n;\n\t}\n\t`)\n\tassert(b, err)\n\n\tb.ResetTimer()\n\n\tvalue, err := o.Call(\"addn\", nil, b.N, 21, 21)\n\tassert(b, err)\n\tfv, err := value.ToFloat()\n\tassert(b, err)\n\tassert(b, isTrue(\"addn(n,...) == n\", fv == float64(b.N)))\n}"} {"input": "package fileset\n\nimport(\n\t\"path/filepath\"\n)\n\n\n\n\n\n\n\nfunc filterEntryMap(entryMap EntryMap, patterns []string) (newEntryMap EntryMap) {\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}\n\nfunc (diff EntryMapDiff) Filter(patterns []string) (newDiff EntryMapDiff) ", "output": "{\n\tnewDiff.Added = filterEntryMap(diff.Added, patterns)\n\tnewDiff.Updated = filterEntryMap(diff.Updated, patterns)\n\tnewDiff.Removed = filterEntryMap(diff.Removed, patterns)\n\treturn\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\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 (l *caAiaMissing) CheckApplies(c *x509.Certificate) bool ", "output": "{\n\treturn util.IsCACert(c) && !util.IsRootCA(c)\n}"} {"input": "package strings\n\nimport (\n\t\"strings\"\n)\n\n\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\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 RemoveSpace(s string) (d string) ", "output": "{\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}"} {"input": "package handlers\n\nimport (\n\t\"fmt\"\n\t\"net/http\"\n)\n\n\n\nfunc RobotsHandler(w http.ResponseWriter, r *http.Request) ", "output": "{\n\tfmt.Fprint(w, \"User-agent: *\\nDisallow: /\")\n}"} {"input": "package server\n\nimport \"golang.org/x/crypto/bcrypt\"\n\n\n\n\n\n\nfunc MatchPassword(password string, hashedPassword string) (bool, error) {\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}\n\nfunc createHashedPassword(password string) (string, error) ", "output": "{\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}"} {"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\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 (b *callbackBehavior) Terminate() error ", "output": "{\n\treturn nil\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() {}\n\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 }\nfunc (is *InterpolatedString) String() string { return is.Token.Literal }\n\nfunc (s *StringLiteral) TokenLiteral() string ", "output": "{ return s.Token.Literal }"} {"input": "package compiler\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\n\t\"github.com/xenioplatform/go-xenio/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 main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"github.com/wrouesnel/tailio\"\n\t\"os\"\n)\n\n\n\nfunc main() {\n\tconfig, n := args2config()\n\tif flag.NFlag() < 1 {\n\t\tfmt.Println(\"need one or more files as arguments\")\n\t\tos.Exit(1)\n\t}\n\n\tif n != 0 {\n\t\tconfig.Location = &tailio.SeekInfo{-n, os.SEEK_END}\n\t}\n\n\tdone := make(chan bool)\n\tfor _, filename := range flag.Args() {\n\t\tgo tailFile(filename, config, done)\n\t}\n\n\tfor _, _ = range flag.Args() {\n\t\t<-done\n\t}\n}\n\nfunc tailFile(filename string, config tailio.Config, done chan bool) {\n\tdefer func() { done <- true }()\n\tt, err := tailio.TailFile(filename, config)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn\n\t}\n\tfor line := range t.Lines {\n\t\tfmt.Println(line.Text)\n\t}\n\terr = t.Wait()\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n}\n\nfunc args2config() (tailio.Config, int64) ", "output": "{\n\tconfig := tailio.Config{Follow: true}\n\tn := int64(0)\n\tmaxlinesize := int(0)\n\tflag.Int64Var(&n, \"n\", 0, \"tail from the last Nth location\")\n\tflag.IntVar(&maxlinesize, \"max\", 0, \"max line size\")\n\tflag.BoolVar(&config.Follow, \"f\", false, \"wait for additional data to be appended to the file\")\n\tflag.BoolVar(&config.ReOpen, \"F\", false, \"follow, and track file rename/rotation\")\n\tflag.BoolVar(&config.Poll, \"p\", false, \"use polling, instead of inotify\")\n\tflag.Parse()\n\tif config.ReOpen {\n\t\tconfig.Follow = true\n\t}\n\tconfig.MaxLineSize = maxlinesize\n\treturn config, n\n}"} {"input": "package server\n\nimport (\n\t\"github.com/labstack/echo\"\n\t\"net/http\"\n)\n\n\n\nfunc (s *Server) Githook(c echo.Context) error ", "output": "{\n\treturn c.String(http.StatusOK, \"Hello, World!\")\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\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 newClusterSubjectAccessReviews(c *Client) *clusterSubjectAccessReviews ", "output": "{\n\treturn &clusterSubjectAccessReviews{\n\t\tr: c,\n\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\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\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) Get(name string, options metav1.GetOptions) (*userapi.Identity, error) ", "output": "{\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}"} {"input": "package main\n\nimport (\n\t\"net/http\"\n)\n\n\n\nfunc domainClearHandler(w http.ResponseWriter, r *http.Request) {\n\ttype request struct {\n\t\tOwnerToken *string `json:\"ownerToken\"`\n\t\tDomain *string `json:\"domain\"`\n\t}\n\n\tvar x request\n\tif err := bodyUnmarshal(r, &x); err != nil {\n\t\tbodyMarshal(w, response{\"success\": false, \"message\": err.Error()})\n\t\treturn\n\t}\n\n\to, err := ownerGetByOwnerToken(*x.OwnerToken)\n\tif err != nil {\n\t\tbodyMarshal(w, response{\"success\": false, \"message\": err.Error()})\n\t\treturn\n\t}\n\n\tdomain := domainStrip(*x.Domain)\n\tisOwner, err := domainOwnershipVerify(o.OwnerHex, domain)\n\tif err != nil {\n\t\tbodyMarshal(w, response{\"success\": false, \"message\": err.Error()})\n\t\treturn\n\t}\n\n\tif !isOwner {\n\t\tbodyMarshal(w, response{\"success\": false, \"message\": errorNotAuthorised.Error()})\n\t\treturn\n\t}\n\n\tif err = domainClear(*x.Domain); err != nil {\n\t\tbodyMarshal(w, response{\"success\": false, \"message\": err.Error()})\n\t\treturn\n\t}\n\n\tbodyMarshal(w, response{\"success\": true})\n}\n\nfunc domainClear(domain string) error ", "output": "{\n\tif domain == \"\" {\n\t\treturn errorMissingField\n\t}\n\n\tstatement := `\n\t\tDELETE FROM votes\n\t\tUSING comments\n\t\tWHERE comments.commentHex = votes.commentHex AND comments.domain = $1;\n\t`\n\t_, err := db.Exec(statement, domain)\n\tif err != nil {\n\t\tlogger.Errorf(\"cannot delete votes: %v\", err)\n\t\treturn errorInternal\n\t}\n\n\tstatement = `\n\t\tDELETE FROM comments\n\t\tWHERE comments.domain = $1;\n\t`\n\t_, err = db.Exec(statement, domain)\n\tif err != nil {\n\t\tlogger.Errorf(statement, domain)\n\t\treturn errorInternal\n\t}\n\n\tstatement = `\n\t\tDELETE FROM pages\n\t\tWHERE pages.domain = $1;\n\t`\n\t_, err = db.Exec(statement, domain)\n\tif err != nil {\n\t\tlogger.Errorf(statement, domain)\n\t\treturn errorInternal\n\t}\n\n\treturn nil\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\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\n\n\nfunc computeHash(name string) string ", "output": "{\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}"} {"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\n\n\n\ntype NotifyArgs struct {\n Message string\n Title string\n Level string\n Duration string\n}\n\n\nfunc handleMessage (conn net.Conn, m svarmrgo.Message) {\n switch m.Selector {\n case \"reveal-yourself\" :\n\t\t\t m.Respond(svarmrgo.Message{Selector: \"announce\", Arg: \"user notifier\"})\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 runCommand (cmd *exec.Cmd, stdin io.Reader) bytes.Buffer", "output": "{\n\tcmd.Stdin = stdin\n\tvar out bytes.Buffer\n\tcmd.Stdout = &out\n\tcmd.Run()\n\treturn out\n}"} {"input": "package main\n\nimport (\n\t\"github.com/grd/iup\"\n\t\"fmt\"\n)\n\nvar someone *iup.Ihandle\n\nfunc nameKeyEntry(ih *iup.Ihandle, ch int, newValue string) int {\n\tfmt.Printf(\"Char Pressed: %d, New Value: %s\\n\", ch, newValue)\n\treturn 0\n}\n\nfunc sayHello(ih *iup.Ihandle) int {\n\tfmt.Printf(\"Hello, %s!\\n\", iup.GetAttribute(ih, \"TO_WHO\"))\n\treturn 0\n}\n\n\n\nfunc main() {\n\tiup.Open()\n\tdefer iup.Close()\n\n\tsomeone = iup.Text((iup.TextActionFunc)(nameKeyEntry))\n\thelloSomeone := iup.Button(\"Say Hello\",\n\t\t(iup.ActionFunc)(sayHelloToSomeone))\n\n\tline1 := iup.Hbox(iup.Label(\"Name:\"), someone, helloSomeone)\n\tiup.SetAttributes(line1, \"ALIGNMENT=ACENTER,GAP=5\")\n\n\thelloJohn := iup.Button(\"Hello John\",\n\t\t(iup.ActionFunc)(sayHello),\n\t\t\"TO_WHO=\\\"John Doe\\\"\")\n\n\thelloJim := iup.Button(\"Hello Jim\",\n\t\t(iup.ActionFunc)(sayHello),\n\t\t\"TO_WHO=\\\"Jim Doe\\\"\")\n\n\tline2 := iup.Hbox(iup.Label(\"Predefined greeters:\"), helloJohn, helloJim)\n\tiup.SetAttributes(line2, \"ALIGNMENT=ACENTER,GAP=5\")\n\n\tform := iup.Vbox(line1, line2)\n\tiup.SetAttributes(form, \"GAP=5,MARGIN=3x3\")\n\n\tdlg := iup.Dialog(form, \"TITLE=Greeter\")\n\tiup.Show(dlg)\n\n\tiup.MainLoop()\n}\n\nfunc sayHelloToSomeone(ih *iup.Ihandle) int ", "output": "{\n\tfmt.Printf(\"Hello, %s!\\n\", iup.GetAttribute(someone, \"VALUE\"))\n\treturn 0\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\nfunc TestN3(t *testing.T) {\n\tn := getTestObject()\n\tn.Print()\n\treturn\n}\n\n\n\nfunc TestWriteN3(t *testing.T) ", "output": "{\n\tn := getTestObject()\n\tn.WriteN3()\n\treturn\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\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 PK2(endpoint, counter string) string ", "output": "{\n\treturn fmt.Sprintf(\"%s/%s\", endpoint, counter)\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\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) IsIpv6() bool ", "output": "{\n\treturn false\n}"} {"input": "package introspect\n\nimport (\n\t\"encoding/xml\"\n\t\"strings\"\n\n\t\"github.com/godbus/dbus/v5\"\n)\n\n\n\n\n\nfunc Call(o dbus.BusObject) (*Node, error) ", "output": "{\n\tvar xmldata string\n\tvar node Node\n\n\terr := o.Call(\"org.freedesktop.DBus.Introspectable.Introspect\", 0).Store(&xmldata)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\terr = xml.NewDecoder(strings.NewReader(xmldata)).Decode(&node)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif node.Name == \"\" {\n\t\tnode.Name = string(o.Path())\n\t}\n\treturn &node, 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\n\n\nfunc TestConcurrent(t *testing.T) {\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}\n\nfunc BenchmarkGet(b *testing.B) ", "output": "{\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}"} {"input": "package main\n\nimport (\n\t\"net/http\"\n\t\"net/http/httptest\"\n\t\"testing\"\n)\n\n\n\nfunc TestApi(t *testing.T) {\n\tmux := Api{\n\t\tingestHandler: stubHandler(\"ingest\"),\n\t\tmetrictankHandler: stubHandler(\"metrictank\"),\n\t\tgraphiteHandler: stubHandler(\"graphite\"),\n\t\tbulkImportHandler: stubHandler(\"bulk-import\"),\n\t}.Mux()\n\n\ttype args struct {\n\t\tpath string\n\t\twant string\n\t}\n\n\ttests := []args{\n\t\t{\n\t\t\tpath: \"/\",\n\t\t\twant: \"graphite\",\n\t\t},\n\t\t{\n\t\t\tpath: \"/whatever\",\n\t\t\twant: \"graphite\",\n\t\t},\n\t\t{\n\t\t\tpath: \"/metrics/whatever\",\n\t\t\twant: \"graphite\",\n\t\t},\n\t\t{\n\t\t\tpath: \"/metrics\",\n\t\t\twant: \"ingest\",\n\t\t},\n\t\t{\n\t\t\tpath: \"/metrics/index.json\",\n\t\t\twant: \"metrictank\",\n\t\t},\n\t\t{\n\t\t\tpath: \"/metrics/delete\",\n\t\t\twant: \"metrictank\",\n\t\t},\n\t\t{\n\t\t\tpath: \"/metrics/import\",\n\t\t\twant: \"bulk-import\",\n\t\t},\n\t}\n\n\tfor _, test := range tests {\n\t\tt.Run(test.path, func(t *testing.T) {\n\t\t\trecorder := httptest.NewRecorder()\n\n\t\t\tmux.ServeHTTP(recorder, httptest.NewRequest(\"\", test.path, nil))\n\t\t\tsvc := recorder.Body.String()\n\t\t\tif svc != test.want {\n\t\t\t\tt.Errorf(\"want %s, got %s\", test.want, svc)\n\t\t\t}\n\t\t})\n\t}\n\n}\n\n\n\n\nfunc stubHandler(svc string) http.Handler ", "output": "{\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tw.Write([]byte(svc))\n\t})\n}"} {"input": "package allocator\n\nimport (\n\t\"math/big\"\n\t\"testing\"\n)\n\n\n\nfunc TestCountBits(t *testing.T) {\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}\n\nfunc TestBitCount(t *testing.T) ", "output": "{\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}"} {"input": "package cli\n\nimport \"fmt\"\n\n\n\nfunc Help() ", "output": "{\n fmt.Println(\"package cli\")\n fmt.Println(\"func RegArgs(args []string)\")\n fmt.Println(\"func UnRegArgs(list []string, args...int) (error)\")\n fmt.Println(\"func RegArgsStat(s string) int\")\n fmt.Println(\"func ClearArgsStat() error\")\n fmt.Println(\"func IsArgExist(args []string, s string)(bool)\")\n fmt.Println(\"func GetArgBool(args []string, s string)(bool)\")\n fmt.Println(\"func GetArgInt(args []string, s string)(int, error)\")\n fmt.Println(\"func GetArgInts(args []string, s string)([]int, error)\")\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\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 updateReferralTable(referral_id string) string", "output": "{\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}"} {"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\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\nfunc Register(codec uint64, decoder DecodeBlockFunc) {\n\tDefaultBlockDecoder.Register(codec, decoder)\n}\n\nfunc (d *safeBlockDecoder) Decode(block blocks.Block) (Node, error) ", "output": "{\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}"} {"input": "package codegen\n\nimport (\n\t\"bytes\"\n\t\"strings\"\n\t\"text/template\"\n)\n\nconst (\n\tcommentLinePrefix = \" \"\n)\n\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\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 applyTemplate(tmpl string, i interface{}) (string, error) ", "output": "{\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}"} {"input": "package to_spreadsheet\n\nimport \"testing\"\n\n\n\nfunc TestIsValidSpreadsheetId(t *testing.T) ", "output": "{\n\tif x := IsValidSpreadsheetId(\"1Kokm29I8he7mn7p9iE66veGwj8qyEpTtixv1ulbl7Tw\"); !x {\n\t\tt.Error(x)\n\t}\n\tif x := IsValidSpreadsheetId(\" \"); x {\n\t\tt.Error(x)\n\t}\n\tif x := IsValidSpreadsheetId(\"&redirect_uri=http%3A%2F%2Fexample.com\"); x {\n\t\tt.Error(x)\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\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) Len() int ", "output": "{\n\treturn len(b.backingSlice)\n}"} {"input": "package virtcontainers\n\ntype mockAddr struct {\n\tnetwork string\n\tipAddr string\n}\n\n\n\nfunc (m mockAddr) String() string {\n\treturn m.ipAddr\n}\n\nfunc (m mockAddr) Network() string ", "output": "{\n\treturn m.network\n}"} {"input": "package term\n\nimport (\n\t\"testing\"\n\n\t\"gotest.tools/assert\"\n\tis \"gotest.tools/assert/cmp\"\n)\n\n\n\nfunc TestToBytes(t *testing.T) ", "output": "{\n\tcodes, err := ToBytes(\"ctrl-a,a\")\n\tassert.NilError(t, err)\n\tassert.Check(t, is.DeepEqual([]byte{1, 97}, codes))\n\n\t_, err = ToBytes(\"shift-z\")\n\tassert.Check(t, is.ErrorContains(err, \"\"))\n\n\tcodes, err = ToBytes(\"ctrl-@,ctrl-[,~,ctrl-o\")\n\tassert.NilError(t, err)\n\tassert.Check(t, is.DeepEqual([]byte{0, 27, 126, 15}, codes))\n\n\tcodes, err = ToBytes(\"DEL,+\")\n\tassert.NilError(t, err)\n\tassert.Check(t, is.DeepEqual([]byte{127, 43}, codes))\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\nfunc Get(url string) {\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}\n\n\n\nfunc acceptableCharset(contentTypes []string) bool ", "output": "{\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}"} {"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\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\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) TouchPeer(pubkey *[ed25519.PublicKeySize]byte) ", "output": "{\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}"} {"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\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) Register(request *worker.RegisterRequest, stream Service_RegisterServer) error ", "output": "{\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}"} {"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\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\nfunc (SimpleSSLocator) DeleteOld(ctx context.Context, threshold int, dryRun bool) ([]string, error) {\n\treturn []string{}, nil\n}\n\nfunc generateBlobpath() string ", "output": "{\n\treturn fmt.Sprintf(\"%s_SimpleSSLocator\", metadata.INodeDBSnapshotBlobpathPrefix)\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\nfunc (a *GroupedAnimation) Reset() {\n\tfor _, animator := range a.animators {\n\t\tanimator.Reset()\n\t}\n}\n\n\n\nfunc (a *GroupedAnimation) Delete() ", "output": "{\n\tfor _, animator := range a.animators {\n\t\tanimator.Delete()\n\t}\n\ta.animators = []Animator{}\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\n\n\n\n\nfunc LogMessage(msg []byte, msgType events.LogMessage_MessageType) log_sender.LogChainer {\n\treturn logSender.LogMessage(msg, msgType)\n}\n\nfunc ScanErrorLogStream(appID, sourceType, sourceInstance string, reader io.Reader) ", "output": "{\n\tif logSender == nil {\n\t\treturn\n\t}\n\tlogSender.ScanErrorLogStream(appID, sourceType, sourceInstance, reader)\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\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\n\n\n\nfunc ReturnDomain(currentURL string) string {\n\turlParse, _ := url.Parse(currentURL)\n\tdomain := urlParse.Host\n\treturn domain\n}\n\nfunc StringInSlice(domain string, list []string) bool ", "output": "{\n\tfor _, eachDomain := range list {\n\t\tif domain == eachDomain {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}"} {"input": "package instancegroup\n\nimport (\n\tboshlog \"github.com/cloudfoundry/bosh-utils/logger\"\n\n\t\"bosh-google-cpi/google/operation_service\"\n\t\"google.golang.org/api/compute/v1\"\n)\n\nconst googleInstanceGroupServiceLogTag = \"GoogleInstanceGroupService\"\n\ntype GoogleInstanceGroupService struct {\n\tproject string\n\tcomputeService *compute.Service\n\toperationService operation.Service\n\tlogger boshlog.Logger\n}\n\n\n\nfunc NewGoogleInstanceGroupService(\n\tproject string,\n\tcomputeService *compute.Service,\n\toperationService operation.Service,\n\tlogger boshlog.Logger,\n) GoogleInstanceGroupService ", "output": "{\n\treturn GoogleInstanceGroupService{\n\t\tproject: project,\n\t\tcomputeService: computeService,\n\t\toperationService: operationService,\n\t\tlogger: logger,\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\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) Update(obj interface{}) error ", "output": "{\n\treturn fmt.Errorf(\"Not implemented yet\")\n}"} {"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\n\n\nfunc TestRules(t *testing.T) {\n\tRegisterFailHandler(Fail)\n\tjunitReporter := reporters.NewJUnitReporter(\"../report/routetable_suite.xml\")\n\tRunSpecsWithDefaultAndCustomReporters(t, \"RouteTable Suite\", []Reporter{junitReporter})\n}\n\nfunc init() ", "output": "{\n\ttestutils.HookLogrusForGinkgo()\n}"} {"input": "package dat\n\nimport (\n\t\"fmt\"\n\t\"strconv\"\n\n\t\"github.com/mgutz/logxi/v1\"\n)\n\nvar logger log.Logger\n\n\nvar Strict = false\n\n\nvar EnableInterpolation = false\n\n\nconst maxLookup = 100\n\n\nvar atoiTab = make(map[string]int, maxLookup)\n\n\nvar itoaTab = make([]string, maxLookup)\n\n\nvar placeholderTab = make([]string, maxLookup)\n\n\nvar equalsPlaceholderTab = make([]string, maxLookup)\n\n\nvar inPlaceholderTab = make([]string, maxLookup)\n\nvar identifierTab = make([]string, maxLookup)\n\n\n\nfunc init() ", "output": "{\n\tfor i := 0; i < maxLookup; i++ {\n\t\tplaceholderTab[i] = fmt.Sprintf(\"$%d\", i)\n\t\tinPlaceholderTab[i] = fmt.Sprintf(\" IN $%d\", i)\n\t\tequalsPlaceholderTab[i] = fmt.Sprintf(\" = $%d\", i)\n\t\tatoiTab[strconv.Itoa(i)] = i\n\t\titoaTab[i] = strconv.Itoa(i)\n\t\tidentifierTab[i] = fmt.Sprintf(\"dat%d\", i)\n\t}\n\n\tlogger = log.New(\"dat\")\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\nfunc (l *ScopedLogger) Fatalf(format string, args ...interface{}) {\n\tl.log.Fatalf(l.fmt, l.scp, fmt.Sprintf(format, args...))\n}\n\n\n\nfunc intToStringWithSign(i int) string ", "output": "{\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}"} {"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\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 (report *TorrentReport) ToJson() TorrentReportJson ", "output": "{\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}"} {"input": "package main\n\nimport (\n\t\"bitbucket.org/liamstask/goose/lib/goose\"\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"time\"\n)\n\nvar createCmd = &Command{\n\tName: \"create\",\n\tUsage: \"\",\n\tSummary: \"Create the scaffolding for a new migration\",\n\tHelp: `create extended help here...`,\n\tRun: createRun,\n}\n\n\n\nfunc createRun(cmd *Command, args ...string) ", "output": "{\n\n\tif len(args) < 1 {\n\t\tlog.Fatal(\"goosees create: migration name required\")\n\t}\n\n\tmigrationType := \"go\" \n\tif len(args) >= 2 {\n\t\tmigrationType = args[1]\n\t}\n\n\tconfs, err := loadConfig()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tconf := confs[0]\n\n\tif err = os.MkdirAll(conf.MigrationsDir, 0777); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tn, err := goose.CreateMigration(args[0], migrationType, conf.MigrationsDir, time.Now())\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\ta, e := filepath.Abs(n)\n\tif e != nil {\n\t\tlog.Fatal(e)\n\t}\n\n\tfmt.Println(\"goosees: created\", a)\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\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 SetupSignalHandlerIgnoringFurtherSignals() <-chan struct{} ", "output": "{\n\treturn SetupSignalContextNotExiting().Done()\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\n\n\nfunc TestGetNamespace(t *testing.T) {\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}\n\nfunc getTestNamespaceAPI(t *testing.T) (*NamespaceAPI, func()) ", "output": "{\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}"} {"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\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\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}"} {"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\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) Expires() time.Time ", "output": "{\n\treturn vp.expires\n}"} {"input": "package dynaml\n\nimport (\n\t\"fmt\"\n)\n\ntype BooleanExpr struct {\n\tValue bool\n}\n\nfunc (e BooleanExpr) Evaluate(binding Binding, locally bool) (interface{}, EvaluationInfo, bool) {\n\treturn e.Value, DefaultInfo(), true\n}\n\n\n\nfunc (e BooleanExpr) String() string ", "output": "{\n\treturn fmt.Sprintf(\"%v\", e.Value)\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\n\n\nfunc TestRangeFilterWithFormat(t *testing.T) {\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}\n\nfunc TestRangeFilterWithTimeZone(t *testing.T) ", "output": "{\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}"} {"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\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\n\n\nfunc (p BackingProcess) Delete() error ", "output": "{\n\t_, err := p.containerdProcess.Delete(p.context)\n\treturn err\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\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) BinaryRequestBody() (*common.OCIReadSeekCloser, bool) ", "output": "{\n\n\treturn nil, false\n\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\n\n\n\nfunc (h *cmdHandler) handleError(err error) {\n\tfmt.Println(err)\n}\n\nfunc (h *cmdHandler) handleUsageError(message string) ", "output": "{\n\tfmt.Println(message)\n\th.PrintUsage()\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\nfunc (f *EnumFlag) IsSet() bool {\n\treturn f.i != -1\n}\n\n\n\n\n\nfunc (f *EnumFlag) Set(s string) error ", "output": "{\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}"} {"input": "package cloudfoundry\n\nimport (\n\t\"github.com/enaml-ops/enaml\"\n\t\"github.com/enaml-ops/omg-product-bundle/products/oss_cf/enaml-gen/proxy\"\n\t\"github.com/enaml-ops/omg-product-bundle/products/oss_cf/plugin/config\"\n)\n\n\ntype MySQLProxy struct {\n\tConfig *config.Config\n}\n\n\nfunc NewMySQLProxyPartition(config *config.Config) InstanceGroupCreator {\n\treturn &MySQLProxy{\n\t\tConfig: config,\n\t}\n}\n\n\n\n\nfunc (s *MySQLProxy) newMySQLProxyJob() enaml.InstanceJob {\n\treturn enaml.InstanceJob{\n\t\tName: \"proxy\",\n\t\tRelease: \"cf-mysql\",\n\t\tProperties: &proxy.ProxyJob{\n\t\t\tCfMysql: &proxy.CfMysql{\n\t\t\t\tExternalHost: s.Config.MySQLProxyExternalHost,\n\t\t\t\tProxy: &proxy.Proxy{\n\t\t\t\t\tApiUsername: s.Config.MySQLProxyAPIUsername,\n\t\t\t\t\tApiPassword: s.Config.MySQLProxyAPIPassword,\n\t\t\t\t\tProxyIps: s.Config.MySQLProxyIPs,\n\t\t\t\t},\n\t\t\t\tMysql: &proxy.Mysql{\n\t\t\t\t\tClusterIps: s.Config.MySQLIPs,\n\t\t\t\t},\n\t\t\t},\n\t\t\tSyslogAggregator: &proxy.SyslogAggregator{\n\t\t\t\tAddress: s.Config.SyslogAddress,\n\t\t\t\tPort: s.Config.SyslogPort,\n\t\t\t\tTransport: s.Config.SyslogTransport,\n\t\t\t},\n\t\t\tNats: &proxy.Nats{\n\t\t\t\tUser: s.Config.NATSUser,\n\t\t\t\tPassword: s.Config.NATSPassword,\n\t\t\t\tMachines: s.Config.NATSMachines,\n\t\t\t\tPort: s.Config.NATSPort,\n\t\t\t},\n\t\t},\n\t}\n}\n\nfunc (s *MySQLProxy) ToInstanceGroup() (ig *enaml.InstanceGroup) ", "output": "{\n\tig = &enaml.InstanceGroup{\n\t\tName: \"mysql_proxy-partition\",\n\t\tInstances: len(s.Config.MySQLProxyIPs),\n\t\tVMType: s.Config.MySQLProxyVMType,\n\t\tAZs: s.Config.AZs,\n\t\tStemcell: s.Config.StemcellName,\n\t\tJobs: []enaml.InstanceJob{\n\t\t\ts.newMySQLProxyJob(),\n\t\t},\n\t\tNetworks: []enaml.Network{\n\t\t\tenaml.Network{Name: s.Config.NetworkName, StaticIPs: s.Config.MySQLProxyIPs},\n\t\t},\n\t\tUpdate: enaml.Update{\n\t\t\tMaxInFlight: 1,\n\t\t},\n\t}\n\treturn\n}"} {"input": "package mutate\n\nimport (\n\tv1 \"github.com/google/go-containerregistry/pkg/v1\"\n\t\"github.com/google/go-containerregistry/pkg/v1/empty\"\n\t\"github.com/google/go-containerregistry/pkg/v1/mutate\"\n\t\"github.com/sigstore/cosign/pkg/oci\"\n)\n\n\n\nfunc AppendSignatures(base oci.Signatures, sigs ...oci.Signature) (oci.Signatures, error) {\n\tadds := make([]mutate.Addendum, 0, len(sigs))\n\tfor _, sig := range sigs {\n\t\tann, err := sig.Annotations()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tadds = append(adds, mutate.Addendum{\n\t\t\tLayer: sig,\n\t\t\tAnnotations: ann,\n\t\t})\n\t}\n\timg, err := mutate.Append(base, adds...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &sigAppender{\n\t\tImage: img,\n\t\tbase: base,\n\t\tsigs: sigs,\n\t}, nil\n}\n\n\n\n\n\ntype sigAppender struct {\n\tv1.Image\n\tbase oci.Signatures\n\tsigs []oci.Signature\n}\n\nvar _ oci.Signatures = (*sigAppender)(nil)\n\n\nfunc (sa *sigAppender) Get() ([]oci.Signature, error) {\n\tsl, err := sa.base.Get()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn append(sl, sa.sigs...), nil\n}\n\nfunc ReplaceSignatures(base oci.Signatures) (oci.Signatures, error) ", "output": "{\n\tsigs, err := base.Get()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tadds := make([]mutate.Addendum, 0, len(sigs))\n\tfor _, sig := range sigs {\n\t\tann, err := sig.Annotations()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tadds = append(adds, mutate.Addendum{\n\t\t\tLayer: sig,\n\t\t\tAnnotations: ann,\n\t\t})\n\t}\n\timg, err := mutate.Append(empty.Image, adds...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &sigAppender{\n\t\tImage: img,\n\t\tbase: base,\n\t\tsigs: sigs,\n\t}, nil\n}"} {"input": "package configtx\n\nimport (\n\t\"testing\"\n\n\t\"github.com/hyperledger/fabric/common/configtx\"\n)\n\nfunc TestConfigtxInitializerInterface(t *testing.T) {\n\t_ = configtx.Initializer(&Initializer{})\n}\n\n\n\nfunc TestConfigtxManagerInterface(t *testing.T) ", "output": "{\n\t_ = configtx.Manager(&Manager{})\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\n\n\nfunc (s *StepImport) Cleanup(state multistep.StateBag) {\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}\n\nfunc (s *StepImport) Run(state multistep.StateBag) multistep.StepAction ", "output": "{\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}"} {"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\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\n\n\nfunc (r *RelationUnitShim) Relation() Relation ", "output": "{\n\treturn &relationShim{r.RelationUnit.Relation()}\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}\nfunc (m *MockStats) Emit(req *http.Request, dur time.Duration) {\n\tm.Called(req, dur)\n}\n\n\nfunc (m *MockStats) RequestTimeout(req *http.Request, timeout time.Duration) ", "output": "{\n\tm.Called(req, timeout)\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\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 RespondWithNotFoundError(w http.ResponseWriter, errMsg string) ", "output": "{\n\tRespondWithError(w, http.StatusNotFound, errMsg)\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\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 (w *debugWrapper) Close() error ", "output": "{\n\treturn w.conn.Close()\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\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 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\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 (c StringKeyValueMap) IsContain(key string) bool ", "output": "{\n\t_, ok := c[key]\n\treturn ok\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\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\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) AWSCloudFormationType() string ", "output": "{\n\treturn \"AWS::AmazonMQ::Configuration.TagsEntry\"\n}"} {"input": "package spatial\n\nimport \"fmt\"\n\n\n\nfunc (l Line) string() string {\n\ts := \"\"\n\tfor _, point := range l {\n\t\ts += fmt.Sprintf(\"%v, \", point)\n\t}\n\treturn s[:len(s)-2]\n}\n\nfunc (p Polygon) string() string ", "output": "{\n\ts := \"(\"\n\tfor _, line := range p {\n\t\ts += fmt.Sprintf(\"%v, \", line)\n\t}\n\treturn s[:len(s)-2] + \")\"\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\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) SetUpdateType(value string) ", "output": "{\n\ts.UpdateType = (*StatementUpdateTypeCode)(&value)\n}"} {"input": "package osc\n\nimport (\n\t\"testing\"\n\n\t\"github.com/hashicorp/terraform/helper/resource\"\n)\n\n\n\nfunc TestAccAWSCustomerGateway_importBasic(t *testing.T) ", "output": "{\n\tresourceName := \"aws_customer_gateway.foo\"\n\n\tresource.Test(t, resource.TestCase{\n\t\tPreCheck: func() { testAccPreCheck(t) },\n\t\tProviders: testAccProviders,\n\t\tCheckDestroy: testAccCheckCustomerGatewayDestroy,\n\t\tSteps: []resource.TestStep{\n\t\t\tresource.TestStep{\n\t\t\t\tConfig: testAccCustomerGatewayConfig,\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 goparser\n\nimport (\n\t\"strings\"\n)\n\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}\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 isExceptedStatement(name string, prefixs, suffixs, fullnames []string) bool ", "output": "{\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}"} {"input": "package ir\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"strings\"\n)\n\n\n\n\n\nfunc AttrToPythonValue(attr interface{}) string {\n\tswitch a := attr.(type) {\n\tcase bool:\n\t\treturn strings.Title(fmt.Sprintf(\"%v\", a))\n\tcase int:\n\t\treturn fmt.Sprintf(\"%d\", a)\n\tcase int64:\n\t\treturn fmt.Sprintf(\"%d\", a)\n\tcase float32:\n\t\treturn fmt.Sprintf(\"%f\", a)\n\tcase float64: \n\t\treturn fmt.Sprintf(\"%f\", attr.(float64))\n\tcase []int:\n\t\tif a == nil {\n\t\t\treturn \"None\"\n\t\t}\n\t\tintArrayAttrStr, _ := MarshalToJSONString(a)\n\t\treturn intArrayAttrStr\n\tcase []string:\n\t\tif a == nil {\n\t\t\treturn \"None\"\n\t\t}\n\t\tif len(a) == 0 {\n\t\t\treturn \"[]\"\n\t\t}\n\t\tstringListStr, _ := MarshalToJSONString(a)\n\t\treturn stringListStr\n\tcase []interface{}:\n\t\tif a == nil {\n\t\t\treturn \"None\"\n\t\t}\n\t\tif len(a) > 0 {\n\t\t\tif _, ok := a[0].(int); ok {\n\t\t\t\tintlist := []int{}\n\t\t\t\tfor _, v := range a {\n\t\t\t\t\tintlist = append(intlist, v.(int))\n\t\t\t\t}\n\t\t\t\tintlistStr, _ := MarshalToJSONString(intlist)\n\t\t\t\treturn intlistStr\n\t\t\t}\n\t\t}\n\t\treturn \"[]\"\n\tcase string:\n\t\treturn fmt.Sprintf(`\"%s\"`, a)\n\tdefault:\n\t\treturn \"\"\n\t}\n}\n\n\nfunc MarshalToJSONString(in interface{}) (string, error) {\n\tbytes, err := json.Marshal(in)\n\treturn string(bytes), err\n}\n\nfunc DTypeToString(dt int) string ", "output": "{\n\tswitch dt {\n\tcase Float:\n\t\treturn \"float32\"\n\tcase Int:\n\t\treturn \"int64\"\n\tcase String:\n\t\treturn \"string\"\n\tdefault:\n\t\treturn \"\"\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\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\nfunc (r *AWSIoTAnalyticsPipeline_Channel) SetDeletionPolicy(policy policies.DeletionPolicy) {\n\tr._deletionPolicy = policy\n}\n\nfunc (r *AWSIoTAnalyticsPipeline_Channel) DependsOn() []string ", "output": "{\n\treturn r._dependsOn\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\nfunc (a *AcceptorCompletionAdviceV02) AddCompletionAdvice() *iso20022.AcceptorCompletionAdvice2 {\n\ta.CompletionAdvice = new(iso20022.AcceptorCompletionAdvice2)\n\treturn a.CompletionAdvice\n}\n\n\n\nfunc (a *AcceptorCompletionAdviceV02) AddSecurityTrailer() *iso20022.ContentInformationType6 ", "output": "{\n\ta.SecurityTrailer = new(iso20022.ContentInformationType6)\n\treturn a.SecurityTrailer\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\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\nfunc (response ListTaggingWorkRequestErrorsResponse) HTTPResponse() *http.Response {\n\treturn response.RawResponse\n}\n\nfunc (request ListTaggingWorkRequestErrorsRequest) String() string ", "output": "{\n\treturn common.PointerString(request)\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\nfunc (f *flagStringSlice) String() string {\n\treturn fmt.Sprintf(\"%v\", *f)\n}\n\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) Set(value string) error ", "output": "{\n\t*f = append(*f, value)\n\treturn nil\n}"} {"input": "package multiwriter\n\nimport (\n\t\"io\"\n)\n\n\ntype multiWriter []io.Writer\n\n\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\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 New(w ...io.Writer) io.Writer ", "output": "{\n\treturn multiWriter(w)\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\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) UnsubscribeRoom(shard, room string) error ", "output": "{\n\treturn ws.Unsubscribe(fmt.Sprintf(roomFormat, shard, room))\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\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\n\n\nfunc (tree *Node) Prev() *Node ", "output": "{\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}"} {"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\nfunc isPalindrome(n int) bool {\n\treturn n == reverse(n)\n}\n\n\n\nfunc p4() int ", "output": "{\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}"} {"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\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\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 WithClientConfig(cc constant.ClientConfig) 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, configKey{}, cc)\n\t}\n}"} {"input": "package utils\n\nimport (\n\t\"math\"\n\t\"strconv\"\n\t\"strings\"\n\t\"unicode\"\n\n\t\"github.com/juju/errors\"\n)\n\n\n\n\n\n\nfunc ParseSize(str string) (MB uint64, err error) {\n\ti := strings.IndexFunc(str, func(r rune) bool {\n\t\treturn r != '.' && !unicode.IsDigit(r)\n\t})\n\tvar multiplier float64 = 1\n\tif i > 0 {\n\t\tsuffix := str[i:]\n\t\tmultiplier = 0\n\t\tfor j := 0; j < len(sizeSuffixes); j++ {\n\t\t\tbase := string(sizeSuffixes[j])\n\t\t\tswitch suffix {\n\t\t\tcase base, base + \"B\", base + \"iB\":\n\t\t\t\tmultiplier = float64(sizeSuffixMultiplier(j))\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif multiplier == 0 {\n\t\t\treturn 0, errors.Errorf(\"invalid multiplier suffix %q, expected one of %s\", suffix, []byte(sizeSuffixes))\n\t\t}\n\t\tstr = str[:i]\n\t}\n\n\tval, err := strconv.ParseFloat(str, 64)\n\tif err != nil || val < 0 {\n\t\treturn 0, errors.Errorf(\"expected a non-negative number, got %q\", str)\n\t}\n\tval *= multiplier\n\treturn uint64(math.Ceil(val)), nil\n}\n\nvar sizeSuffixes = \"MGTPEZY\"\n\n\n\nfunc sizeSuffixMultiplier(i int) int ", "output": "{\n\treturn 1 << uint(i*10)\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\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 (m *Deployment) AsExtnV1B1Deployment() (*api_extn_v1beta1.Deployment, error) ", "output": "{\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}"} {"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\nfunc (em *EventsMock) Header(header types.Hash) {\n\tem.Called(header)\n}\n\n\n\n\nfunc (em *EventsMock) Transaction(transaction types.Hash) ", "output": "{\n\tem.Called(transaction)\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\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 (this *DB) Open() (err error) ", "output": "{\n\tthis.DataBase, err = sql.Open(this.DriverName, this.DriverSourceName)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\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\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) SoMsg(msg string, actual interface{},\n\tassert func(actual interface{}, expected ...interface{}) string, expected ...interface{}) ", "output": "{\n\tc.Lock()\n\tdefer c.Unlock()\n\tc.C.SoMsg(msg, actual, assert, expected...)\n}"} {"input": "package platform\n\nvar IsPartnerBuild = true\n\nfunc GuessMimeType(absPath string) (mimeType string, err error) {\n\treturn \"mime type disabled\", nil\n}\n\n\n\nfunc GuessMimeTypeByBuffer(buf []byte) (mimeType string, err error) ", "output": "{\n\treturn \"mime type disabled\", 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\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\nfunc (connectRequest *ConnectRequest) State() ConnectState {\n\tconnectRequest.lock.RLock()\n\tdefer connectRequest.lock.RUnlock()\n\treturn connectRequest.state\n}\n\n\nfunc (connectRequest *ConnectRequest) String() string ", "output": "{\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}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\n\t\"github.com/jackytck/projecteuler/tools\"\n)\n\nfunc match(p, s string) bool {\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}\n\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 check(p string, log []string) bool ", "output": "{\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}"} {"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\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\n\n\nfunc (q *queryNode) addOptions() ", "output": "{\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}"} {"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 }\n\nfunc (r n) M10() int { return a.G10 }\n\nfunc (r n) M9() int ", "output": "{ return a.G9 }"} {"input": "package loadbalancer\n\nimport (\n\t\"github.com/oracle/oci-go-sdk/common\"\n)\n\n\n\n\n\ntype WorkRequest struct {\n\tErrorDetails []WorkRequestError `mandatory:\"true\" json:\"errorDetails\"`\n\n\tId *string `mandatory:\"true\" json:\"id\"`\n\n\tLifecycleState WorkRequestLifecycleStateEnum `mandatory:\"true\" json:\"lifecycleState\"`\n\n\tLoadBalancerId *string `mandatory:\"true\" json:\"loadBalancerId\"`\n\n\tMessage *string `mandatory:\"true\" json:\"message\"`\n\n\tTimeAccepted *common.SDKTime `mandatory:\"true\" json:\"timeAccepted\"`\n\n\tType *string `mandatory:\"true\" json:\"type\"`\n\n\tTimeFinished *common.SDKTime `mandatory:\"false\" json:\"timeFinished\"`\n}\n\n\n\n\ntype WorkRequestLifecycleStateEnum string\n\n\nconst (\n\tWorkRequestLifecycleStateAccepted WorkRequestLifecycleStateEnum = \"ACCEPTED\"\n\tWorkRequestLifecycleStateInProgress WorkRequestLifecycleStateEnum = \"IN_PROGRESS\"\n\tWorkRequestLifecycleStateFailed WorkRequestLifecycleStateEnum = \"FAILED\"\n\tWorkRequestLifecycleStateSucceeded WorkRequestLifecycleStateEnum = \"SUCCEEDED\"\n)\n\nvar mappingWorkRequestLifecycleState = map[string]WorkRequestLifecycleStateEnum{\n\t\"ACCEPTED\": WorkRequestLifecycleStateAccepted,\n\t\"IN_PROGRESS\": WorkRequestLifecycleStateInProgress,\n\t\"FAILED\": WorkRequestLifecycleStateFailed,\n\t\"SUCCEEDED\": WorkRequestLifecycleStateSucceeded,\n}\n\n\nfunc GetWorkRequestLifecycleStateEnumValues() []WorkRequestLifecycleStateEnum {\n\tvalues := make([]WorkRequestLifecycleStateEnum, 0)\n\tfor _, v := range mappingWorkRequestLifecycleState {\n\t\tvalues = append(values, v)\n\t}\n\treturn values\n}\n\nfunc (m WorkRequest) String() string ", "output": "{\n\treturn common.PointerString(m)\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\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) WithHashKey(key []byte) *AuthTest ", "output": "{\n\tr.hashKey = key\n\treturn r\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\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\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 TestCreateExtraVarsNilParameters(t *testing.T) ", "output": "{\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}"} {"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\nfunc (n *NullBool) MarshalJSON() ([]byte, error) {\n\tif !n.Valid {\n\t\treturn []byte(\"null\"), nil\n\t}\n\treturn json.Marshal(n.Bool)\n}\n\n\n\n\nfunc (n *NullBool) UnmarshalJSON(b []byte) error ", "output": "{\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}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"net/http\"\n)\n\n\ntype HandlerFunc func(http.ResponseWriter, *http.Request) (int, error)\n\n\nfunc (s *server) routes(mux *http.ServeMux) {\n\tmux.HandleFunc(\"/\", s.handlerWrapper(handleProcess)) \n\tmux.HandleFunc(fmt.Sprintf(\"/api/v%s/nodeInfo\", apiVersion), s.handlerWrapper(handleProcess)) \n}\n\n\n\n\nfunc (s *server) handlerWrapper(h HandlerFunc) http.HandlerFunc ", "output": "{\n\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\n\t\tw.Header().Set(\"Content-Type\", \"application/json\")\n\n\t\tstatus, err := h(w, r)\n\n\t\tvar errMsg string\n\n\t\tif err != nil {\n\t\t\tw.Write([]byte(\"{\\\"message\\\": \\\"An unknown error occurred\\\"}\"))\n\t\t\terrMsg = err.Error()\n\t\t}\n\n\t\tlog.Printf(\"%s %s %s %d %s\", r.RemoteAddr, r.Method, r.URL, status, errMsg)\n\n\t}\n\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\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 HttpError(w http.ResponseWriter, code int) ", "output": "{\n\thttp.Error(w, http.StatusText(code), code)\n}"} {"input": "package parser\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"path\"\n\t\"strings\"\n)\n\n\n\nfunc getPkgPath(fname string, isDir bool) (string, error) {\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}\n\nfunc normalizePath(path string) string ", "output": "{\n\treturn strings.Replace(path, \"\\\\\", \"/\", -1)\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\n\n\n\n\nfunc (t *SuiteSuite) VerifyMethodsWrongSignatureSkipped1(x int) {\n\tt.Fatalf(\"This should never run.\")\n}\n\n\n\nfunc (t *SuiteSuite) VerifyMethodsWrongSignatureSkipped2() int {\n\tt.Fatalf(\"This should never run.\")\n\treturn 0\n}\n\nfunc (t *SuiteSuite) TestInfof() ", "output": "{\n\tt.Infof(\"This is a log statement produced by t.Infof\")\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\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\n\n\nfunc (o *VPCDHCPOptionsAssociation) String() string ", "output": "{\n\treturn fi.TaskAsString(o)\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\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\n\n\nfunc NewTimeoutConn(c net.Conn, readTimeout, writeTimeout time.Duration) *TimeoutConn ", "output": "{\n\treturn &TimeoutConn{\n\t\tQuirkConn: QuirkConn{Conn: c},\n\t\treadTimeout: readTimeout,\n\t\twriteTimeout: writeTimeout,\n\t}\n}"} {"input": "package utils\n\nimport (\n\t\"testing\"\n)\n\n\n\nfunc TestStringSlicesEqualIgnoreOrder(t *testing.T) {\n\ttests := []struct {\n\t\tl []string\n\t\tr []string\n\t\texpected bool\n\t}{\n\t\t{\n\t\t\tl: []string{\"a\", \"b\"},\n\t\t\tr: []string{\"a\"},\n\t\t\texpected: false,\n\t\t},\n\t\t{\n\t\t\tl: []string{\"a\", \"b\"},\n\t\t\tr: []string{\"a\", \"c\"},\n\t\t\texpected: false,\n\t\t},\n\t\t{\n\t\t\tl: []string{\"a\", \"b\"},\n\t\t\tr: []string{\"b\", \"a\"},\n\t\t\texpected: true,\n\t\t},\n\t}\n\n\tfor _, test := range tests {\n\t\tresult := StringSlicesEqualIgnoreOrder(test.l, test.r)\n\t\tif test.expected != result {\n\t\t\tt.Errorf(\"Expected %v, got %v\", test.expected, result)\n\t\t}\n\t}\n}\n\nfunc TestStringSlicesEqual(t *testing.T) ", "output": "{\n\ttests := []struct {\n\t\tl []string\n\t\tr []string\n\t\texpected bool\n\t}{\n\t\t{\n\t\t\tl: []string{\"a\", \"b\"},\n\t\t\tr: []string{\"a\"},\n\t\t\texpected: false,\n\t\t},\n\t\t{\n\t\t\tl: []string{\"a\", \"b\"},\n\t\t\tr: []string{\"a\", \"c\"},\n\t\t\texpected: false,\n\t\t},\n\t\t{\n\t\t\tl: []string{\"a\", \"b\"},\n\t\t\tr: []string{\"a\", \"b\"},\n\t\t\texpected: true,\n\t\t},\n\t}\n\n\tfor _, test := range tests {\n\t\tresult := StringSlicesEqual(test.l, test.r)\n\t\tif test.expected != result {\n\t\t\tt.Errorf(\"Expected %v, got %v\", test.expected, result)\n\t\t}\n\t}\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\n\n\n\nfunc (t Timestamp) Equal(u Timestamp) bool {\n\treturn t.Time.Equal(u.Time)\n}\n\nfunc (t *Timestamp) UnmarshalJSON(data []byte) (err error) ", "output": "{\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}"} {"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\n\n\nfunc (err *loadError) Error() string {\n\treturn fmt.Sprintf(\"LoadError: cannot load such file -- %s\\n%s\", err.filename, err.callstack)\n}\n\nfunc (err *loadError) String() string ", "output": "{\n\treturn \"LoadError\"\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\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\n\n\nfunc (c *baseConfigurer) IsCloudArchivePackage(pack string) bool ", "output": "{\n\t_, ok := c.cloudArchivePackages[pack]\n\treturn ok\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\n\n\nfunc (this *ScriptReloaderHandler) ServeHTTP(res http.ResponseWriter, req *http.Request) {\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}\n\nfunc NewScriptReloaderHandler() *ScriptReloaderHandler {\n\treturn new(ScriptReloaderHandler)\n}\n\nfunc (this ScriptInjectResponseWriter) Write(data []byte) (int, error) ", "output": "{\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}"} {"input": "package main\n\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\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 f1(i int) ", "output": "{\n\tfor j := i - 1; j >= 0; j-- { \n\t}\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\nfunc Groups(w http.ResponseWriter, r *http.Request, u *mdl.User) error {\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}\n\n\n\n\n\nfunc formatGroupsJSON(groups []*mdl.Tgroup) []GroupJSON ", "output": "{\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}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"strings\"\n\n\t\"github.com/labstack/echo\"\n\n\t\"github.com/golang-devops/go-psexec/shared/dtos\"\n)\n\n\n\nfunc (h *handler) handleStatsFunc(c echo.Context) error ", "output": "{\n\tpath := c.QueryParam(\"path\")\n\tif strings.TrimSpace(path) == \"\" {\n\t\treturn fmt.Errorf(\"Request does not contain query 'path' value\")\n\t}\n\n\tinfo, err := os.Stat(path)\n\tif err != nil {\n\t\tif os.IsNotExist(err) {\n\t\t\treturn c.JSON(200, &dtos.StatsDto{\n\t\t\t\tPath: path,\n\t\t\t\tExists: false,\n\t\t\t})\n\t\t}\n\t\treturn fmt.Errorf(\"Unable to get stats of path '%s', error: %s\", path, err.Error())\n\t}\n\n\treturnDto := &dtos.StatsDto{\n\t\tPath: path,\n\t\tExists: true,\n\t\tIsDir: info.IsDir(),\n\t\tModTime: info.ModTime(),\n\t\tMode: info.Mode(),\n\t\tSize: info.Size(),\n\t}\n\treturn c.JSON(200, returnDto)\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\nfunc (g *Graph) AddEdge(u, v int) {\n\tg.addSingleEdge(u, v)\n\tg.addSingleEdge(v, u)\n}\n\n\n\nfunc (g *Graph) Adjacent(u int) <-chan int ", "output": "{\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}"} {"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\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\nfunc Mode() string {\n\treturn mode_name\n}\n\nfunc init() ", "output": "{\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}"} {"input": "package sysfs\n\nimport (\n\t\"path/filepath\"\n\t\"testing\"\n)\n\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\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 TestGetRaplZones(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}"} {"input": "package client\n\nimport (\n\t\"context\"\n\t\"time\"\n\n\t\"github.com/micro/micro/v3/util/backoff\"\n)\n\ntype BackoffFunc func(ctx context.Context, req Request, attempts int) (time.Duration, error)\n\n\n\nfunc exponentialBackoff(ctx context.Context, req Request, attempts int) (time.Duration, error) ", "output": "{\n\treturn backoff.Do(attempts), nil\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\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) Nodes() []*Node ", "output": "{\n\treturn c.nodes\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\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 NewForConfigOrDie(c *rest.Config) *SchedulingV1beta1Client ", "output": "{\n\tclient, err := NewForConfig(c)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn client\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\n\n\nfunc getProblems(input *utils.Input) []*Problem {\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}\n\nfunc (problem *Problem) Solve() string ", "output": "{\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}"} {"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\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) Do(op set.Op, t Set) Set ", "output": "{\n\tdata := append(s, t...)\n\tn := op(data, len(s))\n\treturn data[:n]\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\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) SetFrequency(value string) ", "output": "{\n\ts.Frequency = (*EventFrequency1Code)(&value)\n}"} {"input": "package app\n\nimport (\n\t\"github.com/tsuru/tsuru/quota\"\n\t\"github.com/tsuru/tsuru/storage\"\n\tquotaTypes \"github.com/tsuru/tsuru/types/quota\"\n)\n\n\n\nfunc QuotaService() (quotaTypes.QuotaService, error) ", "output": "{\n\tdbDriver, err := storage.GetCurrentDbDriver()\n\tif err != nil {\n\t\tdbDriver, err = storage.GetDefaultDbDriver()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\treturn "a.QuotaService{\n\t\tStorage: dbDriver.AppQuotaStorage,\n\t}, nil\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"runtime\"\n\n\t\"k8s.io/kubernetes/cmd/kube-proxy/app\"\n\t\"k8s.io/kubernetes/pkg/healthz\"\n\t\"k8s.io/kubernetes/pkg/util\"\n\t\"k8s.io/kubernetes/pkg/version/verflag\"\n\n\t\"github.com/spf13/pflag\"\n)\n\n\n\nfunc main() {\n\truntime.GOMAXPROCS(runtime.NumCPU())\n\ts := app.NewProxyServer()\n\ts.AddFlags(pflag.CommandLine)\n\n\tutil.InitFlags()\n\tutil.InitLogs()\n\tdefer util.FlushLogs()\n\n\tverflag.PrintAndExitIfRequested()\n\n\tif err := s.Run(pflag.CommandLine.Args()); 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 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\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\nfunc NewSuggester(suggestions ...string) Suggester {\n\treturn newSuggester(suggestions)\n}\n\nfunc NewEngine() *Engine ", "output": "{\n\treturn newEngine()\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\n\n\nfunc (r *rorm) Querier() Querier {\n\treturn r.redisQuerier\n}\n\nfunc (r rorm) Using(alias string) ROrmer ", "output": "{\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}"} {"input": "package main\n\nimport (\n\t\"context\"\n\t\"net/url\"\n\n\t\"github.com/streadway/amqp\"\n)\n\ntype amqpResource struct {\n\turl.URL\n}\n\n\n\nfunc (a amqpResource) Await(ctx context.Context) error ", "output": "{\n\tconn, err := amqp.Dial(a.String())\n\tif err != nil {\n\t\treturn &unavailabilityError{Reason: err}\n\t}\n\t_ = conn.Close()\n\treturn nil\n}"} {"input": "package main\n\nimport (\n\t\"image/png\"\n\t\"net/http\"\n\n\t\"github.com/Sirupsen/logrus\"\n\t\"github.com/jakobvarmose/go-qidenticon\"\n)\n\n\n\nfunc handleIdenticon(w http.ResponseWriter, req *http.Request, address string) ", "output": "{\n\tw.Header().Set(\"Cache-Control\", \"max-age=604800\")\n\tw.Header().Set(\"Content-Type\", \"image/png\")\n\tw.Header().Set(\"X-Content-Type-Options\", \"nosniff\")\n\tw.Header().Set(\"X-Frame-Options\", \"DENY\")\n\tcode := qidenticon.Code(address)\n\timage := qidenticon.Render(code, 30, qidenticon.DefaultSettings())\n\terr := png.Encode(w, image)\n\tif err != nil {\n\t\tlogrus.Error(err)\n\t}\n}"} {"input": "package graphql\n\nimport (\n\t\"context\"\n\t\"encoding/json\"\n\t\"io\"\n\n\t\"github.com/dennwc/graphql/gqlerrors\"\n\n\t\"github.com/cayleygraph/cayley/graph\"\n\t\"github.com/cayleygraph/cayley/query\"\n)\n\ntype httpResult struct {\n\tData interface{} `json:\"data\"`\n\tErrors []gqlerrors.FormattedError `json:\"errors,omitempty\"`\n}\n\nfunc httpError(w query.ResponseWriter, err error) {\n\tjson.NewEncoder(w).Encode(httpResult{\n\t\tErrors: []gqlerrors.FormattedError{{\n\t\t\tMessage: err.Error(),\n\t\t}},\n\t})\n}\n\n\n\nfunc httpQuery(ctx context.Context, qs graph.QuadStore, w query.ResponseWriter, r io.Reader) ", "output": "{\n\tq, err := Parse(r)\n\tif err != nil {\n\t\thttpError(w, err)\n\t\treturn\n\t}\n\tm, err := q.Execute(ctx, qs)\n\tif err != nil {\n\t\thttpError(w, err)\n\t\treturn\n\t}\n\tjson.NewEncoder(w).Encode(httpResult{Data: m})\n}"} {"input": "package tcell\n\nimport (\n\t\"testing\"\n\n\t. \"github.com/smartystreets/goconvey/convey\"\n)\n\n\n\nfunc TestStyle(t *testing.T) ", "output": "{\n\tConvey(\"Style checks\", t, WithScreen(t, \"\", func(s SimulationScreen) {\n\n\t\tstyle := StyleDefault\n\t\tfg, bg, attr := style.Decompose()\n\n\t\tSo(fg, ShouldEqual, ColorDefault)\n\t\tSo(bg, ShouldEqual, ColorDefault)\n\t\tSo(attr, ShouldEqual, AttrNone)\n\n\t\ts2 := style.\n\t\t\tBackground(ColorRed).\n\t\t\tForeground(ColorBlue).\n\t\t\tBlink(true)\n\n\t\tfg, bg, attr = s2.Decompose()\n\t\tSo(fg, ShouldEqual, ColorBlue)\n\t\tSo(bg, ShouldEqual, ColorRed)\n\t\tSo(attr, ShouldEqual, AttrBlink)\n\t}))\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\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\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 init() ", "output": "{\n\tcore.TypeRegistry.Register(Hostname{})\n}"} {"input": "package base\n\nimport (\n\t\"github.com/johnwilson/bytengine\"\n)\n\n\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\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 ServerListDb(cmd bytengine.Command, user *bytengine.User, eng *bytengine.Engine) (interface{}, error) ", "output": "{\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}"} {"input": "package main\n\nimport \"fmt\"\n\n\n\n\n\n\n\nfunc main() {\n\tname := \"Makes 10\"\n\tfmt.Println(name, \"1:\", makes10(9, 10))\n\tfmt.Println(name, \"2:\", makes10(9, 9))\n\tfmt.Println(name, \"3:\", makes10(1, 9))\n}\n\n\n\nfunc makes10(a, b int) bool ", "output": "{\n\tif a == 10 || b == 10 || (a + b) == 10 {\n\t\treturn true\n\t}\n\n\treturn false\n}"} {"input": "package terraform\n\nimport (\n\t\"github.com/hashicorp/terraform/addrs\"\n\t\"github.com/hashicorp/terraform/configs/configschema\"\n\t\"github.com/hashicorp/terraform/dag\"\n)\n\n\n\n\n\ntype ResourceCountTransformer struct {\n\tConcrete ConcreteResourceInstanceNodeFunc\n\tSchema *configschema.Block\n\n\tCount int\n\tAddr addrs.AbsResource\n}\n\n\n\nfunc (t *ResourceCountTransformer) Transform(g *Graph) error ", "output": "{\n\tif t.Count < 0 {\n\t\taddr := t.Addr.Instance(addrs.NoKey)\n\n\t\tabstract := NewNodeAbstractResourceInstance(addr)\n\t\tabstract.Schema = t.Schema\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\treturn nil\n\t}\n\n\tfor i := 0; i < t.Count; i++ {\n\t\tkey := addrs.IntKey(i)\n\t\taddr := t.Addr.Instance(key)\n\n\t\tabstract := NewNodeAbstractResourceInstance(addr)\n\t\tabstract.Schema = t.Schema\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 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\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\nfunc (response ListTaggingWorkRequestErrorsResponse) HTTPResponse() *http.Response {\n\treturn response.RawResponse\n}\n\nfunc (request ListTaggingWorkRequestErrorsRequest) 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 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 GetList() *methods.Method ", "output": "{\n\tname := \"rtm.lists.getList\"\n\n\tp := url.Values{}\n\tp.Add(\"method\", name)\n\treturn &methods.Method{Name: name, Params: p}\n}"} {"input": "package nzbget\n\nimport \"fmt\"\n\ntype ListFilesResponse struct {\n\tID int\n\tNZBID int\n\tNZBFilename string\n\tNZBName string\n\tNZBNicename string\n\tSubject string\n\tFilename string\n\tFilenameConfirmed bool\n\tDestDir string\n\tFileSizeLo int\n\tFileSizeHi int\n\tRemainingSizeLo int\n\tRemainingSizeHi int\n\tPaused bool\n\tPostTime int\n\tPriority int\n\tActiveDownloads int\n\tProgress int\n}\n\ntype listFilesParameter struct {\n\tIDFrom int\n\tIDTo int\n\tNZBID int\n}\n\n\n\nfunc (c *Client) ListFiles(nzbid int) ([]ListFilesResponse, error) ", "output": "{\n\tp := listFilesParameter{NZBID: nzbid, IDFrom: 0, IDTo: 0}\n\tvar r []ListFilesResponse\n\terr := c.Call(\"listfiles\", toXMLRPCArgs(p), &r)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"listfiles call failed: %v\", err)\n\t}\n\tif len(r) == 0 {\n\t\treturn nil, fmt.Errorf(\"item with id=%d not found in queue\", p.NZBID)\n\t}\n\treturn r, nil\n}"} {"input": "package goFrontEnd\n\nimport (\n \"fmt\"\n \"net/http\"\n \"math/rand\"\n \"strconv\"\n)\n\nfunc init() {\n http.HandleFunc(\"/\", handler)\n http.HandleFunc(\"/abc\", handler2)\n}\n\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 handler(w http.ResponseWriter, r *http.Request) ", "output": "{\n wHeader := w.Header()\n wHeader.Set(\"Content-Type\",\"application/json\")\n fmt.Fprint(w, \"{\\\"a\\\":\\\"beetle\\\",\\\"b\\\":\\\"juice\\\"}\")\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\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 (p *Player) Reset() error ", "output": "{\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}"} {"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 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\nfunc (a *AcceptorCancellationAdvice3) AddContext() *CardPaymentContext2 {\n\ta.Context = new(CardPaymentContext2)\n\treturn a.Context\n}\n\n\n\nfunc (a *AcceptorCancellationAdvice3) AddTransaction() *CardPaymentTransaction28 ", "output": "{\n\ta.Transaction = new(CardPaymentTransaction28)\n\treturn a.Transaction\n}"} {"input": "package v1beta1\n\nimport (\n\t\"context\"\n\n\t\"knative.dev/pkg/apis\"\n\t\"knative.dev/pkg/kmp\"\n)\n\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\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 (et *EventType) Validate(ctx context.Context) *apis.FieldError ", "output": "{\n\treturn et.Spec.Validate(ctx).ViaField(\"spec\")\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\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\n\n\nfunc ScalarMultNonConst(k *ModNScalar, point, result *JacobianPoint) ", "output": "{\n\tsecp.ScalarMultNonConst(k, point, result)\n}"} {"input": "package internal\n\n\n\nfunc BytesToString(b []byte) string ", "output": "{\n\treturn string(b)\n}"} {"input": "package leetcode\n\n\n\nfunc swapPairs(head *ListNode) *ListNode ", "output": "{\n\troot := &ListNode{Next: head}\n\tfirst := root.Next\n\tsecond := root\n\tfor first.Next != nil {\n\t\tsecond.Next = first.Next\n\t\tfirst.Next = first.Next.Next\n\t\tsecond.Next.Next = first\n\n\t\tfirst = first.Next\n\t\tsecond = second.Next.Next\n\t}\n\treturn root.Next\n}"} {"input": "package main\nimport (\n\t\"github.com/samcrosoft/waveform-json\"\n\t\"github.com/samcrosoft/waveform-json/fetchers\"\n\t\"io/ioutil\"\n\t\"os\"\n\t\"flag\"\n\t\"strings\"\n\t\"runtime\"\n)\n\nfunc main() {\n\n\truntime.GOMAXPROCS(runtime.NumCPU())\n\n\tvar sOutputFileName string\n\tvar sSource string\n\tvar oFetcher fetchers.IMAGEFetcher\n\tflag.StringVar(&sOutputFileName, \"o\", \"output.json\", \"the outfile filename, default is output.json\")\n\tflag.StringVar(&sSource, \"s\", \"\", \"the source of the waveform, e.g ./corpus/sample.png\")\n\tflag.Parse()\n\n\tif(sSource == \"\"){\n\t\tos.Stderr.WriteString(\"Source Of Waveform cannot be empty\")\n\t\tos.Exit(0)\n\t}\n\toFetcher = determineFetcherTypeFromSource(sSource)\n\toWave := waveformjson.New(sSource, oFetcher)\n\n\tif oJson, err := oWave.GetWaveformJson(); err == nil{\n\t\tif err2 := ioutil.WriteFile(sOutputFileName, oJson, os.FileMode(os.O_WRONLY)); err2 != nil{\n\t\t}\n\t}else{\n\t\tos.Stderr.WriteString(\"Not A Valid Png\")\n\t}\n\n}\n\n\n\n\nfunc determineFetcherTypeFromSource(sSource string) fetchers.IMAGEFetcher", "output": "{\n\tif sSource != \"\" && strings.HasPrefix(sSource, \"http\"){\n\t\treturn &fetchers.URLFetcher{}\n\t}else{\n\t\treturn &fetchers.FILEFetcher{}\n\t}\n}"} {"input": "package main\n\nimport (\n\t\"github.com/grd/iup\"\n\t\"fmt\"\n)\n\nvar someone *iup.Ihandle\n\nfunc nameKeyEntry(ih *iup.Ihandle, ch int, newValue string) int {\n\tfmt.Printf(\"Char Pressed: %d, New Value: %s\\n\", ch, newValue)\n\treturn 0\n}\n\n\n\nfunc sayHelloToSomeone(ih *iup.Ihandle) int {\n\tfmt.Printf(\"Hello, %s!\\n\", iup.GetAttribute(someone, \"VALUE\"))\n\treturn 0\n}\n\nfunc main() {\n\tiup.Open()\n\tdefer iup.Close()\n\n\tsomeone = iup.Text((iup.TextActionFunc)(nameKeyEntry))\n\thelloSomeone := iup.Button(\"Say Hello\",\n\t\t(iup.ActionFunc)(sayHelloToSomeone))\n\n\tline1 := iup.Hbox(iup.Label(\"Name:\"), someone, helloSomeone)\n\tiup.SetAttributes(line1, \"ALIGNMENT=ACENTER,GAP=5\")\n\n\thelloJohn := iup.Button(\"Hello John\",\n\t\t(iup.ActionFunc)(sayHello),\n\t\t\"TO_WHO=\\\"John Doe\\\"\")\n\n\thelloJim := iup.Button(\"Hello Jim\",\n\t\t(iup.ActionFunc)(sayHello),\n\t\t\"TO_WHO=\\\"Jim Doe\\\"\")\n\n\tline2 := iup.Hbox(iup.Label(\"Predefined greeters:\"), helloJohn, helloJim)\n\tiup.SetAttributes(line2, \"ALIGNMENT=ACENTER,GAP=5\")\n\n\tform := iup.Vbox(line1, line2)\n\tiup.SetAttributes(form, \"GAP=5,MARGIN=3x3\")\n\n\tdlg := iup.Dialog(form, \"TITLE=Greeter\")\n\tiup.Show(dlg)\n\n\tiup.MainLoop()\n}\n\nfunc sayHello(ih *iup.Ihandle) int ", "output": "{\n\tfmt.Printf(\"Hello, %s!\\n\", iup.GetAttribute(ih, \"TO_WHO\"))\n\treturn 0\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\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) Reset() ", "output": "{\n\tb.batch.Reset()\n\tb.merge = store.NewEmulatedMerge(b.store.mo)\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\n\n\nfunc (l *logWriter) Close() {\n\tl.lock.Lock()\n\tdefer l.lock.Unlock()\n\tclose(l.log)\n}\n\nfunc (l *logWriter) LogWrite(rec *log4go.LogRecord) ", "output": "{\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}"} {"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\nfunc (r *ResponseErrorAdapter) Model() interface{} {\n\treturn r.Err.Model\n}\n\n\n\nfunc (r *ResponseErrorAdapter) Code() int ", "output": "{\n\treturn r.Err.Code\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\nfunc (ep *Endpoint) url() string {\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}\n\n\n\n\nfunc NewEndpoint(host string, port int, https bool, insecure bool, Cacert, cert, key []byte, timeout time.Duration) *Endpoint ", "output": "{\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}"} {"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\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\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 NewUnitGetCommand(ctx Context) cmd.Command ", "output": "{\n\treturn &UnitGetCommand{ctx: ctx}\n}"} {"input": "package render\n\n\n\n\n\n\n\nfunc JavaScript(names ...string) Renderer {\n\te := New(Options{})\n\treturn e.JavaScript(names...)\n}\n\n\n\n\n\n\n\n\n\n\n\n\nfunc (e *Engine) JavaScript(names ...string) Renderer ", "output": "{\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}"} {"input": "package rest\n\nimport \"net/http\"\n\ntype StaticResource struct {\n\tResourceBase\n\tresult *Result\n\tself Link\n}\n\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\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 NewStaticResource(result *Result, self Link) Resource ", "output": "{\n\treturn &StaticResource{\n\t\tresult: result,\n\t\tself: self,\n\t}\n}"} {"input": "package server\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\n\n\nfunc TestUserRegister(t *testing.T) ", "output": "{\n\tstartTestServer(t)\n\tuserRegisterAPI := TestAddr + \"/api/v1/user/register\"\n\n\tdata := `{\"username\": \"test\",\"password\": \"123456\"}`\n\tm1 := postJSON(userRegisterAPI, strings.NewReader(data))\n\tassert.NotNil(t, m1)\n\tassert.Equal(t, m1[\"message\"], UserRegisterSuccess)\n\n\tm2 := postJSON(userRegisterAPI, strings.NewReader(data))\n\tassert.NotNil(t, m2)\n\tassert.Equal(t, m2[\"message\"], ErrUserExisted)\n\n\ttruncateTable(\"users\")\n}"} {"input": "package main\n\nimport (\n \"fmt\"\n \"time\"\n \"sync\"\n)\n\n\n\n\n\nfunc workerAct(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\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 workerNoRetrieve(ch chan int) ", "output": "{\n go func(ch chan int) {\n ch <- 23\n }(ch)\n\n \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\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 assert(tb testing.TB, condition bool, msg string, v ...interface{}) ", "output": "{\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}"} {"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\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\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) GetInterpolated(section, option string) (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))\n\treturn p.getInterpolated(section, option, c)\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\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\n\n\nfunc (s *Session) handlerFactory(method string) http.Handler ", "output": "{\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}"} {"input": "\n\nfunc pushDominoes(dominoes string) string ", "output": "{\n current := []rune(dominoes)\n next := []rune(dominoes)\n changed := true\n \n for changed {\n changed = false\n for i, r := range current {\n switch r {\n case 'L', 'R':\n next[i] = r\n default:\n if 0 < i && i < len(current)-1 && current[i-1] == 'R' && current[i+1] == 'L' {\n next[i] = r\n } else if 0 < i && current[i-1] == 'R' {\n next[i] = 'R'\n changed = true\n } else if i < len(current)-1 && current[i+1] == 'L' {\n next[i] = 'L'\n changed = true\n } else {\n next[i] = r\n }\n }\n }\n current, next = next, current\n }\n return string(current)\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\nfunc (request ListIPSecConnectionsRequest) String() string {\n\treturn common.PointerString(request)\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\n\n\nfunc (response ListIPSecConnectionsResponse) String() string ", "output": "{\n\treturn common.PointerString(response)\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\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 (s *SVP) ValidHeader(header BlockHeader) bool ", "output": "{\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}"} {"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\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\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 NewCondBr(block value.Value, name string, condition value.Value, trueBlock value.Value, falseBlock value.Value) *CondBr ", "output": "{\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}"} {"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\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) Add(s Size) Value ", "output": "{\n\treturn v + Value(s)\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) }\n\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) Chain(i int) Chain ", "output": "{ return Chain{i, 1} }"} {"input": "package cache\n\nimport (\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/smartystreets/goconvey/convey\"\n)\n\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\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 TestCacheRefreshUpTypeAsync(t *testing.T) ", "output": "{\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}"} {"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\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 (m *remote) SearchDevices(ctx context.Context, query *search.Query, handler DeviceHandler) error ", "output": "{\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}"} {"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\n\n\nfunc (this *TopicMessage) Text() string {\n return this.text\n}\n\nfunc (this *TopicMessage) Source() *Client ", "output": "{\n return this.source\n}"} {"input": "package types\n\nimport (\n\t\"testing\"\n\n\tacm \"github.com/tendermint/tendermint/account\"\n\t. \"github.com/tendermint/tendermint/common\"\n\t_ \"github.com/tendermint/tendermint/config/tendermint_test\"\n)\n\n\n\nfunc TestProposalSignable(t *testing.T) ", "output": "{\n\tproposal := &Proposal{\n\t\tHeight: 12345,\n\t\tRound: 23456,\n\t\tBlockPartsHeader: PartSetHeader{111, []byte(\"blockparts\")},\n\t\tPOLRound: -1,\n\t}\n\tsignBytes := acm.SignBytes(config.GetString(\"chain_id\"), proposal)\n\tsignStr := string(signBytes)\n\n\texpected := Fmt(`{\"chain_id\":\"%s\",\"proposal\":{\"block_parts_header\":{\"hash\":\"626C6F636B7061727473\",\"total\":111},\"height\":12345,\"pol_round\":-1,\"round\":23456}}`,\n\t\tconfig.GetString(\"chain_id\"))\n\tif signStr != expected {\n\t\tt.Errorf(\"Got unexpected sign string for SendTx. Expected:\\n%v\\nGot:\\n%v\", expected, signStr)\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\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\n\n\nfunc AutoRender(w http.ResponseWriter, data interface{}, err error) ", "output": "{\n\tif err != nil {\n\t\tRenderMsgJson(w, err.Error())\n\t\treturn\n\t}\n\tRenderDataJson(w, data)\n}"} {"input": "package etchosts\n\nimport (\n\t\"bytes\"\n\t\"io/ioutil\"\n\t\"os\"\n\t\"testing\"\n)\n\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\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 TestBuildHostnameDomainname(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\", \"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}"} {"input": "package main\n\nimport (\n \"runtime\"\n \"os\"\n\n \"dicewa.re/server\"\n \"github.com/codegangsta/cli\"\n)\n\nfunc main() {\n runtime.GOMAXPROCS(runtime.NumCPU())\n\n app := cli.NewApp()\n app.Name = \"diceware\"\n app.Usage = \"Diceware password generator www/api\"\n\n app.Commands = []cli.Command{\n {\n Name: \"start\",\n Usage: \"Start server\",\n Action: StartServer,\n },\n }\n app.Run(os.Args)\n}\n\n\n\nfunc StartServer(c *cli.Context) ", "output": "{\n app := server.NewApp()\n app.Run(\":8000\")\n}"} {"input": "package stake\n\nimport \"strings\"\n\n\n\n\nfunc (claimant *Claimant) MakeClaim(subject string, claim string) (string, error) ", "output": "{\n\tif strings.TrimSpace(subject) == \"\" {\n\t\treturn \"Subject cannot be blank\", nil\n\t}\n\n\tclaimAlreadyExists := claimant.claimKeyFor(subject, claim)\n\tif claimant.claims[claimAlreadyExists] == true {\n\t\treturn \"Claim already exists\", nil\n\t}\n\n\tclaimant.trackChange(ClaimMade{ClaimantID: claimant.ID, Subject: subject, Claim: claim})\n\treturn \"Success\", nil\n}"} {"input": "package tests\n\nimport (\n\t\"go2o/core/infrastructure/domain\"\n\t\"testing\"\n)\n\n\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\nfunc TestMerchantPwd(t *testing.T) {\n\tpwd := \"123456\"\n\tencPwd := domain.MerchantSha1Pwd(pwd)\n\tt.Log(encPwd)\n}\n\nfunc TestMasterPwd(t *testing.T) ", "output": "{\n\tuser := \"master\"\n\tpwd := \"123456\"\n\tsha1 := domain.Sha1(domain.Md5(pwd) + user + domain.Sha1OffSet)\n\tt.Log(sha1)\n}"} {"input": "package math\n\nimport \"math\"\n\n\n\n\n\n\n\n\nfunc Round(x float64) float64 ", "output": "{\n\tif math.IsNaN(x) || math.IsInf(x, 0) {\n\t\treturn x\n\t}\n\treturn math.Trunc(x + math.Copysign(.5, x))\n}"} {"input": "package config\n\nimport \"golang.org/x/xerrors\"\n\n\ntype JSONLoader struct {\n}\n\n\n\n\nfunc (c JSONLoader) Load(_, _, _ string) (err error) ", "output": "{\n\treturn xerrors.New(\"Not implement yet\")\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\nfunc (c *Config) validateRegion() error {\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}\n\n\n\nfunc (c *Config) getAuthCredential(stsSupported bool) auth.Credential ", "output": "{\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}"} {"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\nfunc init() {\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}\n\n\nvar execW bool \nvar execTimeout float64 \nvar execHelp bool \nvar execGateway string \n\n\n\nfunc runExec(cmd *Command, rawArgs []string) error ", "output": "{\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}"} {"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\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 (m *Modifier) MarkAsDeleted() ", "output": "{\n\tm.Deleted = true\n}"} {"input": "package simulatorsetup\n\nimport (\n\t\"fmt\"\n\t\"os\"\n)\n\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\nfunc (deviceList DeviceList) printDeviceList() {\n\tfor _, device := range deviceList.Devices {\n\t\tfmt.Println(device.Name)\n\t}\n}\n\nfunc ApplyDataToSim(deviceName string, deviceVersion string) ", "output": "{\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}"} {"input": "package mount\n\n\n\nfunc parseMountTable(f FilterFunc) ([]*Info, error) ", "output": "{\n\treturn nil, nil\n}"} {"input": "package clang\n\n\n\nimport \"C\"\n\nimport (\n\t\"time\"\n)\n\n\ntype File struct {\n\tc C.CXFile\n}\n\n\n\n\n\nfunc (c File) ModTime() time.Time {\n\tsec := C.clang_getFileTime(c.c)\n\tconst nsec = 0\n\treturn time.Unix(int64(sec), nsec)\n}\n\nfunc (c File) Name() string ", "output": "{\n\tcstr := cxstring{C.clang_getFileName(c.c)}\n\tdefer cstr.Dispose()\n\treturn cstr.String()\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\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 Fatalln(args ...interface{}) ", "output": "{\n\tlogger.Fatalln(args...)\n\tos.Exit(1)\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\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) RpcMethod() string ", "output": "{\n\treturn self.rpcMethod\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\nfunc NewStorage(generator *generator.BuildGenerator) *CloneREST {\n\treturn &CloneREST{generator: generator}\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\n\n\nfunc (s *CloneREST) Create(ctx kapi.Context, obj runtime.Object) (runtime.Object, error) ", "output": "{\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}"} {"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\nfunc (rs *RestartStatistics) Reset() {\n\trs.failureTimes = []time.Time{}\n}\n\n\n\n\nfunc (rs *RestartStatistics) NumberOfFailures(withinDuration time.Duration) int ", "output": "{\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}"} {"input": "package cache\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/go-spatial/cobra\"\n)\n\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\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 setupMinMaxZoomFlags(cmd *cobra.Command, min, max uint) ", "output": "{\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}"} {"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\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 SetupSignalContextNotExiting() context.Context ", "output": "{\n\treturn setupSignalContext(false)\n}"} {"input": "package translatableerror\n\ntype PackageNotFoundInAppError struct {\n\tAppName string\n\tBinaryName string\n}\n\nfunc (PackageNotFoundInAppError) Error() string {\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}\n\n\n\nfunc (e PackageNotFoundInAppError) Translate(translate func(string, ...interface{}) string) string ", "output": "{\n\treturn translate(e.Error(), map[string]interface{}{\n\t\t\"AppName\": e.AppName,\n\t\t\"BinaryName\": e.BinaryName,\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\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\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 catchPrepare(err interface{}, args map[string]interface{}) ", "output": "{\n\tfmt.Println(\"CRITICAL: \" + extendederror.ParseError(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 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\nfunc (response RemoveNetworkSecurityGroupSecurityRulesResponse) String() string {\n\treturn common.PointerString(response)\n}\n\n\n\n\nfunc (response RemoveNetworkSecurityGroupSecurityRulesResponse) HTTPResponse() *http.Response ", "output": "{\n\treturn response.RawResponse\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\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 (m *MockRoundTripper) EXPECT() *MockRoundTripperMockRecorder ", "output": "{\n\treturn m.recorder\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\nfunc (c *simpleCache) get(key string) (*cacheRecord, bool) {\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}\n\n\n\nfunc (c *simpleCache) remove(key string) {\n\tc.cache.Delete(key)\n}\n\nfunc (c *simpleCache) set(key string, value *cacheRecord, ttl time.Duration) ", "output": "{\n\tc.cache.Set(key, value, ttl)\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\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) For(result interface{}, f func() error) (err error) ", "output": "{\n\treturn i.iter.For(result, f)\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\n\n\nfunc (i *IMEITNS) GetDB() (*mgo.Session, *mgo.Collection) {\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}\n\nfunc (i *IMEITNS) InsertITNS() (*mgo.Session, error) ", "output": "{\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}"} {"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\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 (r *RAM) SetWindow(offset uint32) error ", "output": "{\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}"} {"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\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 IncrRead(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.readReq.Incr(1)\n}"} {"input": "package util\n\nimport (\n\t\"bytes\"\n\t\"encoding/gob\"\n\t\"github.com/goarchit/archit/log\"\n\t\"github.com/valyala/gorpc\"\n)\n\n\n\nfunc GetPeerInfo(serverIP string) PeerList ", "output": "{\n\tvar newPL PeerList\n\n c := gorpc.NewTCPClient(serverIP)\n\tc.Start()\n\tdefer c.Stop()\n\n\td := gorpc.NewDispatcher()\n\td.AddFunc(\"PeerListAll\", func() {})\n\n\tdc := d.NewFuncClient(c)\n\n\tplstr, err := dc.Call(\"PeerListAll\", nil)\n\tif err != nil {\n\t\tlog.Critical(\"Attempt to get PeerList from local farm node\",serverIP,\"failed:\", err)\n\t}\n\tstr, ok := plstr.(string)\n\tif !ok {\n\t\tlog.Critical(\"GetPeerInfo: dc.call(PeerListAll) did not return a string\")\n\t}\n\tbuf := bytes.NewBufferString(str)\n\tdec := gob.NewDecoder(buf)\n\terr = dec.Decode(&newPL)\n\tif err != nil {\n\t\tlog.Critical(\"GetPeerInfo: Error decoding PeerMap:\", err)\n\t}\n\treturn newPL\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\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) Update() error ", "output": "{\n\tif err := checkIndex(t.Id); err != nil {\n\t\treturn err\n\t}\n\tTopicCache[t.Id-1] = t\n\treturn nil\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\n\n\n\nfunc AddPodPVCIndexerIfNotPresent(indexer cache.Indexer) error {\n\treturn AddIndexerIfNotPresent(indexer, PodPVCIndex, PodPVCIndexFunc())\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 PodPVCIndexFunc() func(obj interface{}) ([]string, error) ", "output": "{\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}"} {"input": "package logs\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/spf13/pflag\"\n\n\tutilerrors \"k8s.io/apimachinery/pkg/util/errors\"\n\t\"k8s.io/apimachinery/pkg/util/wait\"\n\t\"k8s.io/component-base/config\"\n\t\"k8s.io/component-base/config/v1alpha1\"\n\t\"k8s.io/component-base/logs/registry\"\n\t\"k8s.io/component-base/logs/sanitization\"\n\t\"k8s.io/klog/v2\"\n)\n\n\ntype Options struct {\n\tConfig config.LoggingConfiguration\n}\n\n\nfunc NewOptions() *Options {\n\tc := v1alpha1.LoggingConfiguration{}\n\tv1alpha1.RecommendedLoggingConfiguration(&c)\n\to := &Options{}\n\tv1alpha1.Convert_v1alpha1_LoggingConfiguration_To_config_LoggingConfiguration(&c, &o.Config, nil)\n\treturn o\n}\n\n\n\n\n\nfunc (o *Options) ValidateAndApply() error {\n\terrs := o.validate()\n\tif len(errs) > 0 {\n\t\treturn utilerrors.NewAggregate(errs)\n\t}\n\to.apply()\n\treturn nil\n}\n\n\n\nfunc (o *Options) validate() []error {\n\terrs := ValidateLoggingConfiguration(&o.Config, nil)\n\tif len(errs) != 0 {\n\t\treturn errs.ToAggregate().Errors()\n\t}\n\treturn nil\n}\n\n\n\n\n\nfunc (o *Options) AddFlags(fs *pflag.FlagSet) {\n\tBindLoggingFlags(&o.Config, fs)\n}\n\n\n\n\nfunc (o *Options) apply() ", "output": "{\n\tfactory, _ := registry.LogRegistry.Get(o.Config.Format)\n\tif factory == nil {\n\t\tklog.ClearLogger()\n\t} else {\n\t\tlog, flush := factory.Create(o.Config.Options)\n\t\tklog.SetLogger(log)\n\t\tlogrFlush = flush\n\t}\n\tif o.Config.Sanitization {\n\t\tklog.SetLogFilter(&sanitization.SanitizingFilter{})\n\t}\n\tif err := loggingFlags.Lookup(\"v\").Value.Set(o.Config.Verbosity.String()); err != nil {\n\t\tpanic(fmt.Errorf(\"internal error while setting klog verbosity: %v\", err))\n\t}\n\tif err := loggingFlags.Lookup(\"vmodule\").Value.Set(o.Config.VModule.String()); err != nil {\n\t\tpanic(fmt.Errorf(\"internal error while setting klog vmodule: %v\", err))\n\t}\n\tgo wait.Forever(FlushLogs, o.Config.FlushFrequency)\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\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\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 dropHyphen(isbn string) string ", "output": "{\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}"} {"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\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) Logger(pkg string) *log.Logger ", "output": "{\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}"} {"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\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) GetInstance(appId, instanceId string) (*InstanceInfo, error) ", "output": "{\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}"} {"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\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\n\n\nfunc HashString(in string, hash crypto.Hash) (out string) ", "output": "{\n\th := hash.New()\n\th.Write(util.S2B(in))\n\tmd := h.Sum(nil)\n\tout = hex.EncodeToString(md)\n\treturn\n}"} {"input": "package bytealg\n\nconst MaxBruteForce = 0\n\n\n\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\nfunc Cutover(n int) int {\n\tpanic(\"unimplemented\")\n}\n\nfunc Index(a, b []byte) int ", "output": "{\n\tpanic(\"unimplemented\")\n}"} {"input": "package vbox\n\nimport (\n\t\"bufio\"\n\t\"io/ioutil\"\n\t\"os\"\n\t\"path\"\n)\n\n\n\n\n\n\n\n\n\nfunc getParentIds(root, id string) ([]string, error) {\n\tf, err := os.Open(path.Join(root, \"layers\", id))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer f.Close()\n\n\tout := []string{}\n\ts := bufio.NewScanner(f)\n\n\tfor s.Scan() {\n\t\tif t := s.Text(); t != \"\" {\n\t\t\tout = append(out, s.Text())\n\t\t}\n\t}\n\treturn out, s.Err()\n}\n\nfunc loadIds(root string) ([]string, error) ", "output": "{\n\tdirs, err := ioutil.ReadDir(root)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tout := []string{}\n\tfor _, d := range dirs {\n\t\tif !d.IsDir() {\n\t\t\tout = append(out, d.Name())\n\t\t}\n\t}\n\treturn out, nil\n}"} {"input": "package chainview\n\nimport \"github.com/btcsuite/btclog\"\n\n\n\n\nvar log btclog.Logger\n\n\n\n\n\n\nfunc DisableLog() {\n\tlog = btclog.Disabled\n}\n\n\n\n\nfunc UseLogger(logger btclog.Logger) {\n\tlog = logger\n}\n\nfunc init() ", "output": "{\n\tDisableLog()\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\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 (s *StatusChange) UpdatePullRequestHead(pullRequestID int, newHead string) ", "output": "{\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}"} {"input": "package main\n\nimport (\n \"fmt\"\n _\"time\"\n)\n\n\n\nfunc main() {\n\n wordChannel := make(chan string)\n stopChannel := make(chan int)\n\n for i := 0; i < 5; i++ {\n go emit(wordChannel, stopChannel)\n }\n\n \n \n \n\n for {\n word := <- wordChannel\n fmt.Printf(\"%s\\n\", word)\n }\n\n}\n\nfunc emit(c chan string, count chan int) ", "output": "{\n\n words := []string{\"The\", \"quick\", \"brown\", \"fox\"}\n\n total := 0\n for {\n fmt.Printf(\"Printing\\n\")\n \n select {\n\n case <-count:\n total += 1\n fmt.Printf(\"total is %d\\n\", total)\n if total == 4 {\n fmt.Printf(\"Closing channel\\n\")\n close(c)\n return\n }\n\n\n default:\n for _, word := range words {\n c <- word\n }\n count <- 1\n \n \n \n \n }\n }\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\nfunc (cmd *rm) Description() string {\n\treturn `Remove SSO users.\n\nExamples:\n govc sso.user.rm NAME`\n}\n\n\n\nfunc (cmd *rm) Run(ctx context.Context, f *flag.FlagSet) error ", "output": "{\n\treturn withClient(ctx, cmd.ClientFlag, func(c *ssoadmin.Client) error {\n\t\treturn c.DeletePrincipal(ctx, f.Arg(0))\n\t})\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\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\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 NewHTTPClient(formats strfmt.Registry) *SubscriptionClient ", "output": "{\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}"} {"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\nfunc (p *NoopPreProcessor) Process(pod apiv1.Pod) (apiv1.Pod, error) {\n\treturn pod, nil\n}\n\n\n\n\nfunc NewDefaultPreProcessor() PreProcessor ", "output": "{\n\treturn &NoopPreProcessor{}\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\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\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) MarshalXML(e *xml.Encoder, start xml.StartElement) error ", "output": "{\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}"} {"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\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) Iterator(k []byte) store.KVIterator ", "output": "{\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}"} {"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\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\n\n\nfunc onDraw() ", "output": "{\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}"} {"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\n\n\n\n\nfunc (l Logger) Log(message string) {\n\tl.Write([]byte(message))\n}\n\nfunc (l Logger) Write(p []byte) (n int, err error) ", "output": "{\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}"} {"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\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\n\n\nfunc (m *OpenpitrixLeaveGroupResponse) UnmarshalBinary(b []byte) error ", "output": "{\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}"} {"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\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) Update(createNetworkContainerRequest cns.CreateNetworkContainerRequest) error ", "output": "{\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}"} {"input": "package faker\n\nimport \"testing\"\n\n\n\nfunc TestFakerHexColor(t *testing.T) {\n\tf := NewDefault()\n\tc := f.HexColor()\n\tassertStringRegexp(t, \"[0-9a-f]{8}\", c)\n}\n\nfunc TestFakerColorName(t *testing.T) ", "output": "{\n\tf := NewDefault()\n\tl := f.ColorName()\n\tassertElementInSlice(t, l, colorNames)\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\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\n\n\nfunc (it *Item) Save() error ", "output": "{\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}"} {"input": "package cloudatcost\n\nimport (\n\t\"fmt\"\n\t\"net/http\"\n\t\"net/url\"\n)\n\ntype CloudProService struct {\n\tclient *Client\n}\n\nfunc (s *CloudProService) Resources() (*CloudProResourcesData, *http.Response, error) {\n\tu := fmt.Sprintf(\"/api/v1/cloudpro/resources.php?key=%s&login=%s\", s.client.Option.Key, s.client.Option.Login)\n\n\treq, err := s.client.NewRequest(\"GET\", u, nil)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\trr := new(CloudProResourcesResponse)\n\tresp, err := s.client.Do(req, rr)\n\tif err != nil {\n\t\treturn nil, resp, err\n\t}\n\treturn &rr.Data, resp, err\n}\n\n\n\nfunc (s *CloudProService) Delete(sid string) (*CloudProServerResponse, *http.Response, error) {\n\tu := \"/api/v1/cloudpro/delete.php\"\n\n\tparameters := url.Values{}\n\tparameters.Add(\"key\", s.client.Option.Key)\n\tparameters.Add(\"login\", s.client.Option.Login)\n\tparameters.Add(\"sid\", sid)\n\n\treq, err := s.client.NewFormRequest(\"POST\", u, parameters)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tsr := new(CloudProServerResponse)\n\tresp, err := s.client.Do(req, sr)\n\tif err != nil {\n\t\treturn nil, resp, err\n\t}\n\treturn sr, resp, err\n}\n\nfunc (s *CloudProService) Create(opt *CreateServerOptions) (*CloudProServerResponse, *http.Response, error) ", "output": "{\n\tu := \"/api/v1/cloudpro/build.php\"\n\n\tparameters := url.Values{}\n\tparameters.Add(\"key\", s.client.Option.Key)\n\tparameters.Add(\"login\", s.client.Option.Login)\n\tparameters.Add(\"cpu\", opt.Cpu)\n\tparameters.Add(\"os\", opt.OS)\n\tparameters.Add(\"ram\", opt.Ram)\n\tparameters.Add(\"storage\", opt.Storage)\n\tparameters.Add(\"datacenter\", opt.Datacenter)\n\n\treq, err := s.client.NewFormRequest(\"POST\", u, parameters)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tsr := new(CloudProServerResponse)\n\tresp, err := s.client.Do(req, sr)\n\tif err != nil {\n\t\treturn nil, resp, err\n\t}\n\treturn sr, resp, err\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\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 testDummy2() *probe.Error ", "output": "{\n\treturn testDummy1().Trace(\"DummyTag2\")\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\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 (bar Bar) String() string ", "output": "{\n\tpretty := \"\"\n\tfor _, note := range bar {\n\t\tpretty = pretty + note.String()\n\t}\n\treturn pretty\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\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\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) WriteTo(w io.Writer) (n int64, err error) ", "output": "{\n\tbuf := make([]byte, f.EncodedLength())\n\tf.Marshal(buf)\n\tn32, err := w.Write(buf)\n\treturn int64(n32), err\n}"} {"input": "package table2rst\n\nimport (\n\t\"bufio\"\n\t\"fmt\"\n\t\"github.com/PuerkitoBio/goquery\"\n\t\"os\"\n\t\"strings\"\n)\n\nfunc StringToLines(s string) []string {\n\tvar lines []string\n\n\tscanner := bufio.NewScanner(strings.NewReader(s))\n\tfor scanner.Scan() {\n\t\tlines = append(lines, scanner.Text())\n\t}\n\n\tif err := scanner.Err(); err != nil {\n\t\tfmt.Fprintln(os.Stderr, \"reading standard input:\", err)\n\t}\n\n\treturn lines\n}\n\nfunc rstListTablePrefixOfEachLine(indexOfTd, indexOfLine int) string {\n\tif indexOfTd == 0 {\n\t\tif indexOfLine == 0 {\n\t\t\treturn \" * - \"\n\t\t} else {\n\t\t\treturn \" \"\n\t\t}\n\t} else {\n\t\tif indexOfLine == 0 {\n\t\t\treturn \" - \"\n\t\t} else {\n\t\t\treturn \" \"\n\t\t}\n\t}\n}\n\nfunc processTr(tr *goquery.Selection, fRstOutput *os.File) {\n\ttr.Find(\"td\").Each(func(indexOfTd int, td *goquery.Selection) {\n\t\tlines := StringToLines(td.Text())\n\t\tfor indexOfLine, line := range lines {\n\t\t\tline = strings.TrimSpace(line)\n\t\t\tfmt.Fprintf(fRstOutput, rstListTablePrefixOfEachLine(indexOfTd, indexOfLine))\n\t\t\tfmt.Fprintf(fRstOutput, line)\n\t\t\tfmt.Fprintf(fRstOutput, \"\\n\")\n\t\t}\n\t})\n}\n\n\n\nfunc htmlTableToRst(url, outputFilePath string) ", "output": "{\n\tdoc, err := goquery.NewDocument(url)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tfRstOutput, err := os.Create(outputFilePath)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tdoc.Find(\"table\").Each(func(_ int, table *goquery.Selection) {\n\t\tfmt.Fprintf(fRstOutput, \".. list-table:: \\n\\n\")\n\t\ttable.Find(\"tr\").Each(func(_ int, tr *goquery.Selection) {\n\t\t\tprocessTr(tr, fRstOutput)\n\t\t})\n\t\tfmt.Fprintf(fRstOutput, \"\\n\\n\")\n\t\tfmt.Fprintf(fRstOutput, \"|\\n|\\n\\n\")\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\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\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 UIntPtr(p uintptr) uint32 ", "output": "{\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}"} {"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\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) AddPermanentPlug(iface interfaces.Interface, plug *snap.PlugInfo) error ", "output": "{\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}"} {"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\nfunc (s *Stopwatch) Dt() string {\n\treturn fmt.Sprintf(\"%s\", s.ElapsedTime())\n}\n\n\n\nfunc (s *Stopwatch) Log(msg string) ", "output": "{\n\ts.logger.Info(\"elapsed\", \"msg\", msg, \"dx\", s.Dt())\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\nfunc (s *OffState) Enter(m StateMachine) {\n\ts.statusLed.Low()\n}\n\n\n\nfunc (s *OffState) Leave(m StateMachine) {}\n\nfunc (s *OffState) String() string {\n\treturn \"Off\"\n}\n\nfunc (s *OffState) Event(m StateMachine, pin uint, value uint) ", "output": "{\n\tif pin == GPIO_SWITCH_PIN && value == GPIO_SWITCH_ON {\n\t\tm.Transit(STATE_WAITING)\n\t}\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\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\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 NewCT_MailMergeDocType() *CT_MailMergeDocType ", "output": "{\n\tret := &CT_MailMergeDocType{}\n\tret.ValAttr = ST_MailMergeDocType(1)\n\treturn ret\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\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 Unmarshal(data []byte, v interface{}) error ", "output": "{\n\treturn provider.Unmarshal(data, v)\n}"} {"input": "package main\n\nimport \"fmt\"\n\nfunc main() {\n\tf(2)\n\tf(3)\n}\n\n\n\nfunc f(i int) ", "output": "{\n\tswitch i {\n\tcase 1:\n\t\tfmt.Println(\"Un\")\n\tcase 2:\n\t\tfmt.Println(\"Dos\")\n\tcase 3:\n\t\tfmt.Println(\"Tres\")\n\tdefault:\n\t\tpanic(i)\n\t}\n}"} {"input": "package js\n\n\n\n\nfunc Check(files []string, libDir, tstDir string) (string, error) ", "output": "{\n\treturn \"\", 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\nfunc (self *CmdAccountAddTriggers) Name() string {\n\treturn self.name\n}\n\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) RpcMethod() string ", "output": "{\n\treturn self.rpcMethod\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\nfunc (cm *CallbackMetric) Write(m *dto.Metric) error {\n\tm.Untyped = &dto.Untyped{Value: proto.Float64(cm.callback())}\n\treturn nil\n}\n\n\n\nfunc ExampleSelfCollector() ", "output": "{\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}"} {"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\nfunc Start(in io.Reader, out io.Writer) {\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}\n\n\n\nfunc printParserErrors(out io.Writer, errors []string) ", "output": "{\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}"} {"input": "package main\n\n\n\nfunc titleToNumber(s string) int ", "output": "{\n\tr := 0\n\tfor _, c := range s {\n\t\tr = r*26 + (c - 'A' + 1)\n\t}\n\treturn r\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\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 findHubNamed(name string) *Hub ", "output": "{\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}"} {"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\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\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 ExtractGroupVersionKind(list *extensions.ThirdPartyResourceList) ([]unversioned.GroupVersion, []unversioned.GroupVersionKind, error) ", "output": "{\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}"} {"input": "package agent\n\n\n\nimport (\n\t\"fmt\"\n\n\t\"launchpad.net/juju-core/state/api/common\"\n\t\"launchpad.net/juju-core/state/api/params\"\n)\n\n\ntype State struct {\n\tcaller common.Caller\n}\n\n\n\nfunc NewState(caller common.Caller) *State {\n\treturn &State{caller}\n}\n\nfunc (st *State) getEntity(tag string) (*params.AgentGetEntitiesResult, error) {\n\tvar results params.AgentGetEntitiesResults\n\targs := params.Entities{\n\t\tEntities: []params.Entity{{Tag: tag}},\n\t}\n\terr := st.caller.Call(\"Agent\", \"\", \"GetEntities\", args, &results)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif len(results.Entities) != 1 {\n\t\treturn nil, fmt.Errorf(\"expected one result, got %d\", len(results.Entities))\n\t}\n\tif err := results.Entities[0].Error; err != nil {\n\t\treturn nil, err\n\t}\n\treturn &results.Entities[0], nil\n}\n\ntype Entity struct {\n\tst *State\n\ttag string\n\tdoc params.AgentGetEntitiesResult\n}\n\nfunc (st *State) Entity(tag string) (*Entity, error) {\n\tdoc, err := st.getEntity(tag)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &Entity{\n\t\tst: st,\n\t\ttag: tag,\n\t\tdoc: *doc,\n\t}, nil\n}\n\n\nfunc (m *Entity) Tag() string {\n\treturn m.tag\n}\n\n\nfunc (m *Entity) Life() params.Life {\n\treturn m.doc.Life\n}\n\n\n\n\n\nfunc (m *Entity) Jobs() []params.MachineJob {\n\treturn m.doc.Jobs\n}\n\n\n\n\nfunc (m *Entity) SetPassword(password string) error ", "output": "{\n\tvar results params.ErrorResults\n\targs := params.PasswordChanges{\n\t\tChanges: []params.PasswordChange{{\n\t\t\tTag: m.tag,\n\t\t\tPassword: password,\n\t\t}},\n\t}\n\terr := m.st.caller.Call(\"Agent\", \"\", \"SetPasswords\", args, &results)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn results.OneError()\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\nfunc TestSleepFunctionString(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(\"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}\n\n\n\nfunc TestSleepFunctionInt(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(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}"} {"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\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 Walker(t *Tree) <-chan int ", "output": "{\n\tch := make(chan int)\n\tgo func() {\n\t\tWalk(t, ch)\n\t\tclose(ch)\n\t}()\n\treturn ch\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\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 (sr *ServiceResource) GetRouterTable(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\trt := sr.repo.GetRouterTable(string(addr))\n\tc.JSON(http.StatusOK, rt)\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\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 IsAbs(path string) bool ", "output": "{\n\treturn filepath.IsAbs(path)\n}"} {"input": "package ringbuf\n\n\n\n\nfunc (r *Reader) read() (interface{}, bool) {\n\tif r.pos <= r.ring.pos-1 && r.cycles == r.ring.cycles {\n\t\tdata := r.ring.data[r.pos]\n\n\t\tr.pos++\n\n\t\tif r.pos >= r.ring.size {\n\t\t\tr.pos = 0\n\t\t\tr.cycles++\n\t\t}\n\n\t\treturn data, true\n\t}\n\n\tif r.pos >= r.ring.pos-1 && r.cycles >= r.ring.cycles {\n\t\treturn nil, false\n\t}\n\n\tif r.cycles < r.ring.cycles {\n\t\tif r.cycles == r.ring.cycles-1 && r.pos >= r.ring.pos {\n\t\t\tdata := r.ring.data[r.pos]\n\n\t\t\tr.pos++\n\n\t\t\tif r.pos >= r.ring.size {\n\t\t\t\tr.pos = 0\n\t\t\t\tr.cycles++\n\t\t\t}\n\n\t\t\treturn data, true\n\t\t}\n\n\t\tr.cycles = r.ring.cycles\n\t\tr.pos = 1\n\t\treturn r.ring.data[0], false\n\t}\n\n\treturn nil, false\n}\n\nfunc (r *Ringbuf) write(data interface{}) ", "output": "{\n\tif r.pos >= r.size {\n\t\tr.pos = 0\n\t\tr.cycles++\n\t}\n\n\tr.data[r.pos] = data\n\tr.pos++\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"net/http\"\n)\n\n\n\nfunc main() {\n\tfmt.Println(\"starting server\")\n\thttp.HandleFunc(\"/\", DoRequest)\n\thttp.ListenAndServe(\":9090\", nil)\n\tfmt.Println(\"ending server\")\n}\n\nfunc DoRequest(w http.ResponseWriter, r *http.Request) ", "output": "{\n\tr.ParseForm()\n\tw.WriteHeader(200)\n\tfor key, values := range r.Form {\n\t\tw.Write([]byte(fmt.Sprintf(\"%s: %s \\n\", key, values)))\n\t}\n}"} {"input": "package maintenance\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() + \" maintenance/2018-06-01-preview\"\n}\n\n\n\n\nfunc Version() string ", "output": "{\n\treturn version.Number\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\nfunc Init() {\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}\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\n\n\nfunc init() ", "output": "{\n\trevel.InterceptMethod((*Transactional).Begin, revel.BEFORE)\n\trevel.InterceptMethod((*Transactional).Commit, revel.AFTER)\n\trevel.InterceptMethod((*Transactional).Rollback, revel.FINALLY)\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\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) Connect(path string, h Handler) ", "output": "{\n\tg.echo.Connect(path, h)\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\nfunc (this *WebSocketController) Get() {\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}\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\n\n\nfunc broadcastWebSocket(event models.Event) ", "output": "{\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}"} {"input": "package service\n\nimport (\n\t\"context\"\n\t\"net/http\"\n\t\"time\"\n\n\t\"go-common/app/admin/main/upload/model\"\n\n\t\"github.com/pkg/errors\"\n)\n\n\n\n\nfunc (s *Service) UploadAdminRecord(ctx context.Context, action string, up *model.UploadParam, data []byte) (result *model.UploadResult, err error) ", "output": "{\n\tvar (\n\t\tlocation, etag string\n\t\tb *model.Bucket\n\t\tok bool\n\t)\n\tif b, ok = s.bucketCache[up.Bucket]; !ok {\n\t\terr = errors.Errorf(\"read bucket items failed: (%s)\", up.Bucket)\n\t\treturn\n\t}\n\tup.Auth = s.dao.Bfs.Authorize(b.KeyID, b.KeySecret, http.MethodPut, up.Bucket, up.FileName, time.Now().Unix())\n\tif up.ContentType == \"\" {\n\t\tup.ContentType = http.DetectContentType(data)\n\t}\n\tif location, etag, err = s.dao.Bfs.Upload(ctx, up, data); err != nil {\n\t\treturn\n\t}\n\tresult = &model.UploadResult{\n\t\tLocation: location,\n\t\tEtag: etag,\n\t}\n\treturn\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\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\n\n\nfunc (s SectionAliasMap) Grep() string ", "output": "{\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}"} {"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\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, 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}\n\nfunc addRegistryAuthFlag(opt *bool, flags *pflag.FlagSet) ", "output": "{\n\tflags.BoolVar(opt, \"with-registry-auth\", false, \"Send registry authentication details to Swarm agents\")\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\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\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) Connected(a int, b int) bool ", "output": "{\n\treturn q.Root(a) == q.Root(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\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 (b *jsonErrorBuilder) Build() JSONError ", "output": "{\n\treturn b.instance\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\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 (ki keyIncorrect) String() string ", "output": "{\n\treturn \"the given key was incorrect\"\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\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 Includes(c *v32.Constraint, v string) bool ", "output": "{\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}"} {"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\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 (e env) Logger() adapter.Logger ", "output": "{\n\treturn e.logger\n}"} {"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\nfunc StopDog() {\n\treturn\n\tif watchdog {\n\t\twatchdog = false\n\t\tf.Close()\n\t}\n}\n\n\n\nfunc PetDog()", "output": "{\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}"} {"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\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) Printf(format string, a ...interface{}) (n int, err error) ", "output": "{\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}"} {"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\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\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 MatchAll(cs *v32.Constraints, execution *v3.PipelineExecution) bool ", "output": "{\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}"} {"input": "package setup\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"path\"\n\t\"strings\"\n)\n\n\ntype Builder interface {\n\tScheduler() (string, error)\n\tWorker() (string, error)\n\tApiServer() (string, error)\n}\n\nconst repoName = \"github.com/scootdev/scoot\"\n\n\ntype GoBuilder struct {\n\tcmds *Cmds\n\n\tinstalled bool\n\terr error\n\tschedBin string\n\tworkerBin string\n\tapiserverBin string\n}\n\n\nfunc NewGoBuilder(cmds *Cmds) *GoBuilder {\n\treturn &GoBuilder{\n\t\tcmds: cmds,\n\t}\n}\n\nfunc GoPath() (string, error) {\n\tgoPath := os.Getenv(\"GOPATH\")\n\tif goPath == \"\" {\n\t\treturn \"\", fmt.Errorf(\"GOPATH unset; cannot build\")\n\t}\n\treturn strings.Split(goPath, \":\")[0], nil\n}\n\nfunc RepoRoot(goPath string) string {\n\treturn path.Join(goPath, \"src\", repoName)\n}\n\n\n\n\nfunc (b *GoBuilder) Scheduler() (string, error) {\n\tb.install()\n\treturn b.schedBin, b.err\n}\n\nfunc (b *GoBuilder) Worker() (string, error) {\n\tb.install()\n\treturn b.workerBin, b.err\n}\n\nfunc (b *GoBuilder) ApiServer() (string, error) {\n\tb.install()\n\treturn b.apiserverBin, b.err\n}\n\nfunc (b *GoBuilder) install() ", "output": "{\n\tif b.installed {\n\t\treturn\n\t}\n\tb.installed = true\n\tgoPath, err := GoPath()\n\tif err != nil {\n\t\treturn\n\t}\n\trepoDir := RepoRoot(goPath)\n\n\tcmd := b.cmds.Command(\"go\", \"install\", \"./binaries/...\")\n\tcmd.Dir = repoDir\n\tif err := b.cmds.RunCmd(cmd); err != nil {\n\t\tb.err = err\n\t\treturn\n\t}\n\tbinDir := path.Join(goPath, \"bin\")\n\tb.schedBin = path.Join(binDir, \"scheduler\")\n\tb.workerBin = path.Join(binDir, \"workerserver\")\n\tb.apiserverBin = path.Join(binDir, \"apiserver\")\n}"} {"input": "package s3crypto\n\nimport (\n\t\"io\"\n)\n\n\ntype Cipher interface {\n\tEncrypter\n\tDecrypter\n}\n\n\ntype Encrypter interface {\n\tEncrypt(io.Reader) io.Reader\n}\n\n\ntype Decrypter interface {\n\tDecrypt(io.Reader) io.Reader\n}\n\n\n\ntype CryptoReadCloser struct {\n\tBody io.ReadCloser\n\tDecrypter io.Reader\n\tisClosed bool\n}\n\n\nfunc (rc *CryptoReadCloser) Close() error {\n\trc.isClosed = true\n\treturn rc.Body.Close()\n}\n\n\n\n\nfunc (rc *CryptoReadCloser) Read(b []byte) (int, error) ", "output": "{\n\tif rc.isClosed {\n\t\treturn 0, io.EOF\n\t}\n\treturn rc.Decrypter.Read(b)\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\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\nfunc TestGenerate(t *testing.T) {\n i := 1\n for s := range Generate(text, 0) {\n t.Logf(\"Generate: %d) %v\", i, s)\n i++\n }\n}\n\nfunc init() ", "output": "{\n rand.Seed(time.Now().UTC().UnixNano() ^ int64(time.Now().Nanosecond()))\n}"} {"input": "package context_test\n\nimport (\n\t\"fmt\"\n\t\"time\"\n\n\t\"github.com/flynn-examples/go-flynn-example/Godeps/_workspace/src/golang.org/x/net/context\"\n)\n\n\n\nfunc ExampleWithTimeout() ", "output": "{\n\tctx, _ := context.WithTimeout(context.Background(), 100*time.Millisecond)\n\tselect {\n\tcase <-time.After(200 * time.Millisecond):\n\t\tfmt.Println(\"overslept\")\n\tcase <-ctx.Done():\n\t\tfmt.Println(ctx.Err()) \n\t}\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\nfunc (ua *UnsubackPacket) Type() byte {\n\treturn ua.FixedHeader.MessageType\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\n\n\nfunc (ua *UnsubackPacket) Details() Details ", "output": "{\n\treturn Details{Qos: 0, MessageID: ua.MessageID}\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\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\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) Notify() ", "output": "{\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}"} {"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\nfunc NewMessage(templateID string) *Message {\n\treturn &Message{\n\t\tTemplateID: templateID,\n\t}\n}\n\n\n\n\nfunc (msg *Message) SetVar(name string, value string) ", "output": "{\n\tfullName := fmt.Sprintf(\"-%s-\", name)\n\tmsg.Vars[fullName] = value\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\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 (*JSONSerializer) ContentType() string ", "output": "{\n\treturn \"text/json\"\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\n\n\nfunc (p *PipelinesProvider) Run(ctx context.Context, f fn.Function) error {\n\tp.RunInvoked = true\n\treturn p.RunFn(f)\n}\n\nfunc (p *PipelinesProvider) Remove(ctx context.Context, f fn.Function) error {\n\tp.RemoveInvoked = true\n\treturn p.RemoveFn(f)\n}\n\nfunc NewPipelinesProvider() *PipelinesProvider ", "output": "{\n\treturn &PipelinesProvider{\n\t\tRunFn: func(fn.Function) error { return nil },\n\t\tRemoveFn: func(fn.Function) error { return nil },\n\t}\n}"} {"input": "package foo\n\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\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 f(x interface{}) ", "output": "{\n\tswitch t := x.(type) { \n\tcase int:\n\t}\n}"} {"input": "package daemon\n\nimport (\n\tderr \"github.com/docker/docker/api/errors\"\n)\n\n\n\n\nfunc (daemon *Daemon) ContainerUnpause(name string) error ", "output": "{\n\tcontainer, err := daemon.Get(name)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif err := container.unpause(); err != nil {\n\t\treturn derr.ErrorCodeCantUnpause.WithArgs(name, err)\n\t}\n\n\treturn nil\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\nfunc MakeViewPostEndpoint(svc HttpService) endpoint.Endpoint {\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}\n\n\n\nfunc MakeCreatePostEndpoint(svc HttpService) endpoint.Endpoint ", "output": "{\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}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n)\n\nfunc binSearch(searchspace []int, key int) int {\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}\n\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 printSearchResult(a []int, key int) ", "output": "{\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}"} {"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\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 BenchmarkMain(b *testing.B) ", "output": "{\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}"} {"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\n\n\n\n\n\nfunc (n *NetAddress) Network() string {\n\treturn n.Address.Network()\n}\n\nfunc (n *NetAddress) String() string ", "output": "{\n\tpubkey := n.IdentityKey.SerializeCompressed()\n\n\treturn fmt.Sprintf(\"%x@%v\", pubkey, n.Address)\n}"} {"input": "package parsers\n\nimport (\n\t\"regexp\"\n)\n\n\n\ntype AllRecipesDotComParser struct{}\n\n\nfunc (a AllRecipesDotComParser) GetName(data []byte) string {\n\treturn getFirstH1(data)\n}\n\n\n\n\n\nfunc (a AllRecipesDotComParser) GetIngredients(data []byte) []string {\n\n\tre := regexp.MustCompile(`(?sU)
    `)\n\tuls := re.FindAll(data, -1)\n\n\tlist := []string{}\n\tfor _, ul := range uls {\n\n\t\tre = regexp.MustCompile(`(?sU)

    .*

    `)\n\t\tingredients := re.FindAll(ul, -1)\n\n\t\treamt := regexp.MustCompile(`(?sU)(.*)`)\n\t\trename := regexp.MustCompile(`(?sU)(.*)`)\n\n\t\tfor _, ingredient := range ingredients {\n\t\t\tamount := reamt.FindSubmatch(ingredient)\n\t\t\tname := rename.FindSubmatch(ingredient)\n\n\t\t\titem := \"\"\n\n\t\t\tif len(amount) > 1 {\n\t\t\t\titem = string(amount[1])\n\t\t\t}\n\n\t\t\tif len(name) > 1 {\n\t\t\t\tif item != \"\" {\n\t\t\t\t\titem += \" \"\n\t\t\t\t}\n\n\t\t\t\titem += string(name[1])\n\t\t\t}\n\n\t\t\tif item != \"\" {\n\t\t\t\tlist = append(list, cleanField(item))\n\t\t\t}\n\t\t}\n\t}\n\treturn list\n}\n\nfunc (a AllRecipesDotComParser) GetDirections(data []byte) []string ", "output": "{\n\n\tre := regexp.MustCompile(`(?sU)
      .*
    `)\n\tol := re.Find(data)\n\n\tre = regexp.MustCompile(`(?sU)
  • (.*)
  • `)\n\tdirections := re.FindAllSubmatch(ol, -1)\n\n\tlist := []string{}\n\tfor _, dir := range directions {\n\t\tif len(dir) > 1 {\n\t\t\tlist = append(list, cleanField(string(dir[1])))\n\t\t}\n\t}\n\n\treturn list\n}"} {"input": "package compose\n\nimport (\n\t\"github.com/spf13/cobra\"\n)\n\n\nvar createCommand = &cobra.Command{\n\tUse: \"create\",\n\tRun: passthrough,\n\tSilenceUsage: true,\n\tDisableFlagParsing: true,\n}\n\n\nvar createConfiguration struct {\n\thelp bool\n\tforceRecreate bool\n\tnoRecreate bool\n\tnoBuild bool\n\tbuild bool\n}\n\n\n\nfunc init() ", "output": "{\n\n\tflags := createCommand.Flags()\n\n\tflags.BoolVarP(&createConfiguration.help, \"help\", \"h\", false, \"\")\n\tflags.BoolVar(&createConfiguration.help, \"force-recreate\", false, \"\")\n\tflags.BoolVar(&createConfiguration.noRecreate, \"no-recreate\", false, \"\")\n\tflags.BoolVar(&createConfiguration.noBuild, \"no-build\", false, \"\")\n\tflags.BoolVar(&createConfiguration.build, \"build\", false, \"\")\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\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\n\n\n\nfunc (response DeleteLoadBalancerResponse) HTTPResponse() *http.Response {\n\treturn response.RawResponse\n}\n\nfunc (response DeleteLoadBalancerResponse) String() string ", "output": "{\n\treturn common.PointerString(response)\n}"} {"input": "package gomega\n\nimport (\n\t\"fmt\"\n\t\"reflect\"\n\t\"time\"\n)\n\ntype asyncActual struct {\n\tactualInput interface{}\n\ttimeoutInterval time.Duration\n\tpollingInterval time.Duration\n\tfail OmegaFailHandler\n}\n\nfunc newAsyncActual(actualInput interface{}, fail OmegaFailHandler, timeoutInterval time.Duration, pollingInterval time.Duration) *asyncActual {\n\tactualType := reflect.TypeOf(actualInput)\n\tif actualType.Kind() == reflect.Func {\n\t\tif actualType.NumIn() != 0 || actualType.NumOut() != 1 {\n\t\t\tpanic(\"Expected a function with no arguments and one return value.\")\n\t\t}\n\t}\n\n\treturn &asyncActual{\n\t\tactualInput: actualInput,\n\t\tfail: fail,\n\t\ttimeoutInterval: timeoutInterval,\n\t\tpollingInterval: pollingInterval,\n\t}\n}\n\nfunc (actual *asyncActual) Should(matcher OmegaMatcher, optionalDescription ...interface{}) bool {\n\treturn actual.match(matcher, true, optionalDescription...)\n}\n\nfunc (actual *asyncActual) ShouldNot(matcher OmegaMatcher, optionalDescription ...interface{}) bool {\n\treturn actual.match(matcher, false, optionalDescription...)\n}\n\nfunc (actual *asyncActual) buildDescription(optionalDescription ...interface{}) string {\n\tswitch len(optionalDescription) {\n\tcase 0:\n\t\treturn \"\"\n\tdefault:\n\t\treturn fmt.Sprintf(optionalDescription[0].(string), optionalDescription[1:]...) + \"\\n\"\n\t}\n}\nfunc (actual *asyncActual) pollActual() interface{} {\n\tactualType := reflect.TypeOf(actual.actualInput)\n\n\tif actualType.Kind() == reflect.Func && actualType.NumIn() == 0 && actualType.NumOut() == 1 {\n\t\treturn reflect.ValueOf(actual.actualInput).Call([]reflect.Value{})[0].Interface()\n\t}\n\n\treturn actual.actualInput\n}\n\n\n\nfunc (actual *asyncActual) match(matcher OmegaMatcher, desiredMatch bool, optionalDescription ...interface{}) bool ", "output": "{\n\ttimer := time.Now()\n\ttimeout := time.After(actual.timeoutInterval)\n\n\tdescription := actual.buildDescription(optionalDescription...)\n\tmatches, message, err := matcher.Match(actual.pollActual())\n\n\tfor {\n\t\tif err == nil && matches == desiredMatch {\n\t\t\treturn true\n\t\t}\n\n\t\tselect {\n\t\tcase <-time.After(actual.pollingInterval):\n\t\t\tmatches, message, err = matcher.Match(actual.pollActual())\n\t\tcase <-timeout:\n\t\t\terrMsg := \"\"\n\t\t\tif err != nil {\n\t\t\t\terrMsg = \"Error: \" + err.Error()\n\t\t\t}\n\t\t\tactual.fail(fmt.Sprintf(\"Timed out after %.3fs.\\n%s%s%s\", time.Since(timer).Seconds(), description, message, errMsg), 2)\n\t\t\treturn false\n\t\t}\n\t}\n}"} {"input": "package singular\n\nimport (\n\tlog \"github.com/Sirupsen/logrus\"\n)\n\n\nfunc CheckError(msg string, err error) {\n\tif err != nil {\n\t\tlog.Errorf(\"%s: %v\", msg, err)\n\t}\n}\n\n\n\n\nfunc PassOrFatal(msg string, err error) ", "output": "{\n\tif err != nil {\n\t\tlog.Fatalf(\"%s: %v\", msg, err)\n\t}\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\nfunc (m *HealthNotReadyStatus) Validate(formats strfmt.Registry) error {\n\treturn nil\n}\n\n\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) MarshalBinary() ([]byte, error) ", "output": "{\n\tif m == nil {\n\t\treturn nil, nil\n\t}\n\treturn swag.WriteJSON(m)\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\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 *DeleteDeploymentUnauthorized) SetWWWAuthenticate(wWWAuthenticate string) ", "output": "{\n\to.WWWAuthenticate = wWWAuthenticate\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\n\n\nfunc (c *Capture) ID() string {\n\treturn c.ProbePath\n}\n\nfunc (c *CaptureHandler) Name() string ", "output": "{\n\treturn \"capture\"\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\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\n\n\nfunc (c *deadlineConn) Write(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\n\treturn c.Conn.Write(b)\n}"} {"input": "package richtext\n\nimport (\n\t\"fmt\"\n)\n\ntype AnsiFormat8 struct{ ansiFormat }\n\nvar _ Format = &AnsiFormat8{}\n\nvar ansiFormat8 *AnsiFormat8\n\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\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 init() ", "output": "{\n\tansiFormat8 = &AnsiFormat8{}\n\tansiFormat8.init(ansiFormat8)\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\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\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 NewQueue() *queue ", "output": "{\n\treturn &queue{lock: &sync.Mutex{}}\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\nfunc NewConfigStoreMonitor(store model.ConfigStore) Monitor {\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}\n\nfunc (m *configstoreMonitor) ScheduleProcessEvent(configEvent ConfigEvent) {\n\tm.eventCh <- configEvent\n}\n\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 (m *configstoreMonitor) Run(stop <-chan struct{}) ", "output": "{\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}"} {"input": "package math\n\nimport \"jvmgo/ch07/instructions/base\"\nimport \"jvmgo/ch07/rtda\"\n\n\ntype DSUB struct{ base.NoOperandsInstruction }\n\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\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 *DSUB) Execute(frame *rtda.Frame) ", "output": "{\n\tstack := frame.OperandStack()\n\tv2 := stack.PopDouble()\n\tv1 := stack.PopDouble()\n\tresult := v1 - v2\n\tstack.PushDouble(result)\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\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 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 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\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\nfunc (c *userIdentityMappings) Delete(name string) (err error) {\n\terr = c.r.Delete().Resource(\"userIdentityMappings\").Name(name).Do().Error()\n\treturn\n}\n\nfunc newUserIdentityMappings(c *Client) *userIdentityMappings ", "output": "{\n\treturn &userIdentityMappings{\n\t\tr: c,\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\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 *SizeGroup) GetIgnoreHidden() bool ", "output": "{\n\tc := C.gtk_size_group_get_ignore_hidden(v.native())\n\treturn gobool(c)\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\nfunc (h *EchoHandler) CanHandle(sc *gack.SlashCommand) bool {\n\treturn true\n}\n\n\n\n\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) Handle(sc *gack.SlashCommand) (string, error) ", "output": "{\n\treturn fmt.Sprintf(\"%s %s\", sc.Command, sc.Text), nil\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\n\n\ntype gossipCluster struct {\n\tlist *memberlist.Memberlist\n}\n\nfunc (gd *gossipCluster) Members() []Node {\n\n\n\n\treturn nil\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 *gossipDiscovery) Discover(addrs ...string) (RemoteCluster, error) ", "output": "{\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}"} {"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 := 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}\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_, _, err := requireOK(s.c.doRequest(r))\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\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\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 TestPostProcessor_ImplementsPostProcessor(t *testing.T) ", "output": "{\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}"} {"input": "package qb\n\nimport \"testing\"\n\n\n\nfunc BenchmarkUpdateBuilder(b *testing.B) ", "output": "{\n\tb.ResetTimer()\n\tfor i := 0; i < b.N; i++ {\n\t\tUpdate(\"cycling.cyclist_name\").Set(\"id\", \"user_uuid\", \"firstname\", \"stars\").Where(Eq(\"id\")).ToCql()\n\t}\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\nfunc (m Method) err(w http.ResponseWriter, req *http.Request) {\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}\n\n\n\nfunc (m Method) ServeHTTP(w http.ResponseWriter, req *http.Request) ", "output": "{\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}"} {"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\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 GreaterThan(t *testing.T, value, other interface{}) *Matcher ", "output": "{\n\treturn Match(t, value).GreaterThan(other)\n}"} {"input": "package authorizationutil\n\nimport (\n\trbacv1 \"k8s.io/api/rbac/v1\"\n\t\"k8s.io/apiserver/pkg/authentication/serviceaccount\"\n)\n\n\n\nfunc RBACSubjectsToUsersAndGroups(subjects []rbacv1.Subject, defaultNamespace string) (users []string, groups []string) {\n\tfor _, subject := range subjects {\n\n\t\tswitch {\n\t\tcase subject.APIGroup == rbacv1.GroupName && subject.Kind == rbacv1.GroupKind:\n\t\t\tgroups = append(groups, subject.Name)\n\t\tcase subject.APIGroup == rbacv1.GroupName && subject.Kind == rbacv1.UserKind:\n\t\t\tusers = append(users, subject.Name)\n\t\tcase subject.APIGroup == \"\" && subject.Kind == rbacv1.ServiceAccountKind:\n\t\t\tns := defaultNamespace\n\t\t\tif len(subject.Namespace) > 0 {\n\t\t\t\tns = subject.Namespace\n\t\t\t}\n\t\t\tif len(ns) > 0 {\n\t\t\t\tname := serviceaccount.MakeUsername(ns, subject.Name)\n\t\t\t\tusers = append(users, name)\n\t\t\t} else {\n\t\t\t}\n\t\tdefault:\n\t\t}\n\t}\n\n\treturn users, groups\n}\n\nfunc BuildRBACSubjects(users, groups []string) []rbacv1.Subject ", "output": "{\n\tsubjects := []rbacv1.Subject{}\n\n\tfor _, user := range users {\n\t\tsaNamespace, saName, err := serviceaccount.SplitUsername(user)\n\t\tif err == nil {\n\t\t\tsubjects = append(subjects, rbacv1.Subject{Kind: rbacv1.ServiceAccountKind, Namespace: saNamespace, Name: saName})\n\t\t} else {\n\t\t\tsubjects = append(subjects, rbacv1.Subject{Kind: rbacv1.UserKind, APIGroup: rbacv1.GroupName, Name: user})\n\t\t}\n\t}\n\n\tfor _, group := range groups {\n\t\tsubjects = append(subjects, rbacv1.Subject{Kind: rbacv1.GroupKind, APIGroup: rbacv1.GroupName, Name: group})\n\t}\n\n\treturn subjects\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\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 SetSession(uid string, name string, key string) ", "output": "{\n\ts := &Session{UID: uid, Key: key, LastTime: time.Now()}\n\tlock.Lock()\n\tdefer lock.Unlock()\n\tsessions[uid] = s\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\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 FilterNameKana(words []string) func(db *gorm.DB) *gorm.DB ", "output": "{\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}"} {"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\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\n\n\nfunc defaultAdapterErrFunc(rw http.ResponseWriter, req *http.Request, err error) ", "output": "{\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}"} {"input": "package protocol\n\n\n\n\n\ntype Vector []Counter\n\n\ntype Counter struct {\n\tID ShortID\n\tValue uint64\n}\n\n\n\n\nfunc (v Vector) Update(id ShortID) Vector {\n\tfor i := range v {\n\t\tif v[i].ID == id {\n\t\t\tv[i].Value++\n\t\t\treturn v\n\t\t} else if v[i].ID > id {\n\t\t\tnv := make(Vector, len(v)+1)\n\t\t\tcopy(nv, v[:i])\n\t\t\tnv[i].ID = id\n\t\t\tnv[i].Value = 1\n\t\t\tcopy(nv[i+1:], v[i:])\n\t\t\treturn nv\n\t\t}\n\t}\n\treturn append(v, Counter{id, 1})\n}\n\n\n\n\n\n\n\nfunc (v Vector) Copy() Vector {\n\tnv := make(Vector, len(v))\n\tcopy(nv, v)\n\treturn nv\n}\n\n\nfunc (v Vector) Equal(b Vector) bool {\n\treturn v.Compare(b) == Equal\n}\n\n\n\nfunc (v Vector) LesserEqual(b Vector) bool {\n\tcomp := v.Compare(b)\n\treturn comp == Lesser || comp == Equal\n}\n\n\n\nfunc (v Vector) GreaterEqual(b Vector) bool {\n\tcomp := v.Compare(b)\n\treturn comp == Greater || comp == Equal\n}\n\n\nfunc (v Vector) Concurrent(b Vector) bool {\n\tcomp := v.Compare(b)\n\treturn comp == ConcurrentGreater || comp == ConcurrentLesser\n}\n\n\nfunc (v Vector) Counter(id ShortID) uint64 {\n\tfor _, c := range v {\n\t\tif c.ID == id {\n\t\t\treturn c.Value\n\t\t}\n\t}\n\treturn 0\n}\n\nfunc (v Vector) Merge(b Vector) Vector ", "output": "{\n\tvar vi, bi int\n\tfor bi < len(b) {\n\t\tif vi == len(v) {\n\t\t\treturn append(v, b[bi:]...)\n\t\t}\n\n\t\tif v[vi].ID > b[bi].ID {\n\t\t\tn := make(Vector, len(v)+1)\n\t\t\tcopy(n, v[:vi])\n\t\t\tn[vi] = b[bi]\n\t\t\tcopy(n[vi+1:], v[vi:])\n\t\t\tv = n\n\t\t}\n\n\t\tif v[vi].ID == b[bi].ID {\n\t\t\tif val := b[bi].Value; val > v[vi].Value {\n\t\t\t\tv[vi].Value = val\n\t\t\t}\n\t\t}\n\n\t\tif bi < len(b) && v[vi].ID == b[bi].ID {\n\t\t\tbi++\n\t\t}\n\t\tvi++\n\t}\n\n\treturn v\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}\n\n\nfunc init(){\n\tgo teller()\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 teller()", "output": "{\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}"} {"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\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 initialize() ", "output": "{\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}"} {"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\nfunc (s *testHelperSuite) TestGetAggFields(c *C) {\n\taggFields := GetAggFields(s.fields)\n\tc.Assert(aggFields, HasLen, 1)\n}\n\n\n\nfunc (s *testHelperSuite) TestHasAggFields(c *C) ", "output": "{\n\tok := HasAggFields(s.fields)\n\tc.Assert(ok, IsTrue)\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\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) Post(path string, h Handler) ", "output": "{\n\tg.echo.Post(path, h)\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\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\nfunc (p *PointOfInteractionComponent6) AddAssessment() *PointOfInteractionComponentAssessment1 {\n\tnewValue := new(PointOfInteractionComponentAssessment1)\n\tp.Assessment = append(p.Assessment, newValue)\n\treturn newValue\n}\n\nfunc (p *PointOfInteractionComponent6) SetType(value string) ", "output": "{\n\tp.Type = (*POIComponentType4Code)(&value)\n}"} {"input": "package validator\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/concourse/concourse-pipeline-resource/concourse\"\n)\n\n\n\nfunc ValidateTeams(teams []concourse.Team) error ", "output": "{\n\tif teams == nil || len(teams) == 0 {\n\t\treturn fmt.Errorf(\"%s must be provided in source\", \"teams\")\n\t}\n\n\tfor i, team := range teams {\n\t\tif team.Name == \"\" {\n\t\t\treturn fmt.Errorf(\"%s must be provided for team: %d\", \"name\", i)\n\t\t}\n\n\t\tif team.Username == \"\" && team.Password != \"\" {\n\t\t\treturn fmt.Errorf(\"%s must be provided for team: %s\", \"username\", team.Name)\n\t\t}\n\n\t\tif team.Password == \"\" && team.Username != \"\" {\n\t\t\treturn fmt.Errorf(\"%s must be provided for team: %s\", \"password\", team.Name)\n\t\t}\n\t}\n\n\treturn nil\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\nfunc (d DeliverySpeed) MarshalJSON() ([]byte, error) {\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}\n\n\n\n\nfunc (d *DeliverySpeed) UnmarshalJSON(data []byte) error ", "output": "{\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}"} {"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\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\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 Ok(body string) Promise ", "output": "{\n\treturn NewPromise(func(resolve func(x AnyVal) AnyVal) AnyVal {\n\t\treturn resolve(NewPlainResult(http.StatusOK, body))\n\t})\n}"} {"input": "package main\n\nimport (\n \"fmt\"\n \"os/exec\"\n)\n\n\n\nfunc execute() {\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}\n\n\nfunc main(){\n \n fmt.Println(\"Simple Shell\")\n fmt.Println(\"---------------------\")\n \n execute() \n fmt.Println(split(5))\n}\n\nfunc split(x int) (a, b int)", "output": "{\n a := 1\n b := 2\n return\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\nfunc Listxattr(path string) ([]string, error) {\n\treturn nil, nil\n}\n\n\n\n\nfunc Setxattr(path, name string, data []byte) error ", "output": "{\n\treturn nil\n}"} {"input": "package main\n\nimport (\n\t\"github.com/murlokswarm/app\"\n)\n\nvar (\n\tmainWindow app.Contexter\n)\n\n\n\nfunc newWelcomeWindow() app.Contexter ", "output": "{\n\tw := app.NewWindow(app.Window{\n\t\tTitle: \"Write\",\n\t\tWidth: 400,\n\t\tHeight: 580,\n\t\tFixedSize: true,\n\t\tTitlebarHidden: true,\n\n\t\tOnClose: func() bool {\n\t\t\tmainWindow = nil\n\t\t\treturn true\n\t\t},\n\t})\n\n\tw.Mount(&PageWelcome{\n\t\tPage: 0,\n\t\tAnimate: false,\n\t})\n\n\treturn w\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\nfunc (km *hashedKeyMutex) LockKey(id string) {\n\tkm.mutexes[km.hash(id)%len(km.mutexes)].Lock()\n}\n\n\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) UnlockKey(id string) error ", "output": "{\n\tkm.mutexes[km.hash(id)%len(km.mutexes)].Unlock()\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\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\n\n\nfunc (s *Statement8) SetReportNumber(value string) ", "output": "{\n\ts.ReportNumber = (*Max5NumericText)(&value)\n}"} {"input": "package system\n\nimport (\n\t\"testing\"\n\n\t\"github.com/docker/docker/integration-cli/request\"\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\t\"golang.org/x/net/context\"\n)\n\n\n\nfunc TestVersion(t *testing.T) ", "output": "{\n\tclient, err := request.NewClient()\n\trequire.NoError(t, err)\n\n\tversion, err := client.ServerVersion(context.Background())\n\trequire.NoError(t, err)\n\n\tassert.NotNil(t, version.APIVersion)\n\tassert.NotNil(t, version.Version)\n\tassert.NotNil(t, version.MinAPIVersion)\n\tassert.Equal(t, testEnv.DaemonInfo.ExperimentalBuild, version.Experimental)\n\tassert.Equal(t, testEnv.OSType, version.Os)\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\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 ExitPrintError(err error, format string, args ...interface{}) ", "output": "{\n\tExitVerbose(fmt.Sprint(err), format, args...)\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\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 (inv *Inventory) Version() string ", "output": "{\n\treturn common.CollectorVersion\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\nfunc TestLocalDevicesUnmarshalText(t *testing.T) {\n\n\tld1 := &LocalDevices{}\n\terr := ld1.UnmarshalText([]byte(\"scaleio=\"))\n\tassert.NoError(t, err)\n}\n\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 TestLocalDevicesMarshalJSON(t *testing.T) ", "output": "{\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}"} {"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\n\n\nfunc (o OcrRequest) String() string {\n\treturn fmt.Sprintf(\"ImgUrl: %s, EngineType: %s, Preprocessors: %s\", o.ImgUrl, o.EngineType, o.PreprocessorChain)\n}\n\nfunc (ocrRequest *OcrRequest) downloadImgUrl() error ", "output": "{\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}"} {"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\n\n\nfunc getTick(request router.Request) (int, []byte) {\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}\n\nfunc init() ", "output": "{\n\trouter.Register(\"/rest/internal/tick/\", router.GET, nil, nil, getTick)\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\nfunc resolveCallExpr(n *ast.CallExpr, c *Context) bool {\n\treturn false\n}\n\n\n\n\n\n\nfunc TryResolve(n ast.Node, c *Context) bool ", "output": "{\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}"} {"input": "package healthcheck\n\nimport (\n\t\"fmt\"\n\t\"net/http\"\n\t\"strconv\"\n\n\tlog \"github.com/Sirupsen/logrus\"\n)\n\n\n\nfunc StartHealthCheck(port int) error {\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}\n\nfunc healthcheck(w http.ResponseWriter, r *http.Request) ", "output": "{\n\tfmt.Fprint(w, \"ok\")\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\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\n\n\nfunc NewService(name string, port int, dnsName string, secure bool, forceTLS bool, encodedCert string, encodedKey string) Service ", "output": "{\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}"} {"input": "package algorith\n\nimport (\n\t\"bytes\"\n\t\"math/rand\"\n\t\"time\"\n)\n\n\n\n\n\nfunc RandomInt64(min, max int64) int64 {\n\trand.Seed(time.Now().UTC().UnixNano())\n\treturn min + rand.Int63n(max-min)\n}\n\nfunc RandomString(num int) string ", "output": "{\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}"} {"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\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) CDIConfigs() v1beta1.CDIConfigInterface ", "output": "{\n\treturn &FakeCDIConfigs{c}\n}"} {"input": "package eppgo\n\nimport \"fmt\"\n\nconst (\n\tErrorCodeRegisteringWrongType ErrorCode = iota\n\n\tErrorCodeUnknownElement\n)\n\n\ntype ErrorCode int\n\n\n\n\n\n\ntype Error struct {\n\tCode ErrorCode\n\tReference string\n}\n\n\nfunc (e Error) Error() string {\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}\n\nfunc (e ErrorCode) String() string ", "output": "{\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}"} {"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\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 worker(id int, address string, done chan bool, buffers <-chan []byte) ", "output": "{\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}"} {"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\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\nfunc (o *FloatingIP) String() string {\n\treturn fi.TaskAsString(o)\n}\n\nfunc (o *FloatingIP) 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 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}"} {"input": "package main\n\n\n\nfunc Double(i int) int ", "output": "{\n\treturn i * 2\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\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\nfunc getCurrentTime() time.Time {\n\treturn time.Now().Truncate(time.Second)\n}\n\nfunc NewEntry() *Entry ", "output": "{\n\treturn &Entry{\n\t\tMetadata: make(Metadata),\n\t\tCtime: getCurrentTime(),\n\t\tMtime: getCurrentTime(),\n\t}\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\nfunc (m *MaxRateModule) MaxRate() int64 {\n\treturn m.maxRate.Get()\n}\n\n\n\n\n\nfunc (m *MaxRateModule) SetMaxRate(rate int64) ", "output": "{\n\tm.maxRate.Set(rate)\n\tm.rateUpdateChan <- struct{}{}\n}"} {"input": "package apiserver\n\nimport (\n\t\"net/http\"\n)\n\n\ntype MuxHelper struct {\n\tMux Mux\n\tRegisteredPaths []string\n}\n\n\n\nfunc (m *MuxHelper) HandleFunc(path string, handler func(http.ResponseWriter, *http.Request)) {\n\tm.RegisteredPaths = append(m.RegisteredPaths, path)\n\tm.Mux.HandleFunc(path, handler)\n}\n\nfunc (m *MuxHelper) Handle(path string, handler http.Handler) ", "output": "{\n\tm.RegisteredPaths = append(m.RegisteredPaths, path)\n\tm.Mux.Handle(path, handler)\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\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) validateClusters(formats strfmt.Registry) error ", "output": "{\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}"} {"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\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) Unix() int64 ", "output": "{\n\treturn int64(t) / second\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\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 (CertificateSigningRequestSpec) SwaggerDoc() map[string]string ", "output": "{\n\treturn map_CertificateSigningRequestSpec\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\nfunc (s singularSecretary) CheckLease(name string) error {\n\tif name != s.uuid {\n\t\treturn errors.New(\"expected environ UUID\")\n\t}\n\treturn nil\n}\n\n\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) CheckHolder(name string) error ", "output": "{\n\tif _, err := names.ParseMachineTag(name); err != nil {\n\t\treturn errors.New(\"expected machine tag\")\n\t}\n\treturn nil\n}"} {"input": "package tasks_test\n\nimport (\n\t\"testing\"\n\n\t\"github.com/RichardKnop/machinery/v2/tasks\"\n\t\"github.com/stretchr/testify/assert\"\n)\n\n\n\nfunc TestTaskStateIsCompleted(t *testing.T) ", "output": "{\n\tt.Parallel()\n\n\ttaskState := &tasks.TaskState{\n\t\tTaskUUID: \"taskUUID\",\n\t\tState: tasks.StatePending,\n\t}\n\n\tassert.False(t, taskState.IsCompleted())\n\n\ttaskState.State = tasks.StateReceived\n\tassert.False(t, taskState.IsCompleted())\n\n\ttaskState.State = tasks.StateStarted\n\tassert.False(t, taskState.IsCompleted())\n\n\ttaskState.State = tasks.StateSuccess\n\tassert.True(t, taskState.IsCompleted())\n\n\ttaskState.State = tasks.StateFailure\n\tassert.True(t, taskState.IsCompleted())\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\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\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 newFormat() *formatFn ", "output": "{\n\treturn &formatFn{}\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\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 getLibType(lib *memorydll.LazyDLL) int32 ", "output": "{\n\tproc := lib.NewProc(\"DGetLibType\")\n\tr, _, _ := proc.Call()\n\treturn int32(r)\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\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 (it SampleStreamIterator) Metric() metric.Metric ", "output": "{\n\treturn metric.Metric{Metric: it.ss.Metric}\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}\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 BenchmarkTableAmbiguous(b *testing.B) ", "output": "{\n\tbenchSink = benchTable(b, ambiguous)\n}"} {"input": "package multipass\n\nimport (\n\t\"bytes\"\n\t\"crypto/rand\"\n\t\"crypto/rsa\"\n\t\"fmt\"\n\t\"net/http\"\n\t\"testing\"\n)\n\n\n\nfunc TestVerifySignedHeaderFail(t *testing.T) {\n\tpk, err := rsa.GenerateKey(rand.Reader, DefaultKeySize)\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\ttests := []struct {\n\t\tparams string\n\t}{\n\t\t{\"\"},\n\t\t{\"=\"},\n\t\t{\"algo=1\"},\n\t\t{fmt.Sprintf(\"algo=%s\", DefaultAlgo)},\n\t\t{fmt.Sprintf(\"algo=%s; digest=%s\", DefaultAlgo, DefaultDigest)},\n\t\t{fmt.Sprintf(\"algo=%s; digest=%s; signature=\\\"NDI=\\\"\", DefaultAlgo, DefaultDigest)},\n\t}\n\tfor i, test := range tests {\n\t\th := make(http.Header)\n\t\th.Set(\"Multipass-Signature\", test.params)\n\t\terr := VerifySignedHeader(h, &pk.PublicKey)\n\t\tif err == nil {\n\t\t\tt.Errorf(\"test #%d; want %s, got %s\", i, ErrInvalidSignature, err)\n\t\t}\n\t}\n}\n\nfunc TestSignAndVerifySignatureHander(t *testing.T) {\n\th := make(http.Header)\n\th.Add(\"Multipass-Handle\", \"leeloo@dallas\")\n\th.Add(\"Multipass-Origin\", \"127.0.0.2\")\n\tpk, err := rsa.GenerateKey(rand.Reader, DefaultKeySize)\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\tif err := SignHeader(h, pk); err != nil {\n\t\tt.Error(err)\n\t}\n\tif err := VerifySignedHeader(h, &pk.PublicKey); err != nil {\n\t\tt.Error(err)\n\t}\n}\n\nfunc TestConcatonateHeader(t *testing.T) ", "output": "{\n\ttests := []struct {\n\t\theader map[string][]string\n\t\texpect []byte\n\t}{\n\t\t{\n\t\t\theader: map[string][]string{\n\t\t\t\t\"a\": {\"a2\", \"a1\"},\n\t\t\t\t\"b\": {\"b1A\", \"b2\", \"b1B\"},\n\t\t\t\t\" B \": {\"b3\"},\n\t\t\t},\n\t\t\texpect: []byte(\"a:a1,a2\\nb:b1A,b1B,b2,b3\"),\n\t\t},\n\t}\n\tfor i, test := range tests {\n\t\tgot, want := ConcatonateHeader(test.header), test.expect\n\t\tif n := bytes.Compare(got, want); n != 0 {\n\t\t\tt.Errorf(\"test #%d; want %s, got %s\", i, want, got)\n\t\t}\n\t}\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\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 Print(args ...interface{}) ", "output": "{\n\tfmt.Print(\" \")\n\tfmt.Println(args...)\n}"} {"input": "package attachments\n\nimport (\n\t\"io/ioutil\"\n\n\t\"golang.org/x/net/context\"\n)\n\n\n\nfunc Quarantine(ctx context.Context, path string) error ", "output": "{\n\treturn ioutil.WriteFile(path+\":Zone.Identifier\", []byte(\"[ZoneTransfer]\\r\\nZoneId=3\"), 0644)\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\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 NewUTF8Reader(r io.Reader, encoding string) (io.Reader, error) ", "output": "{\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}"} {"input": "package models\n\nimport (\n\t\"testing\"\n\t\"time\"\n)\n\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\nfunc TestGetServiceState(t *testing.T) {\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}\n\nfunc TestSetServiceState(t *testing.T) ", "output": "{\n\terr := SetServiceState(\"testState\", time.Now().UTC(), 1)\n\tif err != nil {\n\t\tt.Error(err)\n\t\treturn\n\t}\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\n\n\nfunc OpenRefsDb(filename string) (*sql.DB, *sql.Stmt, error) {\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}\n\nfunc OpenReposDb(filename string) (*sql.DB, *sql.Stmt, *sql.Stmt, error) ", "output": "{\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}"} {"input": "package ui\n\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\nfunc App() *app {\n\treturn &theApp\n}\n\nfunc About() string ", "output": "{\n\treturn \"go-ui 0.1.1 \"\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\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\n\n\nfunc (response ResetDatabaseParametersResponse) HTTPResponse() *http.Response ", "output": "{\n\treturn response.RawResponse\n}"} {"input": "package utils\n\nimport (\n\t\"bytes\"\n\t\"strings\"\n\n\t\"k8s.io/client-go/util/homedir\"\n)\n\n\n\n\n\nfunc ExpandPath(p string) string {\n\tif strings.HasPrefix(p, \"~/\") {\n\t\tp = homedir.HomeDir() + p[1:]\n\t}\n\n\treturn p\n}\n\nfunc SanitizeString(s string) string ", "output": "{\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}"} {"input": "package devops\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() + \" devops/2019-07-01-preview\"\n}\n\n\n\n\nfunc Version() string ", "output": "{\n\treturn version.Number\n}"} {"input": "package auth0\n\nimport (\n\t\"github.com/GoogleCloudPlatform/terraformer/terraformutils\"\n\t\"gopkg.in/auth0.v5/management\"\n)\n\nvar (\n\tClientAllowEmptyValues = []string{}\n)\n\ntype ClientGenerator struct {\n\tAuth0Service\n}\n\n\n\nfunc (g *ClientGenerator) InitResources() error {\n\tm := g.generateClient()\n\tlist := []*management.Client{}\n\n\tvar page int\n\tfor {\n\t\tl, err := m.Client.List(management.Page(page))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tlist = append(list, l.Clients...)\n\t\tif !l.HasNext() {\n\t\t\tbreak\n\t\t}\n\t\tpage++\n\t}\n\n\tg.Resources = g.createResources(list)\n\treturn nil\n}\n\nfunc (g ClientGenerator) createResources(clients []*management.Client) []terraformutils.Resource ", "output": "{\n\tresources := []terraformutils.Resource{}\n\tfor _, client := range clients {\n\t\tresourceName := *client.ClientID\n\t\tresources = append(resources, terraformutils.NewSimpleResource(\n\t\t\tresourceName,\n\t\t\tresourceName+\"_\"+*client.Name,\n\t\t\t\"auth0_client\",\n\t\t\t\"auth0\",\n\t\t\tClientAllowEmptyValues,\n\t\t))\n\t}\n\treturn resources\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\n\n\nfunc (self *SystemBannerHandler) handleGet(request *restful.Request, response *restful.Response) {\n\tresponse.WriteHeaderAndEntity(http.StatusOK, self.manager.Get())\n}\n\n\nfunc NewSystemBannerHandler(manager SystemBannerManager) SystemBannerHandler {\n\treturn SystemBannerHandler{manager: manager}\n}\n\nfunc (self *SystemBannerHandler) Install(ws *restful.WebService) ", "output": "{\n\tws.Route(\n\t\tws.GET(\"/systembanner\").\n\t\t\tTo(self.handleGet).\n\t\t\tWrites(api.SystemBanner{}))\n}"} {"input": "package linebot\n\nimport (\n\t\"context\"\n\t\"fmt\"\n)\n\n\n\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\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 (client *Client) IssueLinkToken(userID string) *IssueLinkTokenCall ", "output": "{\n\treturn &IssueLinkTokenCall{\n\t\tc: client,\n\t\tuserID: userID,\n\t}\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\n\n\nfunc GetServer(id bson.ObjectId) (*Server, error) {\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}\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 ListServersByBalancer(bal *Balancer) ([]Server, error) ", "output": "{\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}"} {"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\n\n\nfunc NewTestReplicaSpecTemplate() v1.PodTemplateSpec {\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}\n\nfunc SetTestJobCompletionTime(testJob *testjobv1.TestJob) {\n\tnow := metav1.Time{Time: time.Now()}\n\ttestJob.Status.CompletionTime = &now\n}\n\nfunc NewTestJob(worker int) *testjobv1.TestJob ", "output": "{\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}"} {"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\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 bump(x *int) ", "output": "{\n\t*x++\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\nfunc (g *GrossDividendRateFormat21Choice) SetAmount(value, currency string) {\n\tg.Amount = NewActiveCurrencyAnd13DecimalAmount(value, currency)\n}\n\nfunc (g *GrossDividendRateFormat21Choice) AddAmountAndRateStatus() *AmountAndRateStatus1 {\n\tg.AmountAndRateStatus = new(AmountAndRateStatus1)\n\treturn g.AmountAndRateStatus\n}\n\n\n\nfunc (g *GrossDividendRateFormat21Choice) AddRateTypeAndAmountAndRateStatus() *RateTypeAndAmountAndStatus22 ", "output": "{\n\tg.RateTypeAndAmountAndRateStatus = new(RateTypeAndAmountAndStatus22)\n\treturn g.RateTypeAndAmountAndRateStatus\n}"} {"input": "package eval\n\nimport (\n\t\"reflect\"\n)\n\n\n\nfunc EvalIdent(ident *Ident, env Env) (reflect.Value, error) ", "output": "{\n\tif ident.IsConst() {\n\t\treturn ident.Const(), nil\n\t}\n\n\tname := ident.Name\n\tswitch ident.source {\n\tcase EnvVar:\n\t\tfor searchEnv := env; searchEnv != nil; searchEnv = searchEnv.PopScope() {\n\t\t\tif v := searchEnv.Var(name); v.IsValid() {\n\t\t\t\treturn v.Elem(), nil\n\t\t\t}\n\t\t}\n\tcase EnvFunc:\n\t\tfor searchEnv := env; searchEnv != nil; searchEnv = searchEnv.PopScope() {\n\t\t\tif v := searchEnv.Func(name); v.IsValid() {\n\t\t\t\treturn v, nil\n\t\t\t}\n\t\t}\n\t}\n\tpanic(dytc(\"missing identifier '\"+name+\"'\"))\n}"} {"input": "package multipass\n\nimport (\n\t\"bytes\"\n\t\"crypto/rand\"\n\t\"crypto/rsa\"\n\t\"fmt\"\n\t\"net/http\"\n\t\"testing\"\n)\n\nfunc TestConcatonateHeader(t *testing.T) {\n\ttests := []struct {\n\t\theader map[string][]string\n\t\texpect []byte\n\t}{\n\t\t{\n\t\t\theader: map[string][]string{\n\t\t\t\t\"a\": {\"a2\", \"a1\"},\n\t\t\t\t\"b\": {\"b1A\", \"b2\", \"b1B\"},\n\t\t\t\t\" B \": {\"b3\"},\n\t\t\t},\n\t\t\texpect: []byte(\"a:a1,a2\\nb:b1A,b1B,b2,b3\"),\n\t\t},\n\t}\n\tfor i, test := range tests {\n\t\tgot, want := ConcatonateHeader(test.header), test.expect\n\t\tif n := bytes.Compare(got, want); n != 0 {\n\t\t\tt.Errorf(\"test #%d; want %s, got %s\", i, want, got)\n\t\t}\n\t}\n}\n\n\n\nfunc TestSignAndVerifySignatureHander(t *testing.T) {\n\th := make(http.Header)\n\th.Add(\"Multipass-Handle\", \"leeloo@dallas\")\n\th.Add(\"Multipass-Origin\", \"127.0.0.2\")\n\tpk, err := rsa.GenerateKey(rand.Reader, DefaultKeySize)\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\tif err := SignHeader(h, pk); err != nil {\n\t\tt.Error(err)\n\t}\n\tif err := VerifySignedHeader(h, &pk.PublicKey); err != nil {\n\t\tt.Error(err)\n\t}\n}\n\nfunc TestVerifySignedHeaderFail(t *testing.T) ", "output": "{\n\tpk, err := rsa.GenerateKey(rand.Reader, DefaultKeySize)\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\ttests := []struct {\n\t\tparams string\n\t}{\n\t\t{\"\"},\n\t\t{\"=\"},\n\t\t{\"algo=1\"},\n\t\t{fmt.Sprintf(\"algo=%s\", DefaultAlgo)},\n\t\t{fmt.Sprintf(\"algo=%s; digest=%s\", DefaultAlgo, DefaultDigest)},\n\t\t{fmt.Sprintf(\"algo=%s; digest=%s; signature=\\\"NDI=\\\"\", DefaultAlgo, DefaultDigest)},\n\t}\n\tfor i, test := range tests {\n\t\th := make(http.Header)\n\t\th.Set(\"Multipass-Signature\", test.params)\n\t\terr := VerifySignedHeader(h, &pk.PublicKey)\n\t\tif err == nil {\n\t\t\tt.Errorf(\"test #%d; want %s, got %s\", i, ErrInvalidSignature, err)\n\t\t}\n\t}\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\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 ExampleNewStringSetFromStringMapKeys() ", "output": "{\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}"} {"input": "package gc\n\nimport \"strconv\"\n\n\n\nconst _Class_name = \"PxxxPEXTERNPAUTOPAUTOHEAPPPARAMPPARAMOUTPFUNC\"\n\nvar _Class_index = [...]uint8{0, 4, 11, 16, 25, 31, 40, 45}\n\nfunc (i Class) String() string {\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}\n\nfunc _() ", "output": "{\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}"} {"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) {}\n\nfunc (t *tokenNop) info(ctx context.Context, token string, rev uint64) (*AuthInfo, bool) {\n\treturn nil, false\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) genTokenPrefix() (string, error) ", "output": "{ return \"\", nil }"} {"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\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\n\n\nfunc (c *Context) MustGetLogger() logging.Logger ", "output": "{\n\tif c.log == nil {\n\t\tpanic(ErrLoggerNotExist)\n\t}\n\n\treturn c.log\n}"} {"input": "package torus\n\nimport (\n\t\"fmt\"\n)\n\n\ntype Point struct {\n\tR, C int\n}\n\n\n\nfunc (p *Point) String() string ", "output": "{\n\treturn fmt.Sprintf(\"r:%d C:%d\", p.R, p.C)\n}"} {"input": "package image\n\n\n\nfunc hasOSFeature(_ string) bool {\n\treturn false\n}\n\nfunc getOSVersion() string ", "output": "{\n\treturn \"\"\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\n\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) Tracef(msg string, args ...interface{}) ", "output": "{ l.send(TRACE, msg, args...) }"} {"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\nfunc RESTError() {\n\tm.Add(\"RESTErrors\", 1)\n}\n\n\n\nfunc goroutines() interface{} ", "output": "{\n\treturn runtime.NumGoroutine()\n}"} {"input": "package endpoints\n\nimport (\n\t\"net/http\"\n\t\"strings\"\n\n\t\"github.com/justinsb/gova/assert\"\n\t\"github.com/justinsb/gova/log\"\n\t\"github.com/justinsb/gova/rs\"\n\t\"github.com/jxaas/jxaas/auth\"\n)\n\ntype EndpointXaas struct {\n\tAuthenticator auth.Authenticator `inject:\"y\"`\n}\n\ntype Authorization struct {\n\tTenantId string\n\tTenantName string\n}\n\n\n\nfunc (self *EndpointXaas) Item(key string, req *http.Request) (*EndpointTenant, error) ", "output": "{\n\tchild := &EndpointTenant{}\n\n\ttenantId := key\n\ttenantName := strings.Replace(key, \"-\", \"\", -1)\n\n\tassert.That(self.Authenticator != nil)\n\tauthentication := self.Authenticator.Authenticate(tenantId, req)\n\n\tif authentication == nil {\n\t\tlog.Debug(\"Authentication failed\")\n\t\tnotAuthorized := rs.HttpError(http.StatusUnauthorized)\n\t\tnotAuthorized.Headers[\"WWW-Authenticate\"] = \"Basic realm=\\\"jxaas\\\"\"\n\t\treturn nil, notAuthorized\n\t} else {\n\t\tchild.Tenant = tenantName\n\n\t\treturn child, nil\n\t}\n}"} {"input": "package call\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/funcy/functions_go/models\"\n)\n\n\ntype GetCallsCallReader struct {\n\tformats strfmt.Registry\n}\n\n\n\n\n\nfunc NewGetCallsCallOK() *GetCallsCallOK {\n\treturn &GetCallsCallOK{}\n}\n\n\ntype GetCallsCallOK struct {\n\tPayload *models.CallWrapper\n}\n\nfunc (o *GetCallsCallOK) Error() string {\n\treturn fmt.Sprintf(\"[GET /calls/{call}][%d] getCallsCallOK %+v\", 200, o.Payload)\n}\n\nfunc (o *GetCallsCallOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error {\n\n\to.Payload = new(models.CallWrapper)\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 NewGetCallsCallNotFound() *GetCallsCallNotFound {\n\treturn &GetCallsCallNotFound{}\n}\n\n\ntype GetCallsCallNotFound struct {\n\tPayload *models.Error\n}\n\nfunc (o *GetCallsCallNotFound) Error() string {\n\treturn fmt.Sprintf(\"[GET /calls/{call}][%d] getCallsCallNotFound %+v\", 404, o.Payload)\n}\n\nfunc (o *GetCallsCallNotFound) 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 *GetCallsCallReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) ", "output": "{\n\tswitch response.Code() {\n\n\tcase 200:\n\t\tresult := NewGetCallsCallOK()\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 404:\n\t\tresult := NewGetCallsCallNotFound()\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 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\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 (h *StandardHealthcheck) Error() error ", "output": "{\n\treturn h.err\n}"} {"input": "package main\n\nimport (\n\t\"testing\"\n\n\t\"github.com/k0kubun/pp\"\n\n\t_ \"bitbucket.org/ikeikeikeike/antenna/conf/inits\"\n\tlibm \"bitbucket.org/ikeikeikeike/antenna/lib/models\"\n\t\"bitbucket.org/ikeikeikeike/antenna/models\"\n\t\"bitbucket.org/ikeikeikeike/antenna/models/character\"\n\t_ \"bitbucket.org/ikeikeikeike/antenna/routers\"\n)\n\n\n\nfunc TestQuery1(t *testing.T) ", "output": "{\n\tmodels.Pictures().Filter(\"characters__character__name\", \"悟空\").Count()\n\n\tfor _, c := range character.CachedCharacters() {\n\t\tif c.Id > 0 && len([]rune(c.Name)) > 2 && !libm.ReHK3.MatchString(c.Name) {\n\t\t\tpp.Println(c.Name)\n\t\t}\n\t}\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\nfunc FetchPageContents(url string) (string, error) {\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}\n\n\n\nfunc UrlPseudoJoin(path string) string ", "output": "{\n\treturn TwistRoot + strings.TrimSpace(path)\n}"} {"input": "package csv\n\nimport (\n\t\"testing\"\n)\n\nfunc TestParseFile(t *testing.T) {\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}\n\n\n\nfunc TestParseFileDoesNotExists(t *testing.T) ", "output": "{\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}"} {"input": "package parser\n\nimport (\n\t\"monkey/ast\"\n\t\"monkey/token\"\n)\n\n\n\nfunc (p *Parser) parseInterpolatedString() ast.Expression {\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}\n\nfunc (p *Parser) parseStringLiteralExpression() ast.Expression ", "output": "{\n\treturn &ast.StringLiteral{Token: p.curToken, Value: p.curToken.Literal}\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 }\nfunc (a VerticalAlignment) AlignMiddle() bool { return a == AlignMiddle }\n\n\nfunc (a VerticalAlignment) AlignBottom() bool ", "output": "{ return a == AlignBottom }"} {"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\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\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 init() ", "output": "{\n\tparse.Register(\"header.Modifier\", modifierFromJSON)\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\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 TestWrapNarrow(t *testing.T) ", "output": "{\n\texp := \"The\\nquick\\nbrown\\nfox\\njumps\\nover\\nthe\\nlazy\\ndog.\"\n\tif Wrap(text, 5) != exp {\n\t\tt.Fail()\n\t}\n}"} {"input": "package gologger\n\nimport (\n \"fmt\"\n)\n\ntype appender2Console struct {\n}\n\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\nfunc (self *appender2Console) setNext(n logHandler) {\n return\n}\n\nfunc (self *appender2Console) init() error ", "output": "{\n return nil\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\n\n\n\nfunc (p *PubSub) Topic(id string) *pubsub.Topic {\n\treturn p.client.Topic(id)\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 NewPubSub(ctx context.Context, projectID string) (*PubSub, error) ", "output": "{\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}"} {"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\nfunc NewMustRunAs(options *extensions.RunAsUserStrategyOptions) (RunAsUserStrategy, error) {\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}\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\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 (s *mustRunAs) Validate(fldPath *field.Path, _ *api.Pod, _ *api.Container, runAsNonRoot *bool, runAsUser *int64) field.ErrorList ", "output": "{\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}"} {"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\n\n\nfunc ExampleCluster_memberUpdate() {\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}\n\nfunc ExampleCluster_memberRemove() ", "output": "{\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}"} {"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\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\n\n\nfunc VerifyFileCryptoSignature(filename string, sig []byte, pub *rsa.PublicKey) (err error) ", "output": "{\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}"} {"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\nfunc statementRemoveStructInitialization() (a http.Header, b error) {\n\tvar err error\n\n\ta, b = http.Header{}, err\n\n\treturn\n}\n\n\n\nfunc statementRemoveStringArrayMap() map[string][]string ", "output": "{\n\thash := \"ok\"\n\tvar hdr = make(map[string][]string)\n\n\thdr[\"Hash\"] = []string{hash}\n\n\treturn hdr\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\nfunc NewGZipHandler(h http.Handler) http.Handler {\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}\n\n\n\nfunc GzipContent(gzbuff *bytes.Buffer, uncompressedContent []byte) (err error) ", "output": "{\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}"} {"input": "package gzip\n\nimport (\n\t\"compress/gzip\"\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"net/http\"\n\t\"path/filepath\"\n\t\"strings\"\n\t\"sync\"\n\n\t\"github.com/gin-gonic/gin\"\n)\n\nconst (\n\tBestCompression = gzip.BestCompression\n\tBestSpeed = gzip.BestSpeed\n\tDefaultCompression = gzip.DefaultCompression\n\tNoCompression = gzip.NoCompression\n)\n\nfunc Gzip(level int) gin.HandlerFunc {\n\tvar gzPool sync.Pool\n\tgzPool.New = func() interface{} {\n\t\tgz, err := gzip.NewWriterLevel(ioutil.Discard, level)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\treturn gz\n\t}\n\treturn func(c *gin.Context) {\n\t\tif !shouldCompress(c.Request) {\n\t\t\treturn\n\t\t}\n\n\t\tgz := gzPool.Get().(*gzip.Writer)\n\t\tdefer gzPool.Put(gz)\n\t\tgz.Reset(c.Writer)\n\n\t\tc.Header(\"Content-Encoding\", \"gzip\")\n\t\tc.Header(\"Vary\", \"Accept-Encoding\")\n\t\tc.Writer = &gzipWriter{c.Writer, gz}\n\t\tdefer func() {\n\t\t\tgz.Close()\n\t\t\tc.Header(\"Content-Length\", fmt.Sprint(c.Writer.Size()))\n\t\t}()\n\t\tc.Next()\n\t}\n}\n\ntype gzipWriter struct {\n\tgin.ResponseWriter\n\twriter *gzip.Writer\n}\n\nfunc (g *gzipWriter) WriteString(s string) (int, error) {\n\treturn g.writer.Write([]byte(s))\n}\n\nfunc (g *gzipWriter) Write(data []byte) (int, error) {\n\treturn g.writer.Write(data)\n}\n\n\n\nfunc shouldCompress(req *http.Request) bool ", "output": "{\n\tif !strings.Contains(req.Header.Get(\"Accept-Encoding\"), \"gzip\") {\n\t\treturn false\n\t}\n\textension := filepath.Ext(req.URL.Path)\n\tif len(extension) < 4 { \n\t\treturn true\n\t}\n\n\tswitch extension {\n\tcase \".png\", \".gif\", \".jpeg\", \".jpg\":\n\t\treturn false\n\tdefault:\n\t\treturn true\n\t}\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\nfunc Register(name string, adapter Instance) {\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}\n\n\n\n\n\n\nfunc NewCache(adapterName, config string) (adapter Cache, err error) ", "output": "{\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}"} {"input": "package utils\n\nimport (\n\t\"os\"\n\t\"strings\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\n\n\nfunc TestGetProjectDir(t *testing.T) ", "output": "{\n\tast := assert.New(t)\n\tdirs := strings.Split(ProjectPath, string(os.PathSeparator))\n\tlength := len(dirs)\n\tast.Equal(\"JinYongXGo\", dirs[length-1:][0])\n}"} {"input": "package controllers\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/astaxie/beego\"\n)\n\n\ntype MainController struct {\n\tbeego.Controller\n}\n\n\ntype ErrorController struct {\n\tMainController\n}\n\n\nfunc (c *ErrorController) Error404() {\n\tc.Data[\"content\"] = \"page not found\"\n\tc.TplName = \"404.tpl\"\n}\n\n\nfunc (c *ErrorController) Error500() {\n\tc.Data[\"content\"] = \"internal server error\"\n\tc.TplName = \"500.tpl\"\n}\n\n\nfunc (c *ErrorController) ErrorDb() {\n\tc.Data[\"content\"] = \"database is now down\"\n\tc.TplName = \"dberror.tpl\"\n}\n\n\n\n\n\nfunc (c *MainController) Get() {\n\tc.activeContent(\"index\")\n\tsess := c.GetSession(\"portale\")\n\tif sess == nil {\n\t\tc.Redirect(\"/login\", 302)\n\t\treturn\n\t}\n\n\tm := sess.(map[string]interface{})\n\tfmt.Println(\"username is\", m[\"username\"])\n\tfmt.Println(\"logged in at\", m[\"timestamp\"])\n}\n\n\nfunc (c *MainController) Notice() {\n\tsess := c.GetSession(\"portale\")\n\tif sess != nil {\n\t\tc.activeContent(\"noticelog\")\n\t} else {\n\t\tc.activeContent(\"notice\")\n\t}\n\n\tflash := beego.ReadFromRequest(&c.Controller)\n\tfmt.Printf(flash.Data[\"notice\"])\n\tif n, ok := flash.Data[\"notice\"]; ok {\n\t\tc.Data[\"notice\"] = n\n\t}\n}\n\nfunc (c *MainController) activeContent(view string) ", "output": "{\n\tc.Layout = \"basic-layout.tpl\"\n\tc.Data[\"domainname\"] = beego.AppConfig.String(\"appcfgdomainname\")\n\tc.LayoutSections = make(map[string]string)\n\tc.LayoutSections[\"Header\"] = \"header.tpl\"\n\tc.LayoutSections[\"Footer\"] = \"footer.tpl\"\n\tc.TplName = view + \".tpl\"\n\n\tsess := c.GetSession(\"portale\")\n\tif sess != nil {\n\t\tc.Data[\"InSession\"] = 1 \n\t\tm := sess.(map[string]interface{})\n\t\tc.Data[\"First\"] = m[\"first\"]\n\t\tc.Data[\"Admin\"] = m[\"admin\"]\n\t\tc.Data[\"IDkey\"] = m[\"idkey\"]\n\t\tfmt.Println(m[\"portale\"])\n\t\tc.Data[\"Automezzi\"] = m[\"automezzi\"]\n\t}\n}"} {"input": "package assembler\n\nimport (\n\t\"log\"\n\t\"golang.org/x/sys/cpu\"\n)\n\nvar useAVX2, useAVX, useSSE4 bool\n\n\n\nvar logging bool = true\n\nvar Isamax func(x []float32) int\nvar Ismax func(x []float32) int\n\nfunc Init(optimize bool) {\n\tif optimize {\n\t\tIsamax = isamax_asm\n\t\tIsmax = ismax_asm\n\t} else {\n\t\tIsamax = isamax\n\t\tIsmax = ismax\n\t}\n}\n\nfunc init() ", "output": "{\n\n\tuseSSE4 = cpu.X86.HasSSE41\n\tuseAVX = cpu.X86.HasAVX\n\tuseAVX2 = cpu.X86.HasAVX2\n\n\tInit(true)\n\tlog.Printf(\"SSE4: %v\", useSSE4)\n\tlog.Printf(\"AVX: %v\", useAVX)\n\tlog.Printf(\"AVX2: %v\", useAVX2)\n\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\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) Enqueue(value interface{}) ", "output": "{\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}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"net/http\"\n\t\"net/http/httptest\"\n\t\"testing\"\n\n\t\"github.com/julienschmidt/httprouter\"\n\t\"github.com/stretchr/testify/assert\"\n)\n\nfunc doHTTPRequest(method, url string) *http.Response {\n\tclient := &http.Client{\n\t\tTransport: &http.Transport{\n\t\t\tDisableKeepAlives: true,\n\t\t},\n\t}\n\n\trequest, _ := http.NewRequest(method, url, nil)\n\tresponse, _ := client.Do(request)\n\treturn response\n}\n\n\n\nfunc TestHealthzHandler(t *testing.T) ", "output": "{\n\trouter := httprouter.New()\n\trouter.GET(\"/healthz\", HealthzHandler)\n\n\tsrv := httptest.NewServer(router)\n\tdefer srv.Close()\n\n\tresponse := doHTTPRequest(\"GET\", fmt.Sprintf(\"%s/healthz\", srv.URL))\n\tassert.Exactly(t, http.StatusOK, response.StatusCode)\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\n\n\n\nfunc (response GetMonitorResponse) HTTPResponse() *http.Response {\n\treturn response.RawResponse\n}\n\nfunc (response GetMonitorResponse) String() string ", "output": "{\n\treturn common.PointerString(response)\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\nfunc NewCommand() *Command {\n\treturn &Command{\n\t\tStdout: os.Stdout,\n\t}\n}\n\n\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 (cmd *Command) Run(args ...string) error ", "output": "{\n\tfmt.Fprintln(cmd.Stdout, strings.TrimSpace(usage))\n\treturn nil\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\n\n\nfunc init() {\n\n\turlpostfix = \"/\" + SDKAPIPrefix + \"/v\" + strings.Replace(fmt.Sprintf(\"%.1v\", SDKAPIVersion), \".\", \"_\", 100)\n}\n\nfunc NewX509Session(cert *tls.Certificate, url string) (*bambou.Session, *Me) ", "output": "{\n\n\troot := NewMe()\n\turl += urlpostfix\n\n\tsession := bambou.NewX509Session(cert, url, root)\n\n\treturn session, root\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"path\"\n\t\"path/filepath\"\n\t\"runtime\"\n\t\"strings\"\n)\n\ntype tempNamer struct {\n\tprefix string\n}\n\nvar defTempNamer = tempNamer{\".syncthing\"}\n\n\n\nfunc (t tempNamer) TempName(name string) string {\n\ttdir := path.Dir(name)\n\ttname := fmt.Sprintf(\"%s.%s\", t.prefix, path.Base(name))\n\treturn path.Join(tdir, tname)\n}\n\nfunc (t tempNamer) IsTemporary(name string) bool ", "output": "{\n\tif runtime.GOOS == \"windows\" {\n\t\tname = filepath.ToSlash(name)\n\t}\n\treturn strings.HasPrefix(path.Base(name), t.prefix)\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\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\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 NewStack() *Stack ", "output": "{\n\treturn new(Stack)\n\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\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) RetryPolicy() *common.RetryPolicy ", "output": "{\n\treturn request.RequestMetadata.RetryPolicy\n}"} {"input": "package log\n\nimport (\n\t\"os\"\n\t\"testing\"\n)\n\n\n\nfunc TestWithOneWriter(t *testing.T) {\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}\n\nfunc TestInitWithNoArgs(t *testing.T) ", "output": "{\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}"} {"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\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 CreateSequential(name string) (*os.File, error) ", "output": "{\n\treturn os.Create(name)\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\n\n\nfunc (b *BillingServicesTax2) AddPricingAmount() *AmountAndDirection34 {\n\tb.PricingAmount = new(AmountAndDirection34)\n\treturn b.PricingAmount\n}\n\nfunc (b *BillingServicesTax2) SetRate(value string) ", "output": "{\n\tb.Rate = (*DecimalNumber)(&value)\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\nfunc (t *TaxVoucher3) AddBargainDate() *DateAndDateTimeChoice {\n\tt.BargainDate = new(DateAndDateTimeChoice)\n\treturn t.BargainDate\n}\n\n\n\nfunc (t *TaxVoucher3) AddBargainSettlementDate() *DateAndDateTimeChoice ", "output": "{\n\tt.BargainSettlementDate = new(DateAndDateTimeChoice)\n\treturn t.BargainSettlementDate\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\n\n\nfunc newFIFOSet(bundleDir, containerID, processID string, withStdin, withTerminal bool) *containerd.FIFOSet {\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}\n\nfunc pipeName(containerID, processID, name string) string ", "output": "{\n\treturn fmt.Sprintf(`\\\\.\\pipe\\containerd-%s-%s-%s`, containerID, processID, name)\n}"} {"input": "package twiliogo\n\nimport \"net/http\"\n\n\nconst (\n\tIP_MESSAGING_ROOT = \"https://ip-messaging.twilio.com\"\n\tIP_MESSAGING_VERSION = \"v1\"\n\tIP_MESSAGING_ROOT_URL = IP_MESSAGING_ROOT + \"/\" + IP_MESSAGING_VERSION\n)\n\n\ntype TwilioIPMessagingClient struct {\n\tTwilioClient\n}\n\nvar _ Client = &TwilioIPMessagingClient{}\n\n\n\n\nfunc NewIPMessagingClient(accountSid, authToken string) *TwilioIPMessagingClient ", "output": "{\n\trootUrl := IP_MESSAGING_ROOT + \"/\" + IP_MESSAGING_VERSION\n\treturn &TwilioIPMessagingClient{TwilioClient{accountSid: accountSid, authToken: authToken, rootUrl: rootUrl, HTTPClient: &http.Client{}}}\n}"} {"input": "package hcsshim\n\nimport \"github.com/sirupsen/logrus\"\n\n\n\n\n\nfunc CreateLayer(info DriverInfo, id, parent string) error ", "output": "{\n\ttitle := \"hcsshim::CreateLayer \"\n\tlogrus.Debugf(title+\"Flavour %d ID %s parent %s\", info.Flavour, id, parent)\n\n\tinfop, err := convertDriverInfo(info)\n\tif err != nil {\n\t\tlogrus.Error(err)\n\t\treturn err\n\t}\n\n\terr = createLayer(&infop, id, parent)\n\tif err != nil {\n\t\terr = makeErrorf(err, title, \"id=%s parent=%s flavour=%d\", id, parent, info.Flavour)\n\t\tlogrus.Error(err)\n\t\treturn err\n\t}\n\n\tlogrus.Debugf(title+\" - succeeded id=%s parent=%s flavour=%d\", id, parent, info.Flavour)\n\treturn nil\n}"} {"input": "package main\n\ntype Pet struct {\n\tname string\n}\n\n\n\nfunc (p *Pet) SetName(name string) {\n\tp.name = name\n}\n\nfunc (p *Pet) Name() string ", "output": "{\n\treturn p.name\n}"} {"input": "package send\n\nimport (\n\t\"context\"\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"os\"\n\t\"testing\"\n)\n\nfunc BenchmarkAllSenders(b *testing.B) {\n\toutputFileName := getProjectRoot() + string(os.PathSeparator) + \"build\" + string(os.PathSeparator) + \"perf.json\"\n\n\tctx := context.Background()\n\toutput := []interface{}{}\n\tfor _, res := range runAllCases(ctx) {\n\t\tevg, err := res.evergreenPerfFormat()\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\n\t\toutput = append(output, evg...)\n\t}\n\n\tevgOutput, err := json.MarshalIndent(map[string]interface{}{\"results\": output}, \"\", \" \")\n\tif err != nil {\n\t\treturn\n\t}\n\tevgOutput = append(evgOutput, []byte(\"\\n\")...)\n\n\tif outputFileName == \"\" {\n\t\tfmt.Println(string(evgOutput))\n\t} else if err := ioutil.WriteFile(outputFileName, evgOutput, 0644); err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"problem writing file '%s': %s\", outputFileName, err.Error())\n\t\treturn\n\t}\n\n\treturn\n}\n\n\n\nfunc runAllCases(ctx context.Context) []*benchResult ", "output": "{\n\tcases := getAllCases()\n\n\tresults := []*benchResult{}\n\tfor _, bc := range cases {\n\t\tresults = append(results, bc.Run(ctx))\n\t}\n\n\treturn results\n}"} {"input": "package retry\n\nimport (\n\t\"time\"\n)\n\n\ntype ToRetry func() error \n\n\n\n\n\nfunc Do(retries int, sleep time.Duration, toRetry ToRetry) chan error ", "output": "{\n\titeration := 1\n\terrs := make(chan error, retries)\n\tdefer close(errs)\n\n\terr := toRetry()\n\tif err == nil {\n\t\treturn errs\n\t}\n\terrs <- err\n\n\tfor {\n\t\tselect {\n\t\tcase <-time.After(sleep):\n\t\t\tif iteration == retries {\n\t\t\t\treturn errs\n\t\t\t}\n\t\t\terr := toRetry()\n\t\t\tif err != nil {\n\t\t\t\terrs <- err\n\t\t\t} else {\n\t\t\t\terrs := make(chan error, 0)\n\t\t\t\tclose(errs)\n\t\t\t\treturn errs\n\t\t\t}\n\t\t\titeration++\n\t\t}\n\t}\n\treturn errs\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\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 (f *EnumFlag) Type() string ", "output": "{\n\treturn \"{\" + strings.Join(f.vs, \",\") + \"}\"\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\nfunc (b *Block) String() string {\n\treturn fmt.Sprintf(\"[Block %s]\", b.Key())\n}\n\n\n\nfunc (b *Block) Loggable() map[string]interface{} ", "output": "{\n\treturn map[string]interface{}{\n\t\t\"block\": b.Key().String(),\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\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\n\n\nfunc (p *PendingQueryResult) Size() int ", "output": "{\n\treturn len(p.batch)\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\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\nfunc PrettyUniqueToken() string {\n\treturn fmt.Sprintf(\"%d:%s\", time.Now().UnixNano(), NewToken().Hash)\n}\n\nfunc toHash(input []byte) string ", "output": "{\n\thasher := sha256.New()\n\thasher.Write(input)\n\treturn hex.EncodeToString(hasher.Sum(nil))\n}"} {"input": "package internal\n\nimport (\n\t\"io/ioutil\"\n\t\"log\"\n\t\"os\"\n)\n\n\n\nfunc CreateTempDir() (string, func()) ", "output": "{\n\tdir, err := ioutil.TempDir(\"\", \"radigo\")\n\tif err != nil {\n\t\tlog.Fatalf(\"Failed to create temp dir: %s\", err)\n\t}\n\n\treturn dir, func() { os.RemoveAll(dir) }\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\nfunc endpointClient() *gophercloud.ServiceClient {\n\treturn &gophercloud.ServiceClient{Endpoint: endpoint}\n}\n\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 TestGetURL(t *testing.T) ", "output": "{\n\tactual := getURL(endpointClient(), \"foo\")\n\texpected := endpoint + \"images/foo\"\n\tth.CheckEquals(t, expected, actual)\n}"} {"input": "package listener\n\nimport (\n\t\"time\"\n\n\tMQTT \"github.com/eclipse/paho.mqtt.golang\"\n\t\"github.com/golang/protobuf/proto\"\n\t\"github.com/golang/protobuf/ptypes\"\n\t\"github.com/siliconbeacon/iot/messages\"\n\t\"github.com/siliconbeacon/iot/stores/listener/weather\"\n)\n\ntype Listener struct {\n\tclient MQTT.Client\n\tclosing chan chan struct{}\n\tweather chan weather.Readings\n}\n\nfunc New(client MQTT.Client) *Listener {\n\treturn &Listener{\n\t\tclient: client,\n\t}\n}\n\nfunc (l *Listener) Weather() <-chan weather.Readings {\n\treturn l.weather\n}\n\n\n\nfunc (l *Listener) Stop() {\n\tif l.closing != nil {\n\t\twaitc := make(chan struct{})\n\t\tl.closing <- waitc\n\t\t<-waitc\n\t}\n}\n\nfunc deserializeMessage(body []byte) weather.Readings {\n\tpb := &messages.WeatherReadings{}\n\tif err := proto.Unmarshal(body, pb); err != nil {\n\t\treturn nil\n\t}\n\tvar readings weather.Readings\n\n\tbaseTime, _ := ptypes.Timestamp(pb.BaseTime)\n\tfor _, reading := range pb.Readings {\n\t\tdelta := time.Duration(reading.RelativeTimeUs) * time.Microsecond\n\t\treadings = append(readings, &weather.Reading{\n\t\t\tStation: pb.Device,\n\t\t\tTimestamp: baseTime.Add(delta),\n\t\t\tTemperatureDegreesCelsius: reading.TemperatureDegreesC,\n\t\t\tRelativeHumidityPercentage: reading.RelativeHumidityPercentage,\n\t\t})\n\t}\n\treturn readings\n}\n\nfunc (l *Listener) Start(topic string) error ", "output": "{\n\tif token := l.client.Connect(); token.Wait() && token.Error() != nil {\n\t\treturn token.Error()\n\t}\n\n\tvar subscriber MQTT.MessageHandler = func(client MQTT.Client, msg MQTT.Message) {\n\t\treadings := deserializeMessage(msg.Payload())\n\t\tif readings != nil {\n\t\t\tl.weather <- readings\n\t\t}\n\t}\n\tif token := l.client.Subscribe(topic, 0, subscriber); token.Wait() && token.Error() != nil {\n\t\treturn token.Error()\n\t}\n\n\tl.weather = make(chan weather.Readings, 5)\n\tgo func() {\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase waitc := <-l.closing:\n\t\t\t\tl.client.Unsubscribe(topic)\n\t\t\t\tl.client.Disconnect(250)\n\t\t\t\tclose(l.weather)\n\t\t\t\twaitc <- struct{}{}\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}()\n\treturn nil\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\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 TestUpdatePackages(t *testing.T) ", "output": "{\n\tc := setup()\n\tmust(c.InstallPackage(\"request\"))\n\t_, err := c.UpdatePackages()\n\tmust(err)\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\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\n\n\nfunc ExampleIncludeSecond() ", "output": "{\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}"} {"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\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 newWorker(db *sql.DB, wg *sync.WaitGroup) *worker ", "output": "{\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}"} {"input": "package aip0163\n\nimport (\n\t\"github.com/googleapis/api-linter/lint\"\n)\n\n\n\n\nfunc AddRules(r lint.RuleRegistry) error ", "output": "{\n\treturn r.Register(\n\t\t163,\n\t\tdeclarativeFriendlyRequired,\n\t\tsynonyms,\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\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\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) List(label labels.Selector, field fields.Selector) (*authorizationapi.ClusterRoleList, error) ", "output": "{\n\tobj, err := c.Fake.Invokes(FakeAction{Action: \"list-clusterRoles\"}, &authorizationapi.ClusterRoleList{})\n\treturn obj.(*authorizationapi.ClusterRoleList), err\n}"} {"input": "package operations\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"log\"\n\t\"net\"\n\n\t\"golang.org/x/crypto/ssh\"\n)\n\n\n\n\nfunc RemoteRun(user string, addr string, port int, sshKey []byte, cmd string) (string, error) ", "output": "{\n\tsigner, err := ssh.ParsePrivateKey(sshKey)\n\tif err != nil {\n\t\tlog.Fatalf(\"unable to parse private key: %v\", err)\n\t}\n\n\tconfig := &ssh.ClientConfig{\n\t\tUser: user,\n\t\tAuth: []ssh.AuthMethod{\n\t\t\tssh.PublicKeys(signer),\n\t\t},\n\t\tHostKeyCallback: func(string, net.Addr, ssh.PublicKey) error { return nil },\n\t}\n\tclient, err := ssh.Dial(\"tcp\", fmt.Sprintf(\"%s:%d\", addr, port), config)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tsession, err := client.NewSession()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tdefer session.Close()\n\tvar b bytes.Buffer\n\tsession.Stdout = &b \n\n\terr = session.Run(cmd)\n\treturn b.String(), err\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\n\n\nfunc ReadCredentials(path string) *Credentials {\n\traw, err := ioutil.ReadFile(path)\n\tvar credentials Credentials\n\terr = json.Unmarshal(raw, &credentials)\n\te(err)\n\treturn &credentials\n}\n\nfunc e(err error) ", "output": "{\n\tif nil != err {\n\t\tpanic(err)\n\t}\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\nfunc Error(title string, err error) {\n\tlogWithLevel(title, kayvee.Error, M{\"error\": fmt.Sprint(err)})\n}\n\n\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 ErrorDetailed(title string, err error, extras M) ", "output": "{\n\textras[\"error\"] = fmt.Sprint(err)\n\tlogWithLevel(title, kayvee.Error, extras)\n}"} {"input": "package csdb\n\nimport (\n\t\"errors\"\n\t\"os\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\n\n\nfunc TestGetDSN(t *testing.T) ", "output": "{\n\n\ttests := []struct {\n\t\tenv string\n\t\tenvContent string\n\t\terr error\n\t\treturnErr bool\n\t}{\n\t\t{\n\t\t\tenv: \"TEST_CS_1\",\n\t\t\tenvContent: \"Hello\",\n\t\t\terr: errors.New(\"World\"),\n\t\t\treturnErr: false,\n\t\t},\n\t}\n\n\tfor _, test := range tests {\n\t\tos.Setenv(test.env, test.envContent)\n\t\ts, aErr := getDSN(test.env, test.err)\n\t\tassert.Equal(t, test.envContent, s)\n\t\tassert.NoError(t, aErr)\n\n\t\ts, aErr = getDSN(test.env+\"NOTFOUND\", test.err)\n\t\tassert.Equal(t, \"\", s)\n\t\tassert.Error(t, aErr)\n\t\tassert.Equal(t, test.err, aErr)\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\nfunc LatestVersion(installDir string, forceCheckpoint bool) *LatestVersionOption {\n\topt := &LatestVersionOption{\n\t\tforceCheckpoint: forceCheckpoint,\n\t\tinstallDir: installDir,\n\t}\n\n\treturn opt\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\n\n\nfunc latestVersion(forceCheckpoint bool) (string, error) ", "output": "{\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}"} {"input": "package treemap\n\nimport (\n\t\"github.com/emirpasic/gods/containers\"\n\trbt \"github.com/emirpasic/gods/trees/redblacktree\"\n)\n\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\nfunc (iterator *Iterator) Last() bool {\n\treturn iterator.iterator.Last()\n}\n\nfunc assertIteratorImplementation() ", "output": "{\n\tvar _ containers.ReverseIteratorWithKey = (*Iterator)(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\nfunc (wu *workUnit) Value() interface{} {\n\treturn wu.value\n}\n\n\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) Error() error ", "output": "{\n\treturn wu.err\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\nfunc (*astImport) GetStrings() []string { return []string{} }\n\n\n\nfunc (n *astImport) WriteGo(w io.Writer, opts *GenGoOpts) ", "output": "{\n\tif n.alias != \"\" {\n\t\tio.WriteString(w, n.alias+\" \")\n\t}\n\tio.WriteString(w, n.pkgName+\"\\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\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\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) Path(index int) (string, bool) ", "output": "{\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}"} {"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\n\n\n\nfunc (r *noneEndpointReconciler) StopReconciling(serviceName string, ip net.IP, endpointPorts []api.EndpointPort) error {\n\treturn nil\n}\n\nfunc (r *noneEndpointReconciler) ReconcileEndpoints(serviceName string, ip net.IP, endpointPorts []api.EndpointPort, reconcilePorts bool) error ", "output": "{\n\treturn nil\n}"} {"input": "package handler\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"io\"\n)\n\nconst (\n\tNOTIFY_NEVER = iota\n\tNOTIFY_CHANGE\n\tNOTIFY_ALWAYS\n)\n\ntype Handler interface {\n\tHandle(string, io.Reader, error, uint64, chan<- uint64)\n}\n\ntype OpsConfigFileHandler struct {\n\tContent interface{}\n\tResultChannel chan interface{}\n\tOpsConfigChannel chan OpsConfig\n}\n\ntype OpsConfig struct {\n\tUsername string `json:\"username\"`\n\tPassword string `json:\"password\"`\n\tUrl string `json:\"url\"`\n\tInsecure bool `json:\"insecure\"`\n\tCdnName string `json:\"cdnName\"`\n\tHttpListener string `json:\"httpListener\"`\n}\n\n\n\nfunc (handler OpsConfigFileHandler) Listen() ", "output": "{\n\tfor {\n\t\tresult := <-handler.ResultChannel\n\t\tvar toc OpsConfig\n\n\t\terr := json.Unmarshal(result.([]byte), &toc)\n\n\t\tif err != nil {\n\t\t\tfmt.Printf(\"Error unmarshalling JSON: %s\\n\", err)\n\t\t} else {\n\t\t\thandler.OpsConfigChannel <- toc\n\t\t}\n\t}\n}"} {"input": "package websocket\n\n\ntype WSRequest struct {\n\tTopic string `json:\"topic\"`\n}\n\n\nfunc NewWSRequest(topic string) *WSRequest {\n\treturn &WSRequest{\n\t\tTopic: topic,\n\t}\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\n\n\nfunc NewWSResponse(notificationType string, data interface{}, err error) *WSResponse ", "output": "{\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}"} {"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\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) {\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}\n\nfunc scheduleMetric(c *cron.Cron, schedule string, fct func()) ", "output": "{\n\tc.AddFunc(schedule, fct)\n\tif strings.HasPrefix(schedule, \"@every\") {\n\t\tfct()\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\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\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) Lifetime() time.Duration ", "output": "{\n\treturn vp.expires.Sub(vp.date)\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\nfunc (u User) MarshalJSON() ([]byte, error) {\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}\n\n\n\n\nfunc (c *Client) GetUserInfo(user string) (*User, error) ", "output": "{\n\tu := new(User)\n\terr := c.getParsedResponse(\"GET\", fmt.Sprintf(\"/users/%s\", user), nil, nil, u)\n\treturn u, err\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\nfunc dataSourceAwsRedshiftServiceAccount() *schema.Resource {\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}\n\n\n\nfunc dataSourceAwsRedshiftServiceAccountRead(d *schema.ResourceData, meta interface{}) error ", "output": "{\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}"} {"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\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\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) Type() byte ", "output": "{\n\treturn BufferProbeChunkType\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\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\nfunc (p *nonePolicy) GetTopologyHints(s state.State, pod v1.Pod, container v1.Container) map[string][]topologymanager.TopologyHint {\n\treturn nil\n}\n\nfunc NewNonePolicy() Policy ", "output": "{\n\treturn &nonePolicy{}\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\n\n\n\nfunc Version() string {\n\treturn version.Number\n}\n\nfunc UserAgent() string ", "output": "{\n\treturn \"Azure-SDK-For-Go/\" + version.Number + \" policy/2019-01-01\"\n}"} {"input": "package google\n\nimport (\n\t\"fmt\"\n\t\"net/http\"\n\t\"os\"\n\n\t\"context\"\n\n\t\"github.com/otiai10/chant/server/middleware\"\n)\n\n\ntype Client struct {\n\tAPIKey string\n\tCustomSearchEngineID string\n\tReferer string\n\t*http.Client\n}\n\n\n\n\n\nfunc (c *Client) Get(url string) (*http.Response, error) {\n\treq, err := http.NewRequest(\"GET\", url, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif c.Referer != \"\" {\n\t\treq.Header.Set(\"Referer\", c.Referer)\n\t}\n\treturn c.Do(req)\n}\n\nfunc NewClient(ctx context.Context) (*Client, error) ", "output": "{\n\thttpclient := middleware.HTTPClient(ctx)\n\tkey := os.Getenv(\"GOOGLE_SEARCH_API_KEY\")\n\tif key == \"\" {\n\t\treturn nil, fmt.Errorf(\"Requiredd evn var `GOOGLE_SEARCH_API_KEY` is not set, please tell admin to add it to `app/secret.yaml`\")\n\t}\n\tengineID := os.Getenv(\"GOOGLE_SEARCH_ENGINE_ID\")\n\tif engineID == \"\" {\n\t\treturn nil, fmt.Errorf(\"Requiredd evn var `GOOGLE_SEARCH_ENGINE_ID` is not set, please tell admin to add it to `app/secret.yaml`\")\n\t}\n\treturn &Client{\n\t\tAPIKey: key,\n\t\tCustomSearchEngineID: engineID,\n\t\tClient: httpclient,\n\t}, nil\n}"} {"input": "package v1api\n\nimport \"github.com/labstack/echo\"\n\n\n\nfunc GetDeviceStatics(ctx echo.Context) error {\n\treturn ctx.JSON(NotImplemented, apiResponse{})\n}\n\n\n\n\nfunc GetServiceStatics(ctx echo.Context) error ", "output": "{\n\treturn ctx.JSON(NotImplemented, apiResponse{})\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\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) setDataDir(defaultDatadir string) ", "output": "{\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}"} {"input": "package values\n\nimport \"fmt\"\nimport \"strconv\"\n\n\ntype Int int\n\n\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\nfunc (i *Int) String() string {\n\treturn fmt.Sprintf(\"%v\", *i)\n}\n\nfunc NewInt(val int, p *int) *Int ", "output": "{\n\t*p = val\n\treturn (*Int)(p)\n}"} {"input": "package appdir\n\nimport (\n\t\"fmt\"\n\t\"path/filepath\"\n\t\"runtime\"\n\t\"strings\"\n)\n\n\n\nfunc logs(app string) string {\n\treturn filepath.Join(general(app), \"logs\")\n}\n\nfunc general(app string) string ", "output": "{\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}"} {"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\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\nfunc (c *ServerForceLeaveCommand) Run(args []string) int {\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}\n\nfunc (c *ServerForceLeaveCommand) Help() string ", "output": "{\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}"} {"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\n\nfunc DateStampAsString() string {\n\tt := time.Now()\n\treturn \"[\" + YmdToString() + \" \" + fmt.Sprintf(\"%02d\", t.Hour()) + \":\" + fmt.Sprintf(\"%02d\", t.Minute()) + \":\" + fmt.Sprintf(\"%02d\", t.Second()) + \"]\"\n}\n\nfunc YmdToString() string ", "output": "{\n\tt := time.Now()\n\ty, m, d := t.Date()\n\treturn strconv.Itoa(y) + fmt.Sprintf(\"%02d\", m) + fmt.Sprintf(\"%02d\", d)\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\nfunc (h *basicHandler) Handle(argv ...string) (string, error) {\n\treturn h.handler(argv...)\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\n\n\nfunc Simple(responder func(...string) (string, error), help string) CommandHandler ", "output": "{\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}"} {"input": "package main\n\nimport (\n . \"g2d\"\n \"math\"\n)\n\n\n\n\n\nfunc main() {\n a := ToFloat(Prompt(\"a? \"))\n b := ToFloat(Prompt(\"b? \"))\n c := hypotenuse(a, b)\n Alert(c)\n}\n\nfunc hypotenuse(cathetus1, cathetus2 float64) float64 ", "output": "{\n return math.Sqrt(cathetus1*cathetus1 + cathetus2*cathetus2)\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\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 resetSignalSIGWINCH() ", "output": "{\n\tsignal.Reset(syscall.SIGWINCH)\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\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\n\n\nfunc GetEnvAsFloat64OrFallback(key string, defaultValue float64) (float64, error) ", "output": "{\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}"} {"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\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\n\n\nfunc IsFieldListTypePackageType(fieldList *ast.FieldList, position int, info *types.Info, packageSuffix string, typeName string) bool ", "output": "{\n\tt := FieldListType(fieldList, position)\n\n\treturn t != nil && IsPackageFunctionFieldListType(*t, info, packageSuffix, typeName)\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\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\tlog.Print(message)\n\t}\n\tc.ws.Close()\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\n\n\nfunc WsHandler(w http.ResponseWriter, u domain.UserUid, r *http.Request) ", "output": "{\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}"} {"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\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\nfunc (rr *Reader) Read(p []byte) (int, error) {\n\treturn rr.r.Read(p)\n}\n\nfunc New(r io.Reader) *Reader ", "output": "{\n\treturn &Reader{r: r}\n}"} {"input": "package lib_gc_log\n\nimport (\n\t\"io\"\n\t\"log\"\n\t\"os\"\n)\n\n\n\nvar (\n\tTrace *log.Logger\n\tInfo *log.Logger\n\tWarning *log.Logger\n\tError *log.Logger\n)\n\nvar LogLevel LOG_LEVEL = TRACE\n\nfunc Init(\n\ttraceHandle io.Writer,\n\tinfoHandle io.Writer,\n\twarningHandle io.Writer,\n\terrorHandle io.Writer) {\n\n\tTrace = log.New(traceHandle,\n\t\t\"TRACE: \",\n\t\tlog.Ldate|log.Ltime|log.Lmicroseconds|log.Lshortfile)\n\n\tInfo = log.New(infoHandle,\n\t\t\"INFO: \",\n\t\tlog.Ldate|log.Ltime|log.Lmicroseconds|log.Lshortfile)\n\n\tWarning = log.New(warningHandle,\n\t\t\"WARNING: \",\n\t\tlog.Ldate|log.Ltime|log.Lmicroseconds|log.Lshortfile)\n\n\tError = log.New(errorHandle,\n\t\t\"ERROR: \",\n\t\tlog.Ldate|log.Ltime|log.Lmicroseconds|log.Lshortfile)\n}\n\nfunc init() ", "output": "{\n\tInit(os.Stdout, os.Stdout, os.Stdout, os.Stdout)\n}"} {"input": "package boottest\n\nimport (\n\t\"strings\"\n\n\t\"github.com/snapcore/snapd/asserts\"\n\t\"github.com/snapcore/snapd/snap\"\n)\n\ntype mockDevice struct {\n\tbootSnap string\n\tmode string\n\tuc20 bool\n\n\tmodel *asserts.Model\n}\n\n\n\n\n\n\n\n\n\n\n\n\nfunc MockUC20Device(mode string, model *asserts.Model) snap.Device {\n\tif mode == \"\" {\n\t\tmode = \"run\"\n\t}\n\tif model == nil {\n\t\tmodel = MakeMockUC20Model()\n\t}\n\treturn &mockDevice{\n\t\tbootSnap: model.Kernel(),\n\t\tmode: mode,\n\t\tuc20: true,\n\t\tmodel: model,\n\t}\n}\n\nfunc snapAndMode(str string) (snap, mode string, uc20 bool) {\n\tparts := strings.SplitN(string(str), \"@\", 2)\n\tif len(parts) == 1 || parts[1] == \"\" {\n\t\treturn parts[0], \"run\", false\n\t}\n\treturn parts[0], parts[1], true\n}\n\nfunc (d *mockDevice) Kernel() string { return d.bootSnap }\nfunc (d *mockDevice) Classic() bool { return d.bootSnap == \"\" }\nfunc (d *mockDevice) RunMode() bool { return d.mode == \"run\" }\nfunc (d *mockDevice) HasModeenv() bool { return d.uc20 }\nfunc (d *mockDevice) Base() string {\n\tif d.model != nil {\n\t\treturn d.model.Base()\n\t}\n\treturn d.bootSnap\n}\nfunc (d *mockDevice) Model() *asserts.Model {\n\tif d.model == nil {\n\t\tpanic(\"Device.Model called but MockUC20Device not used\")\n\t}\n\treturn d.model\n}\n\nfunc MockDevice(s string) snap.Device ", "output": "{\n\tbootsnap, mode, uc20 := snapAndMode(s)\n\tif uc20 && bootsnap == \"\" {\n\t\tpanic(\"MockDevice with no snap name and @mode is unsupported\")\n\t}\n\treturn &mockDevice{\n\t\tbootSnap: bootsnap,\n\t\tmode: mode,\n\t\tuc20: uc20,\n\t}\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\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 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\nfunc Get() apimachineryversion.Info {\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}\n\n\n\nfunc init() ", "output": "{\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}"} {"input": "package ray\n\nimport (\n\t\"github.com/v2ray/v2ray-core/common/alloc\"\n)\n\nconst (\n\tbufferSize = 128\n)\n\n\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\nfunc (this *directRay) InboundOutput() <-chan *alloc.Buffer {\n\treturn this.Output\n}\n\nfunc NewRay() Ray ", "output": "{\n\treturn &directRay{\n\t\tInput: make(chan *alloc.Buffer, bufferSize),\n\t\tOutput: make(chan *alloc.Buffer, bufferSize),\n\t}\n}"} {"input": "package pretty\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\n\t\"github.com/MakeNowJust/heredoc\"\n)\n\n\n\n\n\n\nfunc LongDesc(s string) string {\n\ts = heredoc.Doc(s)\n\ts = strings.TrimSpace(s)\n\treturn s\n}\n\nfunc Bash(s string) string ", "output": "{\n\treturn fmt.Sprintf(\"`%s`\", s)\n}"} {"input": "package overlayutils \n\nimport (\n\t\"fmt\"\n\n\t\"github.com/docker/docker/daemon/graphdriver\"\n)\n\n\n\n\nfunc ErrDTypeNotSupported(driver, backingFs string) error ", "output": "{\n\tmsg := fmt.Sprintf(\"%s: the backing %s filesystem is formatted without d_type support, which leads to incorrect behavior.\", driver, backingFs)\n\tif backingFs == \"xfs\" {\n\t\tmsg += \" Reformat the filesystem with ftype=1 to enable d_type support.\"\n\t}\n\tmsg += \" Backing filesystems without d_type support are not supported.\"\n\n\treturn graphdriver.NotSupportedError(msg)\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\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\nfunc (this *SCmd) mainWorker() {\n\tfor strCmd := range this.m_chanStringCmd {\n\t\tthis.m_funcDoCmd(strCmd)\n\t}\n}\n\nfunc NewSCmd(funcDoCmd func(string)) *SCmd ", "output": "{\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}"} {"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\nfunc (response GetVolumeKmsKeyResponse) String() string {\n\treturn common.PointerString(response)\n}\n\n\n\n\nfunc (response GetVolumeKmsKeyResponse) HTTPResponse() *http.Response ", "output": "{\n\treturn response.RawResponse\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\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\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 ManifestValidateType(value interface{}) error ", "output": "{\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}"} {"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\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\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) triggerError() error ", "output": "{\n\tif t.TriggerError {\n\t\treturn errors.New(\"Artificial error triggered in testSyslogger\")\n\t}\n\n\treturn nil\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 }\nfunc (t *tokenNop) info(ctx context.Context, token string, rev uint64) (*AuthInfo, bool) {\n\treturn nil, false\n}\n\nfunc newTokenProviderNop() (*tokenNop, error) {\n\treturn &tokenNop{}, nil\n}\n\nfunc (t *tokenNop) assign(ctx context.Context, username string, revision uint64) (string, error) ", "output": "{\n\treturn \"\", ErrAuthFailed\n}"} {"input": "package grace\n\nimport \"net/http\"\n\ntype ServeMux struct {\n\thttp.ServeMux\n}\n\n\nfunc (sm *ServeMux) HandleFunc(pattern string, handler func(http.ResponseWriter, *http.Request)) {\n\tsm.Handle(pattern, HandlerFunc(handler))\n}\n\n\n\n\n\nvar DefaultServeMux = NewServeMux()\n\nfunc NewServeMux() *ServeMux ", "output": "{ return &ServeMux{*http.NewServeMux()} }"} {"input": "package controllers\n\nimport (\n\tlog \"github.com/Sirupsen/logrus\"\n\t\"weibo.com/opendcp/imagebuild/code/errors\"\n\t\"weibo.com/opendcp/imagebuild/code/web/models\"\n)\n\n\ntype ProjectCloneController struct {\n\tBasicController\n}\n\n\n\nfunc (c *ProjectCloneController) Post() ", "output": "{\n\tsrcProjectName := c.GetString(\"srcProjectName\")\n\tdstProjectName := c.GetString(\"dstProjectName\")\n\tcreator := c.Operator()\n\tif creator == \"\" || srcProjectName == \"\" || dstProjectName == \"\" {\n\t\tlog.Error(\"creator,srcProjectName,dstProjectName should not be empy when building project\")\n\t\tresp := models.BuildResponse(\n\t\t\terrors.PARAMETER_INVALID,\n\t\t\t-1,\n\t\t\terrors.ErrorCodeToMessage(errors.PARAMETER_INVALID))\n\n\t\tc.Data[\"json\"] = resp\n\t\tc.ServeJSON(true)\n\t\treturn\n\t}\n\t_, projectInfo := models.AppServer.GetProjectInfo(srcProjectName)\n\n\t_, code := models.AppServer.CloneProject(srcProjectName, dstProjectName, creator, projectInfo.Cluster, projectInfo.DefineDockerFileType)\n\tresponse := models.BuildResponse(code, \"\", errors.ErrorCodeToMessage(code))\n\tc.Data[\"json\"] = response\n\tc.ServeJSON(true)\n\treturn\n}"} {"input": "package kiiroo\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"runtime\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/funjack/launchcontrol/protocol\"\n)\n\n\nvar scenario = \"{1.00:1,1.50:4,1.51:4,1.51:3,1.52:4,1.66:1,1.84:2,1.85:3,1.90:4,1.95:1,2.00:2,2.20:4,2.45:2}\"\n\nfunc playerwithscenario(scenario string) (protocol.Player, error) {\n\tb := bytes.NewBufferString(scenario)\n\treturn Load(b)\n}\n\ntype actionValidator struct {\n\tLastPostion int\n\tLastTime time.Duration\n}\n\n\n\nfunc (a *actionValidator) Validate(p int, t time.Duration) error {\n\tdefer func() {\n\t\ta.LastPostion = p\n\t\ta.LastTime = t\n\t}()\n\n\tif p == a.LastPostion {\n\t\treturn fmt.Errorf(\"received the same position in a row\")\n\t}\n\tif a.LastTime > 0 && (t-a.LastTime) < (time.Millisecond*150) {\n\t\treturn fmt.Errorf(\"time between events not big enough: %s\", t-a.LastTime)\n\t}\n\treturn nil\n}\n\n\n\nfunc TestPlay(t *testing.T) ", "output": "{\n\tif runtime.GOOS == \"darwin\" {\n\t\tt.Skip(\"don't run timing tests on darwin #17610\")\n\t}\n\n\tk, err := playerwithscenario(scenario)\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\n\tav := actionValidator{}\n\tstarttime := time.Now()\n\tfor a := range k.Play() {\n\t\teventtime := time.Now().Sub(starttime)\n\t\tt.Logf(\"Action: %s: %d,%d\", eventtime, a.Position, a.Speed)\n\t\tif err := av.Validate(a.Position, eventtime); err != nil {\n\t\t\tt.Error(err)\n\t\t}\n\t}\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\nfunc TestLoadFromURL(t *testing.T) {\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}\n\n\n\nfunc TestLoadFromURLError(t *testing.T) ", "output": "{\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}"} {"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\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\n\n\nfunc (s *Service) decrypt(text string) (string, error) ", "output": "{\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}"} {"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\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 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\nfunc TestIp(t *testing.T) {\n\tRegisterFailHandler(Fail)\n\tjunitReporter := reporters.NewJUnitReporter(\"../report/ip_suite.xml\")\n\tRunSpecsWithDefaultAndCustomReporters(t, \"IP Suite\", []Reporter{junitReporter})\n}\n\n\n\nfunc init() ", "output": "{\n\ttestutils.HookLogrusForGinkgo()\n\tlogrus.AddHook(&logutils.ContextHook{})\n\tlogrus.SetFormatter(&logutils.Formatter{})\n}"} {"input": "package assertions\n\nimport (\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"os\"\n\t\"os/exec\"\n)\n\nfunc Diffb(a string, b string) []byte {\n\n\tdirpath := NewSimpleTempDir(\"diffdir_\")\n\tdefer os.RemoveAll(dirpath)\n\n\tfa := SimpleTempFile(dirpath)\n\tfmt.Fprintf(fa, \"%s\\n\", a)\n\tfa.Close()\n\n\tfb := SimpleTempFile(dirpath)\n\tfmt.Fprintf(fb, \"%s\\n\", b)\n\tfb.Close()\n\n\tco, err := exec.Command(\"diff\", \"-b\", fa.Name(), fb.Name()).CombinedOutput()\n\tif err != nil {\n\t}\n\treturn co\n}\n\n\n\nfunc SimpleTempFile(dirpath string) *os.File {\n\n\tf, err := ioutil.TempFile(dirpath, \"diff_file_\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn f\n}\n\nfunc NewSimpleTempDir(prefix string) string ", "output": "{\n\tdirpath, err := ioutil.TempDir(\".\", prefix)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn dirpath\n}"} {"input": "package inputs\n\nimport (\n\t\"fmt\"\n)\n\n\ntype DiskIO struct {\n\tbaseInput\n}\n\n\n\n\n\nfunc (d *DiskIO) UnmarshalTOML(data interface{}) error {\n\treturn nil\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) PluginName() string ", "output": "{\n\treturn \"diskio\"\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\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\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 (h *Style) ServeHTTP(res http.ResponseWriter, req *http.Request) ", "output": "{\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}"} {"input": "package argerror\n\nimport \"testing\"\n\n\n\nfunc TestNew(t *testing.T) ", "output": "{\n\tmessage := \"Hello\"\n\targs := map[string]string{\n\t\t\"arg\": \"Arg value\",\n\t\t\"barg\": \"Barg\\nvalue\\nbaz\",\n\t}\n\tvar err error = New(message, args)\n\tactual := err.Error()\n\texpected := \"Hello; arg=\\\"Arg value\\\" barg=\\\"Barg value baz\\\"\"\n\tif actual != expected {\n\t\tt.Errorf(\"Expected error to be '%s', but was '%s'\", expected, actual)\n\t}\n}"} {"input": "package options\n\nimport (\n\t\"time\"\n\n\tgenericoptions \"k8s.io/kubernetes/pkg/genericapiserver/options\"\n\n\t\"github.com/spf13/pflag\"\n)\n\n\ntype ServerRunOptions struct {\n\tGenericServerRunOptions *genericoptions.ServerRunOptions\n\tEtcd *genericoptions.EtcdOptions\n\tSecureServing *genericoptions.SecureServingOptions\n\tInsecureServing *genericoptions.ServingOptions\n\tAuthentication *genericoptions.BuiltInAuthenticationOptions\n\tAuthorization *genericoptions.BuiltInAuthorizationOptions\n\n\tEventTTL time.Duration\n}\n\n\n\n\n\nfunc (s *ServerRunOptions) AddFlags(fs *pflag.FlagSet) {\n\ts.GenericServerRunOptions.AddUniversalFlags(fs)\n\ts.Etcd.AddFlags(fs)\n\ts.SecureServing.AddFlags(fs)\n\ts.InsecureServing.AddFlags(fs)\n\ts.Authentication.AddFlags(fs)\n\ts.Authorization.AddFlags(fs)\n\n\tfs.DurationVar(&s.EventTTL, \"event-ttl\", s.EventTTL,\n\t\t\"Amount of time to retain events. Default is 1h.\")\n}\n\nfunc NewServerRunOptions() *ServerRunOptions ", "output": "{\n\ts := ServerRunOptions{\n\t\tGenericServerRunOptions: genericoptions.NewServerRunOptions(),\n\t\tEtcd: genericoptions.NewEtcdOptions(),\n\t\tSecureServing: genericoptions.NewSecureServingOptions(),\n\t\tInsecureServing: genericoptions.NewInsecureServingOptions(),\n\t\tAuthentication: genericoptions.NewBuiltInAuthenticationOptions().WithAll(),\n\t\tAuthorization: genericoptions.NewBuiltInAuthorizationOptions(),\n\n\t\tEventTTL: 1 * time.Hour,\n\t}\n\treturn &s\n}"} {"input": "package gomposer\n\nimport (\n\t\"os\"\n\t\"testing\"\n)\n\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\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_Folder(t *testing.T) ", "output": "{\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}"} {"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\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\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 LoggingMiddleware(c *mv.Context) ", "output": "{\n\tlog.Println(\"Simluate real logging here\")\n\tc.Next()\n}"} {"input": "package css\n\nfunc checkSubArraySum(nums []int, k int) bool {\n\treturn bruteForce(nums, k)\n}\n\n\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 bruteForce(nums []int, k int) bool ", "output": "{\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}"} {"input": "package action\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n)\n\ntype catalogNode struct {\n\t*config\n}\n\n\n\nfunc (c *catalogNode) CommandFlags() *flag.FlagSet {\n\treturn c.newFlagSet(FLAG_DATACENTER, FLAG_CONSISTENCY, FLAG_OUTPUT, FLAG_BLOCKING)\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 CatalogNodeAction() Action ", "output": "{\n\treturn &catalogNode{\n\t\tconfig: &gConfig,\n\t}\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\n\n\nfunc (matcher *BeEquivalentToMatcher) NegatedFailureMessage(actual interface{}) (message string) {\n\treturn format.Message(actual, \"not to be equivalent to\", matcher.Expected)\n}\n\nfunc (matcher *BeEquivalentToMatcher) FailureMessage(actual interface{}) (message string) ", "output": "{\n\treturn format.Message(actual, \"to be equivalent to\", matcher.Expected)\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\n\n\nfunc (iotDaemonSetList *IotDaemonSetList) GetObjectKind() schema.ObjectKind {\n\treturn &iotDaemonSetList.TypeMeta\n}\n\nfunc (iotDaemonSetList *IotDaemonSetList) GetListMeta() metav1.List {\n\treturn &iotDaemonSetList.Metadata\n}\n\nfunc (iotDaemonSet *IotDaemonSet) GetObjectMeta() *metav1.ObjectMeta ", "output": "{\n\treturn &iotDaemonSet.Metadata\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\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\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 ReadData(path string) []byte ", "output": "{\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}"} {"input": "package net_sniff\n\nimport (\n\t\"encoding/asn1\"\n\n\t\"github.com/bettercap/bettercap/packets\"\n\n\t\"github.com/google/gopacket\"\n\t\"github.com/google/gopacket/layers\"\n\n\t\"github.com/evilsocket/islazy/tui\"\n)\n\n\n\nfunc krb5Parser(ip *layers.IPv4, pkt gopacket.Packet, udp *layers.UDP) bool ", "output": "{\n\tif udp.DstPort != 88 {\n\t\treturn false\n\t}\n\n\tvar req packets.Krb5Request\n\t_, err := asn1.UnmarshalWithParams(udp.Payload, &req, packets.Krb5AsReqParam)\n\tif err != nil {\n\t\treturn false\n\t}\n\n\tif s, err := req.String(); err == nil {\n\t\tNewSnifferEvent(\n\t\t\tpkt.Metadata().Timestamp,\n\t\t\t\"krb5\",\n\t\t\tip.SrcIP.String(),\n\t\t\tip.DstIP.String(),\n\t\t\tnil,\n\t\t\t\"%s %s -> %s : %s\",\n\t\t\ttui.Wrap(tui.BACKRED+tui.FOREBLACK, \"krb-as-req\"),\n\t\t\tvIP(ip.SrcIP),\n\t\t\tvIP(ip.DstIP),\n\t\t\ts,\n\t\t).Push()\n\n\t\treturn true\n\t}\n\n\treturn false\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\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) checkAircrafts(allPackages *CslPackages) ", "output": "{\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}"} {"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\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 StringEquals(t *testing.T, actual string, expected string) ", "output": "{\n\tif actual != expected {\n\t\tt.Fatalf(\"%#v != %#v\", actual, expected)\n\t}\n}"} {"input": "package eventsource\n\nimport (\n\t\"bytes\"\n\t\"log\"\n\t\"strings\"\n\t\"testing\"\n\t\"time\"\n)\n\n\n\nfunc TestDefaultMetricsEventDone(t *testing.T) ", "output": "{\n\tbuf := new(bytes.Buffer)\n\tlog.SetOutput(buf)\n\tm := DefaultMetrics{}\n\te := DefaultEvent{}\n\tvar d time.Duration\n\tc := []time.Duration{1, 2, 3, 4, 5, 6}\n\tm.EventDone(e, d, c)\n\tline := buf.String()\n\tresult := line[0 : len(line)-1]\n\texpecting := \"Event completed - clients 6, avg time 3.50\"\n\tif !strings.Contains(result, expecting) {\n\t\tt.Errorf(\"expected:\\n%s\\nto be contained in:\\n%s\\n\", expecting, result)\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\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 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\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\n\n\nfunc (e UserAllreadyExists) Error() string ", "output": "{\n\treturn fmt.Sprintf(\"A user with this data allreay exists: %v\", e.existingUser)\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\nfunc TestAccFirestoreIndex_firestoreIndexBasicExample(t *testing.T) {\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}\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\n\n\nfunc testAccCheckFirestoreIndexDestroyProducer(t *testing.T) func(s *terraform.State) error ", "output": "{\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}"} {"input": "package app\n\nimport (\n\t\"k8s.io/kubernetes/pkg/controller/disruption\"\n\t\"k8s.io/kubernetes/pkg/runtime/schema\"\n)\n\n\n\nfunc startDisruptionController(ctx ControllerContext) (bool, error) ", "output": "{\n\tif !ctx.AvailableResources[schema.GroupVersionResource{Group: \"policy\", Version: \"v1beta1\", Resource: \"poddisruptionbudgets\"}] {\n\t\treturn false, nil\n\t}\n\tgo disruption.NewDisruptionController(\n\t\tctx.InformerFactory.Pods().Informer(),\n\t\tctx.ClientBuilder.ClientOrDie(\"disruption-controller\"),\n\t).Run(ctx.Stop)\n\treturn true, nil\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\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\nfunc (l *logWriter) Close() {\n\tl.lock.Lock()\n\tdefer l.lock.Unlock()\n\tclose(l.log)\n}\n\nfunc NewLogWriter(h func(string)) *logWriter ", "output": "{\n\tret := &logWriter{\n\t\tlog: make(chan string, 100),\n\t\thandler: h,\n\t}\n\tgo ret.handle()\n\treturn ret\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\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\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 NewGetEndpointOK() *GetEndpointOK ", "output": "{\n\n\treturn &GetEndpointOK{}\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\nfunc (f *FundSettlementParameters3) AddReceivingSideDetails() *ReceivingPartiesAndAccount3 {\n\tf.ReceivingSideDetails = new(ReceivingPartiesAndAccount3)\n\treturn f.ReceivingSideDetails\n}\n\n\n\nfunc (f *FundSettlementParameters3) AddDeliveringSideDetails() *DeliveringPartiesAndAccount3 ", "output": "{\n\tf.DeliveringSideDetails = new(DeliveringPartiesAndAccount3)\n\treturn f.DeliveringSideDetails\n}"} {"input": "package aws\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/aws/aws-sdk-go/aws\"\n\t\"github.com/aws/aws-sdk-go/service/organizations\"\n\t\"github.com/hashicorp/terraform-plugin-sdk/helper/resource\"\n\t\"github.com/hashicorp/terraform-plugin-sdk/helper/schema\"\n)\n\nfunc dataSourceAwsOrganizationsOrganizationalUnits() *schema.Resource {\n\treturn &schema.Resource{\n\t\tRead: dataSourceAwsOrganizationsOrganizationalUnitsRead,\n\n\t\tSchema: map[string]*schema.Schema{\n\t\t\t\"parent_id\": {\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tRequired: true,\n\t\t\t},\n\t\t\t\"children\": {\n\t\t\t\tType: schema.TypeList,\n\t\t\t\tComputed: true,\n\t\t\t\tElem: &schema.Resource{\n\t\t\t\t\tSchema: map[string]*schema.Schema{\n\t\t\t\t\t\t\"arn\": {\n\t\t\t\t\t\t\tType: schema.TypeString,\n\t\t\t\t\t\t\tComputed: true,\n\t\t\t\t\t\t},\n\t\t\t\t\t\t\"id\": {\n\t\t\t\t\t\t\tType: schema.TypeString,\n\t\t\t\t\t\t\tComputed: true,\n\t\t\t\t\t\t},\n\t\t\t\t\t\t\"name\": {\n\t\t\t\t\t\t\tType: schema.TypeString,\n\t\t\t\t\t\t\tComputed: true,\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\nfunc flattenOrganizationsOrganizationalUnits(ous []*organizations.OrganizationalUnit) []map[string]interface{} {\n\tif len(ous) == 0 {\n\t\treturn nil\n\t}\n\tvar result []map[string]interface{}\n\tfor _, ou := range ous {\n\t\tresult = append(result, map[string]interface{}{\n\t\t\t\"arn\": aws.StringValue(ou.Arn),\n\t\t\t\"id\": aws.StringValue(ou.Id),\n\t\t\t\"name\": aws.StringValue(ou.Name),\n\t\t})\n\t}\n\treturn result\n}\n\nfunc dataSourceAwsOrganizationsOrganizationalUnitsRead(d *schema.ResourceData, meta interface{}) error ", "output": "{\n\tconn := meta.(*AWSClient).organizationsconn\n\n\tparent_id := d.Get(\"parent_id\").(string)\n\td.SetId(resource.UniqueId())\n\n\tparams := &organizations.ListOrganizationalUnitsForParentInput{\n\t\tParentId: aws.String(parent_id),\n\t}\n\n\tvar children []*organizations.OrganizationalUnit\n\n\terr := conn.ListOrganizationalUnitsForParentPages(params,\n\t\tfunc(page *organizations.ListOrganizationalUnitsForParentOutput, lastPage bool) bool {\n\t\t\tchildren = append(children, page.OrganizationalUnits...)\n\n\t\t\treturn !lastPage\n\t\t})\n\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error listing Organizations Organization Units for parent (%s): %s\", parent_id, err)\n\t}\n\n\tif err := d.Set(\"children\", flattenOrganizationsOrganizationalUnits(children)); err != nil {\n\t\treturn fmt.Errorf(\"Error setting children: %s\", err)\n\t}\n\n\treturn nil\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\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\nfunc (response ChangeNetworkLoadBalancerCompartmentResponse) HTTPResponse() *http.Response {\n\treturn response.RawResponse\n}\n\nfunc (request ChangeNetworkLoadBalancerCompartmentRequest) String() string ", "output": "{\n\treturn common.PointerString(request)\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\nfunc (s ByLen) Len() int { return len(s) }\n\n\n\n\n\nfunc (s ByLen) Swap(i, j int) { s[i], s[j] = s[j], s[i] }\n\nfunc (s ByLen) Less(i, j int) bool ", "output": "{ return len(s[i]) > len(s[j]) }"} {"input": "package main\n\nimport (\n\t\"github.com/astaxie/beego\"\n\t\"github.com/gogenerate/rest/controllers\" \n)\n\n\n\nfunc init() ", "output": "{\n\tbeego.Router(\"/api/user/new\", &controllers.UserController{}, \"post:Save\")\n\tbeego.Router(\"/api/user/all\", &controllers.UserController{}, \"get:All\")\n\tbeego.Router(\"/api/user/:id(\\\\d+)\", &controllers.UserController{}) \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\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\nfunc (self *SIPUSH) Execute(frame *chapter4_rtdt.Frame) {\n\ti := int32(self.val)\n\tframe.OperandStack().PushInt(i)\n}\n\nfunc (self *BIPUSH) FetchOperands(reader *base.BytecodeReader) ", "output": "{\n\tself.val = reader.ReadInt8()\n}"} {"input": "package main\n\n\nfunc listMultiples(m, max int, ret chan int) {\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}\n\n\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 collect(c []chan int) int ", "output": "{\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}"} {"input": "package setup\n\nimport (\n\t\"github.com/mholt/caddy/middleware\"\n\t\"github.com/mholt/caddy/middleware/inner\"\n)\n\n\n\n\nfunc internalParse(c *Controller) ([]string, error) {\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}\n\nfunc Internal(c *Controller) (middleware.Middleware, error) ", "output": "{\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}"} {"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\nfunc NewDeleteTargetPoolStep() *DeleteTargetPoolStep {\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}\n\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 (s *DeleteTargetPoolStep) Run(ctx context.Context, output io.Writer,\n\tconfig *steps.Config) error ", "output": "{\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}"} {"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\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) Save(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.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}"} {"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\n\n\nfunc serviceToInternal(a arena.Arena, v interface{}) (interface{}, error) {\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}\n\nfunc internalToService(v interface{}) (interface{}, error) ", "output": "{\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}"} {"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\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 viewHandler(w http.ResponseWriter, r *http.Request) ", "output": "{\n\ttitle := r.URL.Path[len(\"/view/\"):]\n\tp, _ := loadPage(title)\n\trenderTemplate(w, \"view\", p)\n}"} {"input": "package stats\n\nimport (\n\t\"syscall\"\n)\n\n\n\nfunc (disk *DiskStatus) fillInStatus() ", "output": "{\n\tfs := syscall.Statfs_t{}\n\terr := syscall.Statfs(disk.Dir, &fs)\n\tif err != nil {\n\t\treturn\n\t}\n\tdisk.All = fs.Blocks * uint64(fs.Bsize)\n\tdisk.Free = fs.Bfree * uint64(fs.Bsize)\n\tdisk.Used = disk.All - disk.Free\n\treturn\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\nfunc comments(g *gocui.Gui, v *gocui.View) error {\n\tlayout.SetPage(layout.Comments)\n\tlayout.Clear(g, v)\n\treturn nil\n}\n\n\n\nfunc info(g *gocui.Gui, v *gocui.View) error ", "output": "{\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}"} {"input": "package rsync\n\nimport (\n\t\"os\"\n\t\"reflect\"\n\t\"testing\"\n)\n\nfunc TestParseProgress(t *testing.T) {\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}\n\n\n\nfunc TestParseProgressLine(t *testing.T) ", "output": "{\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}"} {"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\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) GetDefaults() *ServiceControlSettings ", "output": "{\n\treturn s.defaults\n}"} {"input": "package test\n\nimport (\n\t\"fmt\"\n\t\"net\"\n\t\"strconv\"\n\t\"time\"\n)\n\ntype TestingBasicServer struct {\n\tPort int\n\tToWrite []byte\n\tWriteWait time.Duration\n}\n\n\n\nfunc (tbs *TestingBasicServer) RunServer() ", "output": "{\n\tl, err := net.Listen(\"tcp\", \":\"+strconv.Itoa(tbs.Port))\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n\tdefer l.Close()\n\tfor {\n\t\tconn, err := l.Accept()\n\t\tif err != nil {\n\t\t\tfmt.Println(err)\n\t\t\treturn\n\t\t}\n\t\tdefer conn.Close()\n\n\t\ttime.Sleep(tbs.WriteWait * time.Second)\n\t\t_, err = conn.Write(tbs.ToWrite)\n\t\tif err != nil {\n\t\t\tfmt.Println(err)\n\t\t}\n\n\t\treturn\n\t}\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\nfunc (a *AcceptorCurrencyConversionRequestV02) AddCurrencyConversionRequest() *iso20022.AcceptorCurrencyConversionRequest2 {\n\ta.CurrencyConversionRequest = new(iso20022.AcceptorCurrencyConversionRequest2)\n\treturn a.CurrencyConversionRequest\n}\n\n\n\nfunc (a *AcceptorCurrencyConversionRequestV02) AddSecurityTrailer() *iso20022.ContentInformationType11 ", "output": "{\n\ta.SecurityTrailer = new(iso20022.ContentInformationType11)\n\treturn a.SecurityTrailer\n}"} {"input": "package errorreporting \n\nimport (\n\t\"golang.org/x/net/context\"\n\t\"google.golang.org/grpc/metadata\"\n)\n\nfunc insertXGoog(ctx context.Context, val []string) context.Context {\n\tmd, _ := metadata.FromOutgoingContext(ctx)\n\tmd = md.Copy()\n\tmd[\"x-goog-api-client\"] = val\n\treturn metadata.NewOutgoingContext(ctx, md)\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 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\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_Instance(obj *Instance) ", "output": "{\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}"} {"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}\n\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) Stats() string ", "output": "{ return fmt.Sprintf(\"%d:%d\", len(p.transactions), len(p.uncles)) }"} {"input": "package v1api\n\nimport \"github.com/labstack/echo\"\n\n\n\n\n\n\nfunc GetServiceStatics(ctx echo.Context) error {\n\treturn ctx.JSON(NotImplemented, apiResponse{})\n}\n\nfunc GetDeviceStatics(ctx echo.Context) error ", "output": "{\n\treturn ctx.JSON(NotImplemented, apiResponse{})\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"math/rand\"\n\t\"sort\"\n)\n\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\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 partition(a sort.Interface, first int, last int, pivotIndex int) int ", "output": "{\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}"} {"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\nfunc WaitJob(server *pb.ServerInfo, jobId string, timeout time.Duration) error {\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}\n\n\n\nfunc waitJob(server *pb.ServerInfo, jobId string) (done bool, err error) ", "output": "{\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}"} {"input": "package main\n\nimport (\n\t\"exectime/timer\"\n\t\"fmt\"\n\t\"os\"\n\t\"os/exec\"\n)\n\n\n\nfunc launchCommand(name string, args ...string) error {\n\tcmd := exec.Command(name, args...)\n\tcmd.Stdin, cmd.Stdout, cmd.Stderr = os.Stdin, os.Stdout, os.Stderr\n\treturn cmd.Run()\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 printError(e interface{}) ", "output": "{\n\tfmt.Printf(\"\\033[1;31m%v\\033[m\\n\", e)\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\n\n\nfunc main() {\n\torm.RunSyncdb(\"default\", false, true)\n\tbeego.Run()\n}\n\nfunc plus1(in int) int {\n\treturn in + 1\n}\n\nfunc init() ", "output": "{\n\tmodels.RegisterDB()\n\tbeego.AddFuncMap(\"plus1\", plus1)\n}"} {"input": "package channel\n\nimport (\n\t\"testing\"\n)\n\nfunc TestBuffers(t *testing.T) {\n\tbuffers()\n}\n\n\nfunc TestController(t *testing.T) ", "output": "{\n\tcontroller()\n}"} {"input": "package structs\n\nimport \"fmt\"\n\ntype NRData struct {\n\tAgent struct {\n\t\tHost string\n\t\tVersion string\n\t\tPID uint64\n\t}\n\tComponents []NRComponent\n}\n\n\n\nfunc (nrd NRData) String() string ", "output": "{\n\treturn fmt.Sprintf(\"Agent Host: %v - Agent Version: %v - Agent PID: %v\", nrd.Agent.Host, nrd.Agent.Version, nrd.Agent.PID)\n}"} {"input": "package main\n\nimport (\n\t\"github.com/astaxie/beego\"\n\t\"test/models\"\n\t_ \"test/routers\"\n\t\"os\"\n)\n\nfunc init() {\n\tmodels.Connect()\n\tinitArgs()\n}\n\nfunc main() {\n\tbeego.Run()\n}\n\n\n\nfunc initArgs() ", "output": "{\n\targs := os.Args\n\tfor _, v := range args {\n\t\tif v == \"-syncdb\" {\n\t\t\tmodels.Syncbd(false)\n\t\t\tos.Exit(0)\n\t\t}\n\t\tif v == \"-syncdb-force\" {\n\t\t\tmodels.Syncbd(true)\n\t\t\tos.Exit(0)\n\t\t}\n\t}\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\nfunc initData(resp http.ResponseWriter, req *http.Request) {\n\n\tinsert()\n}\n\n\n\nfunc getData(resp http.ResponseWriter, req *http.Request) ", "output": "{\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}"} {"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\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 (repo *Repository) Create() error ", "output": "{\n\tcmd := exec.Command(\"git\", \"init\", \"--bare\", repo.Name)\n\tcmd.Dir = config.RepositoryDir\n\treturn cmd.Run()\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\nfunc isValid(s string) bool {\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}\n\n\n\n\n\n\n\n\nfunc isValid2(s string) bool ", "output": "{\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}"} {"input": "package l3plugin\n\nimport (\n\t\"go.ligato.io/cn-infra/v2/config\"\n\t\"go.ligato.io/cn-infra/v2/logging\"\n\n\t\"go.ligato.io/vpp-agent/v3/plugins/kvscheduler\"\n\t\"go.ligato.io/vpp-agent/v3/plugins/linux/ifplugin\"\n\t\"go.ligato.io/vpp-agent/v3/plugins/linux/nsplugin\"\n\t\"go.ligato.io/vpp-agent/v3/plugins/netalloc\"\n)\n\n\nvar DefaultPlugin = *NewPlugin()\n\n\nfunc NewPlugin(opts ...Option) *L3Plugin {\n\tp := &L3Plugin{}\n\n\tp.PluginName = \"linux-l3plugin\"\n\tp.KVScheduler = &kvscheduler.DefaultPlugin\n\tp.NsPlugin = &nsplugin.DefaultPlugin\n\tp.AddrAlloc = &netalloc.DefaultPlugin\n\tp.IfPlugin = &ifplugin.DefaultPlugin\n\n\tfor _, o := range opts {\n\t\to(p)\n\t}\n\n\tif p.Log == nil {\n\t\tp.Log = logging.ForPlugin(p.String())\n\t}\n\tif p.Cfg == nil {\n\t\tp.Cfg = config.ForPlugin(p.String(),\n\t\t\tconfig.WithCustomizedFlag(config.FlagName(p.String()), \"linux-l3plugin.conf\"),\n\t\t)\n\t}\n\n\treturn p\n}\n\n\ntype Option func(*L3Plugin)\n\n\n\n\nfunc UseDeps(f func(*Deps)) Option ", "output": "{\n\treturn func(p *L3Plugin) {\n\t\tf(&p.Deps)\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\nfunc (i *Int) Get() interface{} {\n\treturn int(*i)\n}\n\n\n\n\n\nfunc (i *Int) String() string {\n\treturn fmt.Sprintf(\"%v\", *i)\n}\n\nfunc (i *Int) Set(s string) error ", "output": "{\n\tv, err := strconv.ParseInt(s, 0, 64)\n\t*i = Int(v)\n\treturn err\n}"} {"input": "package log\n\nfunc setup() {\n\n}\n\n\n\n\n\n\nfunc outputsyslog(level int, msg string) {\n}\n\nfunc EnableSyslog() ", "output": "{\n\tlogToSyslog = false\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\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\nfunc (r *AWSEMRCluster_HadoopJarStepConfig) SetDeletionPolicy(policy policies.DeletionPolicy) {\n\tr._deletionPolicy = policy\n}\n\nfunc (r *AWSEMRCluster_HadoopJarStepConfig) DependsOn() []string ", "output": "{\n\treturn r._dependsOn\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\nfunc (m *CT_F) Validate() error {\n\treturn m.ValidateWithPath(\"CT_F\")\n}\n\n\n\n\nfunc (m *CT_F) ValidateWithPath(path string) error ", "output": "{\n\treturn nil\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\n\n\nfunc NewMultiNotifyWatcher(w ...state.NotifyWatcher) state.NotifyWatcher {\n\tmw := newMultiNotifyWatcher(w...)\n\treturn mw\n}\n\nfunc DescriptionFromVersions(name string, vers Versions) FacadeDescription ", "output": "{\n\treturn descriptionFromVersions(name, versions(vers))\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\n\n\nfunc (FixerAmazonShutdownBehavior) Synopsis() string {\n\treturn `Changes \"shutdown_behaviour\" to \"shutdown_behavior\" in Amazon builders.`\n}\n\nfunc (FixerAmazonShutdownBehavior) Fix(input map[string]interface{}) (map[string]interface{}, error) ", "output": "{\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}"} {"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\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) Data() string ", "output": "{\n\treturn \"\"\n}"} {"input": "package otel\n\nimport (\n\t\"sync\"\n)\n\nvar initOnce sync.Once\n\n\n\n\nfunc initialize(cnf *config) {\n\taddClientFactoryHooks(cnf)\n}\n\nfunc Initialize(opts ...Option) ", "output": "{\n\tcnf := newConfig(opts...)\n\tinitOnce.Do(func() {\n\t\tinitialize(cnf)\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\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\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\n\n\nfunc TestErrorSeverity(t *testing.T) ", "output": "{\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}"} {"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\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 LessThan(t *testing.T, value, other interface{}) *Matcher ", "output": "{\n\treturn Match(t, value).LessThan(other)\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\nfunc (s Status) String() string {\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}\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\n\n\nfunc FormatByteCount(n int64) string ", "output": "{\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}"} {"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\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\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 NewGetNodesIdentifierCatalogsParams() *GetNodesIdentifierCatalogsParams ", "output": "{\n\tvar ()\n\treturn &GetNodesIdentifierCatalogsParams{\n\n\t\ttimeout: cr.DefaultTimeout,\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\nfunc NewHelpModule(bot *Bot) *HelpModule {\n return &HelpModule{bot}\n}\n\n\n\nfunc (m *HelpModule) Handle(msg *proto.Msg) string {\n return module.CallCmdMethod(m, msg)\n}\n\nfunc (m *HelpModule) CMD_(msg *proto.Msg) string ", "output": "{\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}"} {"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\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\n\n\nfunc main() {\n \n InitCanvas(screen)\n MainLoop(tick)\n}\n\nfunc tick() ", "output": "{\n ClearCanvas() \n b1.Move()\n b2.Move()\n DrawImage(\"ball.png\", b1.Position()) \n DrawImage(\"ball.png\", b2.Position()) \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\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 (c *ColumnheadersWidget) SetColumns(cols songlist.Columns) ", "output": "{\n\tc.columns = cols\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 }\n\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 (m *csvFiles) FileAppendColumns() []string ", "output": "{ return m.appendcols }"} {"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\nfunc (o *OnedState) Set(other *OnedState) {\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}\n\n\n\n\nfunc (o *OnedState) GetCopy() *OnedState ", "output": "{\n\tother := NewOnedState(len(o.Alp), len(o.Phi))\n\tother.Set(o)\n\treturn other\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\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 TestEnvMustSet(t *testing.T) ", "output": "{\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}"} {"input": "package transformers\n\nimport (\n\t\"fmt\"\n\n\t\"sigs.k8s.io/kustomize/pkg/expansion\"\n\t\"sigs.k8s.io/kustomize/pkg/resmap\"\n\t\"sigs.k8s.io/kustomize/pkg/transformers/config\"\n)\n\ntype refvarTransformer struct {\n\tfieldSpecs []config.FieldSpec\n\tvars map[string]string\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\nfunc (rv *refvarTransformer) Transform(resources resmap.ResMap) error {\n\tfor resId := range resources {\n\t\tobjMap := resources[resId].Map()\n\t\tfor _, pc := range rv.fieldSpecs {\n\t\t\tif !resId.Gvk().IsSelected(&pc.Gvk) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\terr := mutateField(objMap, pc.PathSlice(), false, func(in interface{}) (interface{}, error) {\n\t\t\t\tvar (\n\t\t\t\t\tmappingFunc = expansion.MappingFuncFor(rv.vars)\n\t\t\t\t)\n\t\t\t\tswitch vt := in.(type) {\n\t\t\t\tcase []interface{}:\n\t\t\t\t\tvar xs []string\n\t\t\t\t\tfor _, a := range in.([]interface{}) {\n\t\t\t\t\t\txs = append(xs, expansion.Expand(a.(string), mappingFunc))\n\t\t\t\t\t}\n\t\t\t\t\treturn xs, nil\n\t\t\t\tcase interface{}:\n\t\t\t\t\ts, ok := in.(string)\n\t\t\t\t\tif !ok {\n\t\t\t\t\t\treturn nil, fmt.Errorf(\"%#v is expected to be %T\", in, s)\n\t\t\t\t\t}\n\t\t\t\t\truntimeVal := expansion.Expand(s, mappingFunc)\n\t\t\t\t\treturn runtimeVal, nil\n\t\t\t\tdefault:\n\t\t\t\t\treturn \"\", fmt.Errorf(\"invalid type encountered %T\", vt)\n\t\t\t\t}\n\t\t\t})\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 NewRefVarTransformer(vars map[string]string, p []config.FieldSpec) Transformer ", "output": "{\n\treturn &refvarTransformer{\n\t\tvars: vars,\n\t\tfieldSpecs: p,\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\nfunc NewQueryParamsHandler() types.Middleware {\n\treturn &queryParamsHandler{}\n}\n\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 (h *queryParamsHandler) Handler(m types.APIFunc) types.APIFunc ", "output": "{\n\treturn (&queryParamsHandler{m}).Handle\n}"} {"input": "package models\n\nimport \"github.com/astaxie/beego/orm\"\n\ntype User struct {\n\tId int\n\tName, Passwd string\n\tTotal_amount float64\n\tPermission int\n\tCreator string\n\tFxsm string\n\tPhone string\n}\n\n\n\nfunc Login(u string, p string) (user *User, err error) ", "output": "{\n\tsql := \"SELECT id FROM user WHERE name = ? and passwd =?\"\n\terr = orm.NewOrm().Raw(sql, u, p).QueryRow(&user)\n\treturn user, err\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\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\nfunc (o *PostIPAMParams) validateFamily(formats strfmt.Registry) error {\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}\n\nfunc NewPostIPAMParams() PostIPAMParams ", "output": "{\n\tvar ()\n\treturn PostIPAMParams{}\n}"} {"input": "package email\n\nimport (\n\tgomail \"gopkg.in/gomail.v2\"\n\n\t\"go-common/app/job/main/archive/conf\"\n)\n\n\ntype Dao struct {\n\tc *conf.Config\n\temail *gomail.Dialer\n}\n\n\n\n\nfunc New(c *conf.Config) (d *Dao) ", "output": "{\n\td = &Dao{\n\t\tc: c,\n\t\temail: gomail.NewDialer(c.Mail.Host, c.Mail.Port, c.Mail.Username, c.Mail.Password),\n\t}\n\treturn d\n}"} {"input": "package v2\n\nimport (\n\t\"fmt\"\n\t\"net/http\"\n)\n\nfunc (c *client) DeprovisionInstance(r *DeprovisionRequest) (*DeprovisionResponse, error) {\n\tif err := validateDeprovisionRequest(r); err != nil {\n\t\treturn nil, err\n\t}\n\n\tfullURL := fmt.Sprintf(serviceInstanceURLFmt, c.URL, r.InstanceID)\n\n\tparams := map[string]string{\n\t\tserviceIDKey: string(r.ServiceID),\n\t\tplanIDKey: string(r.PlanID),\n\t}\n\tif r.AcceptsIncomplete {\n\t\tparams[asyncQueryParamKey] = \"true\"\n\t}\n\n\tresponse, err := c.prepareAndDo(http.MethodDelete, fullURL, params, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tswitch response.StatusCode {\n\tcase http.StatusOK, http.StatusGone:\n\t\treturn &DeprovisionResponse{}, nil\n\tcase http.StatusAccepted:\n\t\tresponseBodyObj := &asyncSuccessResponseBody{}\n\t\tif err := c.unmarshalResponse(response, responseBodyObj); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tvar opPtr *OperationKey\n\t\tif responseBodyObj.Operation != nil {\n\t\t\topStr := *responseBodyObj.Operation\n\t\t\top := OperationKey(opStr)\n\t\t\topPtr = &op\n\t\t}\n\n\t\tuserResponse := &DeprovisionResponse{\n\t\t\tAsync: true,\n\t\t\tOperationKey: opPtr,\n\t\t}\n\n\t\treturn userResponse, nil\n\tdefault:\n\t\treturn nil, c.handleFailureResponse(response)\n\t}\n\n\treturn nil, nil\n}\n\n\n\nfunc validateDeprovisionRequest(request *DeprovisionRequest) error ", "output": "{\n\tif request.InstanceID == \"\" {\n\t\treturn required(\"instanceID\")\n\t}\n\n\tif request.ServiceID == \"\" {\n\t\treturn required(\"serviceID\")\n\t}\n\n\tif request.PlanID == \"\" {\n\t\treturn required(\"planID\")\n\t}\n\n\treturn nil\n}"} {"input": "package v1\n\nimport (\n\t\"github.com/gin-gonic/gin\"\n)\n\n\n\n\nfunc Hello(c *gin.Context) ", "output": "{\n\n\tc.Header(\"Content-Type\", \"text/plain\")\n\tc.String(200, \"hello, gin!\")\n}"} {"input": "package grpcservice\n\nimport \"google.golang.org/grpc\"\n\n\n\n\n\nfunc GetInstanceFromClient(grpcclient *GRPCClient) *grpc.ClientConn {\n\treturn grpcclient.connection\n}\n\nfunc GetInstanceFromServer(grpcserver *GRPCServer) *grpc.Server ", "output": "{\n\treturn grpcserver.server\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\n\n\n\nfunc (p *Position) Accept(v Visitor) (Expression, error) {\n\treturn v.VisitPosition(p)\n}\n\nfunc (p *Position) Eval(ctx context.Context, args map[interface{}]interface{}) (v interface{}, err error) ", "output": "{\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}"} {"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\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\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 NewGraph() Graph ", "output": "{\n\treturn Graph{\n\t\tEdges: make(map[int] *set.Set),\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\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\n\n\nfunc (r *Remover) Remove(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 := 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}"} {"input": "package dns\n\nimport (\n\tmdns \"github.com/miekg/dns\"\n\t\"github.com/parkomat/parkomat/config\"\n\t\"strings\"\n)\n\ntype txtHandler struct {\n}\n\n\n\n\nfunc (t *txtHandler) Handle(msg *mdns.Msg, zone *config.Zone, question mdns.Question) (err error) ", "output": "{\n\tfor _, txt := range strings.Split(zone.TXT, \"\\n\") {\n\t\ttxt = strings.Trim(txt, \" \")\n\t\tif txt != \"\" {\n\t\t\ts := strings.Join([]string{\n\t\t\t\tquestion.Name,\n\t\t\t\t\"3600\",\n\t\t\t\t\"IN\",\n\t\t\t\t\"TXT\",\n\t\t\t\ttxt,\n\t\t\t}, \" \")\n\n\t\t\trr, err := mdns.NewRR(s)\n\t\t\tif err == nil {\n\t\t\t\tmsg.Answer = append(msg.Answer, rr)\n\t\t\t}\n\t\t}\n\t}\n\treturn\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\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 ExampleTimer() ", "output": "{\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}"} {"input": "package anthapath\n\nimport (\n\t\"os\"\n\t\"os/user\"\n\t\"path/filepath\"\n)\n\n\nfunc Path() string {\n\tu, err := user.Current()\n\tif err != nil {\n\t\treturn \"\"\n\t}\n\treturn filepath.Join(u.HomeDir, \".antha\")\n}\n\n\n\n\nfunc Exists(filename string) bool ", "output": "{\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}"} {"input": "package conditions\n\nimport (\n\t\"testing\"\n\n\t. \"github.com/zimmski/tavor/test/assert\"\n\n\t\"github.com/zimmski/tavor/token\"\n\t\"github.com/zimmski/tavor/token/lists\"\n\t\"github.com/zimmski/tavor/token/primitives\"\n)\n\nfunc TestConditionsTokensToBeTokens(t *testing.T) {\n\tvar tok *token.Token\n\n\tImplements(t, tok, &If{})\n}\n\nfunc TestVariableIf(t *testing.T) {\n\tvar o token.Token = NewIf(IfPair{\n\t\tHead: NewBooleanEqual(primitives.NewConstantInt(1), primitives.NewConstantInt(1)),\n\t\tBody: primitives.NewConstantString(\"a\"),\n\t})\n\tEqual(t, \"a\", o.String())\n\tEqual(t, 1, o.Permutations())\n\tEqual(t, 1, o.PermutationsAll())\n\n\to2 := o.Clone()\n\tEqual(t, o.String(), o2.String())\n\n\tEqual(t, 1, o.Permutations())\n\n\tNil(t, o.Permutation(0))\n\tEqual(t, \"a\", o.String())\n\n\tEqual(t, o.Permutation(1).(*token.PermutationError).Type, token.PermutationErrorIndexOutOfBound)\n\n\to = lists.NewConcatenation(\n\t\tNewIf(IfPair{\n\t\t\tHead: NewBooleanEqual(primitives.NewConstantInt(1), primitives.NewConstantInt(2)),\n\t\t\tBody: primitives.NewConstantString(\"a\"),\n\t\t}),\n\t\tprimitives.NewConstantString(\"b\"),\n\t)\n\tEqual(t, \"b\", o.String())\n}\n\n\n\nfunc TestVariableElse(t *testing.T) ", "output": "{\n\to := NewIf(\n\t\tIfPair{\n\t\t\tHead: NewBooleanEqual(primitives.NewConstantInt(1), primitives.NewConstantInt(2)),\n\t\t\tBody: primitives.NewConstantString(\"a\"),\n\t\t},\n\t\tIfPair{\n\t\t\tHead: NewBooleanTrue(),\n\t\t\tBody: primitives.NewConstantString(\"b\"),\n\t\t},\n\t)\n\tEqual(t, \"b\", o.String())\n\tEqual(t, 1, o.Permutations())\n\tEqual(t, 1, o.PermutationsAll())\n\n\to2 := o.Clone()\n\tEqual(t, o.String(), o2.String())\n\n\tEqual(t, 1, o.Permutations())\n\n\tNil(t, o.Permutation(0))\n\tEqual(t, \"b\", o.String())\n\n\tEqual(t, o.Permutation(1).(*token.PermutationError).Type, token.PermutationErrorIndexOutOfBound)\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\nfunc (e *DefaultLockedFile) Exclusive() bool {\n\treturn e.exclusive\n}\n\n\n\nfunc (e *DefaultLockedFile) Close() error ", "output": "{\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}"} {"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\n\n\nfunc CgoPprofThread() {\n\truntime.SetCgoTraceback(0, unsafe.Pointer(C.pprofCgoThreadTraceback), nil, nil)\n\tpprofThread()\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 init() ", "output": "{\n\tregister(\"CgoPprofThread\", CgoPprofThread)\n\tregister(\"CgoPprofThreadNoTraceback\", CgoPprofThreadNoTraceback)\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\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\n\n\nfunc MustParseURL(rawURL string) *url.URL ", "output": "{\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}"} {"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\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\n\n\nfunc (m *indexOfInitialisms) sorted() (result []string) ", "output": "{\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}"} {"input": "package mutilate\n\nimport (\n\t\"testing\"\n\n\t\"github.com/intelsdi-x/snap/control\"\n\t\"github.com/intelsdi-x/snap/core\"\n\t\"github.com/intelsdi-x/swan/integration_tests/test_helpers\"\n\t. \"github.com/smartystreets/goconvey/convey\"\n)\n\n\n\nfunc TestMutilatePluginLoad(t *testing.T) ", "output": "{\n\n\tpluginPath := testhelpers.AssertFileExists(\"snap-plugin-collector-mutilate\")\n\n\tConvey(\"Ensure mutilate plugin can be loaded\", t, func() {\n\n\t\tpluginControl := control.New(control.GetDefaultConfig())\n\t\tpluginControl.Start()\n\t\trequestedPlugin, requestedPluginError := core.NewRequestedPlugin(pluginPath, \"/tmp/\", nil)\n\t\tSo(requestedPluginError, ShouldBeNil)\n\n\t\t_, loadError := pluginControl.Load(requestedPlugin)\n\t\tSo(loadError, ShouldBeNil)\n\t})\n}"} {"input": "package static\n\nimport (\n\t\"fmt\"\n\t\"mime\"\n\t\"net/http\"\n\t\"net/url\"\n\t\"path\"\n\n\t\"github.com/golang/glog\"\n)\n\nconst StaticResource = \"/static/\"\n\nvar bootstrapJs, _ = Asset(\"pages/assets/js/bootstrap-3.1.1.min.js\")\nvar containersJs, _ = Asset(\"pages/assets/js/containers.js\")\nvar gchartsJs, _ = Asset(\"pages/assets/js/gcharts.js\")\nvar googleJsapiJs, _ = Asset(\"pages/assets/js/google-jsapi.js\")\nvar jqueryJs, _ = Asset(\"pages/assets/js/jquery-1.10.2.min.js\")\n\nvar bootstrapCss, _ = Asset(\"pages/assets/styles/bootstrap-3.1.1.min.css\")\nvar bootstrapThemeCss, _ = Asset(\"pages/assets/styles/bootstrap-theme-3.1.1.min.css\")\nvar containersCss, _ = Asset(\"pages/assets/styles/containers.css\")\n\nvar staticFiles = map[string][]byte{\n\t\"bootstrap-3.1.1.min.css\": bootstrapCss,\n\t\"bootstrap-3.1.1.min.js\": bootstrapJs,\n\t\"bootstrap-theme-3.1.1.min.css\": bootstrapThemeCss,\n\t\"containers.css\": containersCss,\n\t\"containers.js\": containersJs,\n\t\"gcharts.js\": gchartsJs,\n\t\"google-jsapi.js\": googleJsapiJs,\n\t\"jquery-1.10.2.min.js\": jqueryJs,\n}\n\n\n\nfunc HandleRequest(w http.ResponseWriter, u *url.URL) ", "output": "{\n\tif len(u.Path) <= len(StaticResource) {\n\t\thttp.Error(w, fmt.Sprintf(\"unknown static resource %q\", u.Path), http.StatusNotFound)\n\t\treturn\n\t}\n\n\tresource := u.Path[len(StaticResource):]\n\tcontent, ok := staticFiles[resource]\n\tif !ok {\n\t\thttp.Error(w, fmt.Sprintf(\"unknown static resource %q\", u.Path), http.StatusNotFound)\n\t\treturn\n\t}\n\n\tcontentType := mime.TypeByExtension(path.Ext(resource))\n\tif contentType != \"\" {\n\t\tw.Header().Set(\"Content-Type\", contentType)\n\t}\n\n\tif _, err := w.Write(content); err != nil {\n\t\tglog.Errorf(\"Failed to write response: %v\", err)\n\t}\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\nfunc NewForConfig(c *rest.Config) (*BatchV1Client, 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 &BatchV1Client{client}, nil\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\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 setConfigDefaults(config *rest.Config) error ", "output": "{\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}"} {"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\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) Messages(q *Queue) ([]*Message, error) ", "output": "{\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}"} {"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\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_0) Execute(frame *rtda.Frame) ", "output": "{\n\t_astore(frame, 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\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\n\n\nfunc nickTaken(n string, holder *ClientHolder) bool ", "output": "{\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}"} {"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\n\n\ntype listResult struct {\n\tElements []list.Element `json:\"elements\"`\n\n\tLong bool `json:\"-\"`\n}\n\nfunc (l listResult) Write(w io.Writer) error {\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}\n\nfunc (cmd *ls) Run(f *flag.FlagSet) error ", "output": "{\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}"} {"input": "package trie\n\nimport (\n\t\"testing\"\n\n\t\"github.com/ethereumproject/go-ethereum/common\"\n\t\"github.com/ethereumproject/go-ethereum/ethdb\"\n)\n\nfunc TestIterator(t *testing.T) {\n\ttrie := newEmpty()\n\tvals := []struct{ k, v string }{\n\t\t{\"do\", \"verb\"},\n\t\t{\"ether\", \"wookiedoo\"},\n\t\t{\"horse\", \"stallion\"},\n\t\t{\"shaman\", \"horse\"},\n\t\t{\"doge\", \"coin\"},\n\t\t{\"dog\", \"puppy\"},\n\t\t{\"somethingveryoddindeedthis is\", \"myothernodedata\"},\n\t}\n\tv := make(map[string]bool)\n\tfor _, val := range vals {\n\t\tv[val.k] = false\n\t\ttrie.Update([]byte(val.k), []byte(val.v))\n\t}\n\ttrie.Commit()\n\n\tit := NewIterator(trie)\n\tfor it.Next() {\n\t\tv[string(it.Key)] = true\n\t}\n\n\tfor k, found := range v {\n\t\tif !found {\n\t\t\tt.Error(\"iterator didn't find\", k)\n\t\t}\n\t}\n}\n\n\n\n\nfunc TestNodeIteratorCoverage(t *testing.T) ", "output": "{\n\tdb, trie, _ := makeTestTrie()\n\n\thashes := make(map[common.Hash]struct{})\n\tfor it := NewNodeIterator(trie); it.Next(); {\n\t\tif it.Hash != (common.Hash{}) {\n\t\t\thashes[it.Hash] = struct{}{}\n\t\t}\n\t}\n\tfor hash, _ := range hashes {\n\t\tif _, err := db.Get(hash.Bytes()); err != nil {\n\t\t\tt.Errorf(\"failed to retrieve reported node %x: %v\", hash, err)\n\t\t}\n\t}\n\tfor _, key := range db.(*ethdb.MemDatabase).Keys() {\n\t\tif _, ok := hashes[common.BytesToHash(key)]; !ok {\n\t\t\tt.Errorf(\"state entry not reported %x\", key)\n\t\t}\n\t}\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"math/rand\"\n\t\"time\"\n)\n\n\n\nfunc main() {\n\tfor i := 0; i < 10; i++ {\n\t\tgo func_ex(i)\n\t}\n\tvar input string\n\tfmt.Scanln(&input)\n}\n\nfunc func_ex(n int) ", "output": "{\n\tfor i := 0; i < 10; i++ {\n\t\tfmt.Println(n, \":\", i)\n\t\tsleepDuration := time.Duration(rand.Intn(250))\n\t\ttime.Sleep(time.Millisecond * sleepDuration)\n\t}\n}"} {"input": "package rs\n\nimport (\n\t\"crypto/sha1\"\n\t\"encoding/base64\"\n\t\"io\"\n\t\"net/http\"\n\t\"testing\"\n)\n\nfunc init() {\n\tclient = New(nil)\n\tclient.Delete(nil, bucketName, key)\n}\n\n\n\nfunc TestGetPrivateUrl(t *testing.T) ", "output": "{\n\n\terr := upFile(\"token.go\", bucketName, key)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdefer client.Delete(nil, bucketName, key)\n\n\tbaseUrl := MakeBaseUrl(domain, key)\n\n\tpolicy := GetPolicy{}\n\tprivateUrl := policy.MakeRequest(baseUrl, nil)\n\n\tresp, err := http.Get(privateUrl)\n\tif err != nil {\n\t\tt.Fatal(\"http.Get failed:\", err)\n\t}\n\tdefer resp.Body.Close()\n\n\th := sha1.New()\n\tio.Copy(h, resp.Body)\n\tetagExpected := base64.URLEncoding.EncodeToString(h.Sum([]byte{'\\x16'}))\n\n\tetag := resp.Header.Get(\"Etag\")\n\tif etag[1:len(etag)-1] != etagExpected {\n\t\tt.Fatal(\"http.Get etag failed:\", etag, etagExpected)\n\t}\n\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\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\nfunc (n *Node) IsAlive() bool {\n\treturn n.conn != nil\n}\n\nfunc (n *Node) Dial() (err error) ", "output": "{\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}"} {"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\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, 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}\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 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\n\n\nfunc (c *Counter) Decode(s string) error {\n\tc.value++\n\treturn nil\n}\n\nfunc (c Counter) IsCounter() {}\n\nfunc (c Counter) Value() int ", "output": "{ return c.value }"} {"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\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\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) String() string ", "output": "{\n\treturn common.PointerString(request)\n}"} {"input": "package lnwirefuzz\n\nimport (\n\t\"github.com/lightningnetwork/lnd/lnwire\"\n)\n\n\n\n\nfunc Fuzz_revoke_and_ack(data []byte) int ", "output": "{\n\tdata = prefixWithMsgType(data, lnwire.MsgRevokeAndAck)\n\n\temptyMsg := lnwire.RevokeAndAck{}\n\n\treturn harness(data, &emptyMsg)\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\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\n\n\nfunc SlicePtrFromStrings(ss []string) ([]*byte, error) ", "output": "{\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}"} {"input": "package framework\n\nimport \"github.com/onsi/gomega\"\n\n\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\nfunc ExpectEmpty(actual interface{}, explain ...interface{}) {\n\tgomega.ExpectWithOffset(1, actual).To(gomega.BeEmpty(), explain...)\n}\n\nfunc ExpectEqual(actual interface{}, extra interface{}, explain ...interface{}) ", "output": "{\n\tgomega.ExpectWithOffset(1, actual).To(gomega.Equal(extra), explain...)\n}"} {"input": "package http_test\n\nimport (\n\t\"os\"\n\t\"testing\"\n\n\t\"github.com/YakLabs/k8s-client/http\"\n\t\"github.com/stretchr/testify/require\"\n)\n\n\n\n\nfunc testClient(t *testing.T) *http.Client ", "output": "{\n\tserver := os.Getenv(\"K8S_SERVER\")\n\n\tif server == \"\" {\n\t\tserver = \"http://127.0.0.1:8001\"\n\t}\n\n\topts := []http.OptionsFunc{\n\t\thttp.SetServer(server),\n\t}\n\n\tif caFile := os.Getenv(\"K8S_CAFILE\"); caFile != \"\" {\n\t\topts = append(opts, http.SetCAFromFile(caFile))\n\t}\n\n\tif clientCert := os.Getenv(\"K8S_CLIENTCERT\"); clientCert != \"\" {\n\t\topts = append(opts, http.SetClientCertFromFile(clientCert))\n\t}\n\n\tif clientKey := os.Getenv(\"K8S_CLIENTKEY\"); clientKey != \"\" {\n\t\topts = append(opts, http.SetClientKeyFromFile(clientKey))\n\t}\n\n\tc, err := http.New(opts...)\n\trequire.Nil(t, err)\n\n\treturn c\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\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\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 NewEntryPoint(ctx context.Context, t *tracing.Tracing, entryPointName string, next http.Handler) http.Handler ", "output": "{\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}"} {"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\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\nfunc (response ChangeDatabaseSoftwareImageCompartmentResponse) HTTPResponse() *http.Response {\n\treturn response.RawResponse\n}\n\nfunc (request ChangeDatabaseSoftwareImageCompartmentRequest) String() string ", "output": "{\n\treturn common.PointerString(request)\n}"} {"input": "package grafana\n\nimport \"github.com/aporeto-inc/grafanaclient\"\n\n\nfunc DefaultRow() grafanaclient.Row {\n\treturn grafanaclient.Row{Height: \"\"}\n}\n\n\n\n\nfunc DefaultSelectAttribute() grafanaclient.Select ", "output": "{\n\treturn grafanaclient.Select{}\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\n\n\n\nfunc Rmdir(path string) error {\n\treturn os.Remove(path)\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 Mkdir(path string) error ", "output": "{\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}"} {"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\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) GetAll() (map[string]*Option, error) ", "output": "{\n\tm.Lock()\n\tdefer m.Unlock()\n\n\treturn m.users, nil\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\nfunc (self *CacheParamCfg) loadFromJsonCfg(jsnCfg *CacheParamJsonCfg) error {\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}\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\n\n\nfunc (cCfg CacheCfg) AsTransCacheConfig() (tcCfg map[string]*ltcache.CacheConfig) ", "output": "{\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}"} {"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\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 (CertificateSigningRequestCondition) SwaggerDoc() map[string]string ", "output": "{\n\treturn map_CertificateSigningRequestCondition\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\nfunc (pl *PodTopologySpread) Name() string {\n\treturn Name\n}\n\n\n\n\nfunc New(_ *runtime.Unknown, h framework.FrameworkHandle) (framework.Plugin, error) ", "output": "{\n\tif h.SnapshotSharedLister() == nil {\n\t\treturn nil, fmt.Errorf(\"SnapshotSharedlister is nil\")\n\t}\n\treturn &PodTopologySpread{sharedLister: h.SnapshotSharedLister()}, nil\n}"} {"input": "package iso20022\n\n\ntype AmountAndRateFormat3Choice struct {\n\n\tAmount *ActiveCurrencyAndAmount `xml:\"Amt\"`\n\n\tNotSpecifiedRate *RateValueType6FormatChoice `xml:\"NotSpcfdRate\"`\n}\n\nfunc (a *AmountAndRateFormat3Choice) SetAmount(value, currency string) {\n\ta.Amount = NewActiveCurrencyAndAmount(value, currency)\n}\n\n\n\nfunc (a *AmountAndRateFormat3Choice) AddNotSpecifiedRate() *RateValueType6FormatChoice ", "output": "{\n\ta.NotSpecifiedRate = new(RateValueType6FormatChoice)\n\treturn a.NotSpecifiedRate\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\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) validateUserID(formats strfmt.Registry) error ", "output": "{\n\n\tif swag.IsZero(m.UserID) { \n\t\treturn nil\n\t}\n\n\treturn nil\n}"} {"input": "package http2\n\nimport \"testing\"\n\n\n\nfunc TestFlowAdd(t *testing.T) {\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}\n\nfunc TestFlow(t *testing.T) ", "output": "{\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}"} {"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\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 (f *nameFilter) Filter(srcField, destField reflect.StructField, src, dest reflect.Value) bool ", "output": "{\n\treturn f.exclude != srcField.Name\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\n\n\n\n\n\nfunc (iterator *Iterator) Last() bool {\n\treturn iterator.iterator.Last()\n}\n\nfunc (iterator *Iterator) First() bool ", "output": "{\n\treturn iterator.iterator.First()\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\nfunc (p Packet) Amount() int64 {\n\treturn p.Amt\n}\n\n\n\nfunc (p Packet) String() string ", "output": "{\n\treturn fmt.Sprintf(\"{%x %v %q}\", p.Dest, p.Amt, p.Data)\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\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 (r *RichTransport) ReadByte() (c byte, err error) ", "output": "{\n\treturn readByte(r.TTransport)\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\n\n\n\n\nfunc SaveConfig() {\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}\n\nfunc LoadConfig() ", "output": "{\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}"} {"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\nfunc (e basicFileInfo) Group() int {\n\treturn -1\n}\n\n\n\n\n\nfunc (e *basicFileInfo) osFileInfo() os.FileInfo ", "output": "{\n\tfi := e.FileInfo\n\tif fi, ok := fi.(*dirJunctFileInfo); ok {\n\t\treturn fi.FileInfo\n\t}\n\treturn fi\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\n\n\nfunc (patcher *Dispatch) GetID() int {\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}\n\nfunc reloadIDs(dispatch *Dispatch) ", "output": "{\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}"} {"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\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\nfunc read(t *testing.T, client *http.Client, url string) []byte {\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}\n\nfunc TestServer(t *testing.T) ", "output": "{\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}"} {"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\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\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_BatchAnnotateImages() ", "output": "{\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}"} {"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\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\n\n\nfunc ToRole(c *web.C) *model.Perm ", "output": "{\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}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"time\"\n)\n\n\n\nfunc main() {\n\tdone := make(chan bool)\n\tgo worker(done)\n\t<-done\n}\n\nfunc worker(done chan bool) ", "output": "{\n\tfmt.Println(\"Started\")\n\ttime.Sleep(time.Second)\n\tfmt.Println(\"Done\")\n\tdone <- true\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\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) ProvideFilterArgsForCall(i int) string ", "output": "{\n\tfake.provideFilterMutex.RLock()\n\tdefer fake.provideFilterMutex.RUnlock()\n\treturn fake.provideFilterArgsForCall[i].containerId\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\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\nfunc (bs *BindService) Login(s *session.Session, msg *LoginRequest) error {\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}\n\nfunc (bs *BindService) BindChatServer(s *session.Session, msg []byte) error {\n\treturn errors.Errorf(\"not implement\")\n}\n\nfunc newBindService() *BindService ", "output": "{\n\treturn &BindService{}\n}"} {"input": "package evolve\n\nimport \"sync\"\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\ntype FitnessCache struct {\n\n\tWrapped Evaluator\n\tcache sync.Map\n}\n\n\n\n\n\n\n\n\n\n\n\nfunc (c *FitnessCache) IsNatural() bool { return c.Wrapped.IsNatural() }\n\nfunc (c *FitnessCache) Fitness(cand interface{}, pop []interface{}) float64 ", "output": "{\n\tvar fitness float64\n\tval, ok := c.cache.Load(cand)\n\tif ok {\n\t\tfitness = val.(float64)\n\t} else {\n\t\tfitness = c.Wrapped.Fitness(cand, pop)\n\t\tc.cache.Store(cand, fitness)\n\t}\n\treturn fitness\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\n\n\n\ntype DecommissionSite struct {\n\tContext *middleware.Context\n\tHandler DecommissionSiteHandler\n}\n\nfunc (o *DecommissionSite) 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 = 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}\n\nfunc NewDecommissionSite(ctx *middleware.Context, handler DecommissionSiteHandler) *DecommissionSite ", "output": "{\n\treturn &DecommissionSite{Context: ctx, Handler: handler}\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\n\n\n\nfunc (ref *Reference) ShortName() string {\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}\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) Commit() (*Commit, error) ", "output": "{\n\treturn ref.repo.getCommit(ref.Object)\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\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) Tot() uint64 ", "output": "{\n\treturn atomic.LoadUint64(&c.tot)\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\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) Current() []byte ", "output": "{\n\treturn b.current\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\n\n\n\nfunc (n *AsmLabelAttr) Position() Position {\n\treturn n.Pos\n}\n\nfunc (n *AsmLabelAttr) Children() []Node ", "output": "{\n\treturn n.ChildNodes\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\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\nfunc (c *SchedulingV1beta1Client) RESTClient() rest.Interface {\n\tif c == nil {\n\t\treturn nil\n\t}\n\treturn c.restClient\n}\n\nfunc (c *SchedulingV1beta1Client) PriorityClasses() PriorityClassInterface ", "output": "{\n\treturn newPriorityClasses(c)\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\n\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 (W _container_heap_Interface) Len() int ", "output": "{ return W.WLen() }"} {"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\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\nfunc (c *Config) templatePath(templateName string) string {\n\treturn \"./templates/\" + templateName\n}\n\nfunc NewConfig() *Config ", "output": "{\n\treturn &Config{}\n}"} {"input": "package provider_test\n\nimport (\n\t. \"github.com/onsi/ginkgo\"\n\t. \"github.com/onsi/gomega\"\n\n\t\"testing\"\n)\n\n\n\nfunc TestProviderFactory(t *testing.T) ", "output": "{\n\tRegisterFailHandler(Fail)\n\tRunSpecs(t, \"ProviderFactory Suite\")\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"net/http\"\n)\n\n\ntype HandlerFunc func(http.ResponseWriter, *http.Request) (int, error)\n\n\n\n\n\nfunc (s *server) handlerWrapper(h HandlerFunc) http.HandlerFunc {\n\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\n\t\tw.Header().Set(\"Content-Type\", \"application/json\")\n\n\t\tstatus, err := h(w, r)\n\n\t\tvar errMsg string\n\n\t\tif err != nil {\n\t\t\tw.Write([]byte(\"{\\\"message\\\": \\\"An unknown error occurred\\\"}\"))\n\t\t\terrMsg = err.Error()\n\t\t}\n\n\t\tlog.Printf(\"%s %s %s %d %s\", r.RemoteAddr, r.Method, r.URL, status, errMsg)\n\n\t}\n\n}\n\nfunc (s *server) routes(mux *http.ServeMux) ", "output": "{\n\tmux.HandleFunc(\"/\", s.handlerWrapper(handleProcess)) \n\tmux.HandleFunc(fmt.Sprintf(\"/api/v%s/nodeInfo\", apiVersion), s.handlerWrapper(handleProcess)) \n}"} {"input": "package swt\n\nimport \"github.com/timob/javabind\"\n\ntype WidgetsTypedListenerInterface interface {\n\tJavaLangObjectInterface\n\n\tHandleEvent(a WidgetsEventInterface) \n}\n\ntype WidgetsTypedListener struct {\n\tJavaLangObject\n}\n\n\n\n\nfunc (jbobject *WidgetsTypedListener) HandleEvent(a WidgetsEventInterface) ", "output": "{\n\tconv_a := javabind.NewGoToJavaCallable()\n\tif err := conv_a.Convert(a); err != nil {\n\t\tpanic(err)\n\t}\n\t_, err := jbobject.CallMethod(javabind.GetEnv(), \"handleEvent\", javabind.Void, conv_a.Value().Cast(\"org/eclipse/swt/widgets/Event\"))\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tconv_a.CleanUp()\n\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\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 (i *images) getPath(idx int) string ", "output": "{\n\treturn fmt.Sprintf(i.dir+\"/%d\", idx)\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\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 callerLocation() *Location ", "output": "{\n\treturn newLocation(2)\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\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\n\n\nfunc (o *DownloadImageParams) bindImageID(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.ImageID = raw\n\n\treturn 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) }\n\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) Next(ctx context.Context) (bool, error) ", "output": "{ return d.plan.Next(ctx) }"} {"input": "package pool\n\nimport (\n\t\"fmt\"\n\t\"net\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/hashicorp/consul/lib/freeport\"\n\t\"github.com/hashicorp/nomad/helper/testlog\"\n\t\"github.com/hashicorp/nomad/nomad/structs\"\n\t\"github.com/hashicorp/yamux\"\n\t\"github.com/stretchr/testify/require\"\n)\n\n\n\nfunc TestConnPool_ConnListener(t *testing.T) {\n\trequire := require.New(t)\n\n\tports := freeport.GetT(t, 1)\n\taddrStr := fmt.Sprintf(\"127.0.0.1:%d\", ports[0])\n\taddr, err := net.ResolveTCPAddr(\"tcp\", addrStr)\n\trequire.Nil(err)\n\n\texitCh := make(chan struct{})\n\tdefer close(exitCh)\n\tgo func() {\n\t\tln, err := net.Listen(\"tcp\", addrStr)\n\t\trequire.Nil(err)\n\t\tdefer ln.Close()\n\t\tconn, _ := ln.Accept()\n\t\tdefer conn.Close()\n\n\t\t<-exitCh\n\t}()\n\n\ttime.Sleep(100 * time.Millisecond)\n\n\tpool := newTestPool(t)\n\n\tc := make(chan *yamux.Session, 1)\n\tpool.SetConnListener(c)\n\n\t_, err = pool.acquire(\"test\", addr, structs.ApiMajorVersion)\n\trequire.Nil(err)\n\n\tselect {\n\tcase <-c:\n\tcase <-time.After(100 * time.Millisecond):\n\t\tt.Fatalf(\"timeout\")\n\t}\n\n\trequire.Nil(pool.Shutdown())\n\t_, ok := <-c\n\trequire.False(ok)\n}\n\nfunc newTestPool(t *testing.T) *ConnPool ", "output": "{\n\tl := testlog.HCLogger(t)\n\tp := NewPool(l, 1*time.Minute, 10, nil)\n\treturn p\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\nfunc (s *session) UnmarshalJSON(data []byte) error {\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}\n\n\n\nfunc (c *client) Session(ctx context.Context) (*driver.Session, error) ", "output": "{\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}"} {"input": "package alidayu\n\nimport \"encoding/json\"\n\nfunc messasg(cm *commonModel, sm *smsModel) (*Result, error) {\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}\n\n\n\nfunc lecall(cm *commonModel, lm *lecallModel) (*Result, error) ", "output": "{\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}"} {"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\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 ForceMount(device, target, mType, options string) error ", "output": "{\n\tflag, data := parseOptions(options)\n\treturn mount(device, target, mType, uintptr(flag), data)\n}"} {"input": "package strlit\n\nimport (\n\t\"testing\"\n)\n\n\n\nfunc TestNotBareLiteralAsNotLiteral(t *testing.T) {\n\n\tvar complainer NotLiteral = internalNotBareLiteral{} \n\n\tif nil == complainer {\n\t\tt.Error(\"This should never happen.\")\n\t}\n}\n\nfunc TestNotBareLiteralAsError(t *testing.T) ", "output": "{\n\n\tvar err error = internalNotBareLiteral{} \n\n\tif nil == err {\n\t\tt.Error(\"This should never happen.\")\n\t}\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\nfunc TestStateTestSuite(t *testing.T) {\n\tsuite.Run(t, new(StateTestSuite))\n}\n\n\n\nfunc (s *StateTestSuite) TestElapsedTime() ", "output": "{\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}"} {"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\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 (c *Client) GetChannelID(channel string) (string, error) ", "output": "{\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}"} {"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\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 parseHTTPErrorResponse(r io.Reader) error ", "output": "{\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}"} {"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\n\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 (NilHealthcheck) Error() error ", "output": "{ return nil }"} {"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\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) BinaryRequestBody() (*common.OCIReadSeekCloser, bool) ", "output": "{\n\n\treturn nil, false\n\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\nfunc setUpAdd() {\n\ttest.Setup()\n\ttest.SetupFixture([]string{\n\t\t\"log_problem_contribution_reports\",\n\t})\n}\n\n\n\nfunc TestAddPost(t *testing.T) ", "output": "{\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}"} {"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\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) SetData(data []byte) ", "output": "{\n\tf.data = data\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n)\n\n\n\nfunc LIS(arr []int, n int) int {\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}\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 Max(arr []int) int ", "output": "{\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}"} {"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\n\n\n\n\n\n\nfunc DialMaybeCluster(network, addr string, poolSize int) (util.Cmder, error) {\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}\n\nfunc SRVDialFunc(sc *srvclient.SRVClient, timeout time.Duration) func(string, string) (*redis.Client, error) ", "output": "{\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}"} {"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\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\nfunc NewSongPlayer() *SongPlayer {\n\treturn &SongPlayer{}\n}\n\nfunc (player *SongPlayer) CanPlay(song music.Song) bool ", "output": "{\n\treturn true\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\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 testDummy1() *probe.Error ", "output": "{\n\treturn testDummy0().Trace(\"DummyTag1\")\n}"} {"input": "package\nmain\n\nimport (\n\n\t \"fmt\"\n\t\"math\"\n\n)\n\n\n\nfunc print( ) ", "output": "{\n\t fmt.Printf(\"Hello, world. Sqrt(2) = %v\\n\", math.Sqrt(2))\n}"} {"input": "package proxy\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"os/exec\"\n)\n\nvar RuntimeClis = map[string][]string{\n\t\"udb\": {\"mycli\", \"mysql\"},\n\t\"mysql\": {\"mycli\", \"mysql\"},\n\t\"redis\": {\"iredis\", \"redis-cli\"},\n\t\"mongo\": {\"mongo\"},\n}\n\n\n\nfunc GetCliArgs(p *ProxyInfo) []string {\n\tswitch p.Runtime {\n\tcase \"redis\":\n\t\treturn []string{\"redis-cli\", \"-h\", \"127.0.0.1\", \"-a\", p.AuthPassword, \"-p\", p.LocalPort}\n\tcase \"mongo\":\n\t\treturn []string{\"mongo\", \"--host\", \"127.0.0.1\", \"-u\", p.AuthUser, \"-p\", p.AuthPassword, \"-port\", p.LocalPort}\n\tcase \"udb\":\n\t\tpass := fmt.Sprintf(\"-p%s\", p.AuthPassword)\n\t\treturn []string{\"mysql\", \"-h\", \"127.0.0.1\", \"-u\", p.AuthUser, pass, \"-P\", p.LocalPort}\n\tcase \"mysql\":\n\t\tpass := fmt.Sprintf(\"-p%s\", p.AuthPassword)\n\t\treturn []string{\"mysql\", \"-h\", \"127.0.0.1\", \"-u\", p.AuthUser, pass, \"-P\", p.LocalPort}\n\tcase \"es\":\n\t\treturn []string{\"curl\", p.AuthUser + \":\" + p.AuthPassword + \"@\" + \"127.0.0.1\" + \":\" + p.LocalPort}\n\t}\n\n\tpanic(\"invalid runtime\")\n}\n\nfunc ForkExecCli(p *ProxyInfo, term chan bool) error {\n\treturn forkExec(p, term)\n}\n\nfunc getCli(p *ProxyInfo) (string, error) ", "output": "{\n\tclis := RuntimeClis[p.Runtime]\n\tif clis == nil {\n\t\tpanic(\"invalid runtime\")\n\t}\n\n\tvar cli string\n\tfor _, v := range clis {\n\t\tb, err := exec.LookPath(v)\n\t\tif err == nil {\n\t\t\tcli = b\n\t\t\tbreak\n\t\t}\n\t}\n\tif cli == \"\" {\n\t\tmsg := fmt.Sprintf(\"No cli client for LeanDB runtime %s. Please install cli for runtime first.\", p.Runtime)\n\t\treturn \"\", errors.New(msg)\n\t}\n\n\treturn cli, 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\nfunc (c Logger) Configure() {\n\tSetFormatter(c.Format)\n\tSetLogLevel(c.Level)\n}\n\n\n\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 SetLogLevel(lvl string) ", "output": "{\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}"} {"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\nfunc (c *connection) reader() {\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}\n\n\n\nfunc (c *connection) writer() ", "output": "{\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}"} {"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\nfunc NewOrgCreateCommand(c cli.Interface) *cobra.Command {\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}\n\n\n\nfunc createOrg(c cli.Interface, cmd *cobra.Command, opts createOrgOptions) error ", "output": "{\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}"} {"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 TestPluginPush(t *testing.T) {\n\texpectedURL := \"/plugins/plugin_name\"\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\tauth := req.Header.Get(\"X-Registry-Auth\")\n\t\t\tif auth != \"authtoken\" {\n\t\t\t\treturn nil, fmt.Errorf(\"Invalid auth header : expected 'authtoken', got %s\", auth)\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\n\t_, err := client.PluginPush(context.Background(), \"plugin_name\", \"authtoken\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n}\n\nfunc TestPluginPushError(t *testing.T) ", "output": "{\n\tclient := &Client{\n\t\tclient: newMockClient(errorMock(http.StatusInternalServerError, \"Server error\")),\n\t}\n\n\t_, err := client.PluginPush(context.Background(), \"plugin_name\", \"\")\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 sale\n\nimport \"go2o/src/core/domain/interface/valueobject\"\n\n\nfunc ParseToPartialValueItem(v *valueobject.Goods) *ValueItem {\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}\n\n\n\n\nfunc ParseToValueGoods(v *valueobject.Goods) *ValueGoods ", "output": "{\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}"} {"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\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 ErrNoUsername) Error() string ", "output": "{\n\treturn \"Environment variable OS_USERNAME needs to be set.\"\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\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) KvGet(ctx context.Context, key []byte) (value []byte, err error) ", "output": "{\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}"} {"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\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\n\n\nfunc (s *Scope) lookup(name string) *Decl ", "output": "{\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}"} {"input": "package overview\n\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"cloud.google.com/go/pubsub\"\n)\n\n\n\n\nfunc serviceAccount() error ", "output": "{\n\tclient, err := pubsub.NewClient(context.Background(), \"your-project-id\")\n\tif err != nil {\n\t\treturn fmt.Errorf(\"pubsub.NewClient: %v\", err)\n\t}\n\tdefer client.Close()\n\t_ = client\n\n\treturn nil\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"time\"\n\n\t\"gopkg.in/ini.v1\"\n)\n\nfunc DrawClock(r Renderer, f Font) {\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}\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\n\n\nfunc GetDayOfWeek(w time.Weekday) string ", "output": "{\n\tstr, exists := weekdayNames[w]\n\tif !exists {\n\t\treturn \"?\"\n\t}\n\n\treturn str\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\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 Warning(args ...interface{}) ", "output": "{\n\tlogger.Warning(args...)\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\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\n\n\nfunc (self *Template) RenderPage(w http.ResponseWriter, tmpl string, p *Page) ", "output": "{\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}"} {"input": "package introspect\n\nimport (\n\t\"encoding/xml\"\n\t\"github.com/coreos/mantle/Godeps/_workspace/src/github.com/godbus/dbus\"\n\t\"strings\"\n)\n\n\n\n\n\nfunc Call(o *dbus.Object) (*Node, error) ", "output": "{\n\tvar xmldata string\n\tvar node Node\n\n\terr := o.Call(\"org.freedesktop.DBus.Introspectable.Introspect\", 0).Store(&xmldata)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\terr = xml.NewDecoder(strings.NewReader(xmldata)).Decode(&node)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif node.Name == \"\" {\n\t\tnode.Name = string(o.Path())\n\t}\n\treturn &node, nil\n}"} {"input": "package routers\n\nimport (\n\t\"calibre-web/controllers\"\n\t\"github.com/astaxie/beego\"\n)\n\n\n\nfunc init() ", "output": "{\n beego.Router(\"/\", &controllers.MainController{})\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\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 (m *BeeMap) Get(k interface{}) interface{} ", "output": "{\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}"} {"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\nfunc NewForConfig(c *restclient.Config) (*AuthorizationClient, 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 &AuthorizationClient{client}, nil\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\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 setConfigDefaults(config *restclient.Config) error ", "output": "{\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}"} {"input": "package commandreporter_test\n\nimport (\n\t. \"github.com/onsi/ginkgo\"\n\t. \"github.com/onsi/gomega\"\n\n\t\"testing\"\n)\n\n\n\nfunc TestCommandReporter(t *testing.T) ", "output": "{\n\tRegisterFailHandler(Fail)\n\tRunSpecs(t, \"Command Reporter Suite\")\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\n\n\n\nfunc (l *logBuffer) Connect(logger fxevent.Logger) {\n\tl.logger = logger\n\tfor _, e := range l.events {\n\t\tlogger.LogEvent(e)\n\t}\n\tl.events = nil\n}\n\nfunc (l *logBuffer) LogEvent(event fxevent.Event) ", "output": "{\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}"} {"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\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 GetExistingContainerStatus(statuses []ContainerStatus, name string) ContainerStatus ", "output": "{\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}"} {"input": "package bc\n\nimport \"io\"\n\nfunc (VoteOutput) typ() string { return \"voteOutput1\" }\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\n\n\nfunc NewVoteOutput(source *ValueSource, controlProgram *Program, stateData [][]byte, ordinal uint64, vote []byte) *VoteOutput ", "output": "{\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}"} {"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\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\tlog.Print(message)\n\t}\n\tc.ws.Close()\n}\n\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) Writer() ", "output": "{\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}"} {"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\nfunc (e Increment) TypeString() string {\n\treturn \"Increment\"\n}\n\n\n\n\nfunc (e Increment) String() string ", "output": "{\n\treturn fmt.Sprintf(\"{Type: %s, Key: %s, Value: %d}\", e.TypeString(), e.Name, e.Value)\n}"} {"input": "package frank\n\nimport (\n\tfrankconf \"github.com/breunigs/frank/config\"\n\tirc \"github.com/fluffle/goirc/client\"\n\t\"log\"\n\t\"strings\"\n)\n\n\n\nfunc ItsAlive(conn *irc.Conn, line *irc.Line) ", "output": "{\n\tif line.Args[0] != conn.Me().Nick {\n\t\treturn\n\t}\n\n\tmsg := line.Args[1]\n\tif !strings.HasPrefix(msg, \"msg #\") {\n\t\treturn\n\t}\n\n\tif line.Nick != frankconf.Master {\n\t\tlog.Printf(\"only answering to master %s, but was %s\", frankconf.Master, line.Nick)\n\t\treturn\n\t}\n\n\tcmd := strings.SplitN(msg, \" \", 3)\n\tchannel := cmd[1]\n\tmsg = cmd[2]\n\n\tlog.Printf(\"master command: posting “%s” to %s\", msg, channel)\n\tconn.Privmsg(channel, msg)\n\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\n\n\ntype URL string\n\nfunc (t URL) Validate() error {\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}\n\nfunc (t Name) Validate() error ", "output": "{\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}"} {"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[:]) }\n\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_) Bytes() []byte ", "output": "{ return h[:] }"} {"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\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\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 NewFromPost() blocks.BlockInterface ", "output": "{\n\treturn &FromPost{}\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\nfunc TestISO639_2Constructor(t *testing.T) {\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}\n\n\n\nfunc TestISO639_2MarshalUnmarshal(t *testing.T) ", "output": "{\n\tv := terms.NewISO639_2()\n\tbuf, _ := xml.Marshal(v)\n\tv2 := terms.NewISO639_2()\n\txml.Unmarshal(buf, v2)\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\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 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\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 NewFakeMetricsDu(path string, stats *volume.Metrics) volume.MetricsProvider ", "output": "{\n\treturn &fakeMetricsDu{fakeStats: stats}\n}"} {"input": "package http\n\nimport (\n\t\"go-common/app/admin/main/credit/model/blocked\"\n\tbm \"go-common/library/net/http/blademaster\"\n)\n\n\n\nfunc delQuestion(c *bm.Context) {\n\tv := new(struct {\n\t\tIDS []int64 `form:\"ids,split\" validate:\"min=1,max=20\"`\n\t\tStatus int8 `form:\"status\" validate:\"min=0,max=1\" default:\"1\"`\n\t\tOID int `form:\"oper_id\" validate:\"required\"`\n\t})\n\tif err := c.Bind(v); err != nil {\n\t\treturn\n\t}\n\tif err := creSvc.DB.Model(&blocked.LabourQuestion{}).Where(v.IDS).Updates(map[string]interface{}{\"isdel\": v.Status, \"oper_id\": v.OID}).Error; err != nil {\n\t\thttpCode(c, err)\n\t\treturn\n\t}\n\thttpCode(c, nil)\n}\n\nfunc operQuestion(c *bm.Context) ", "output": "{\n\tv := new(struct {\n\t\tIDS []int64 `form:\"ids,split\" validate:\"min=1,max=20\"`\n\t\tStatus int8 `form:\"status\" validate:\"min=0,max=1\" default:\"1\"`\n\t\tOID int `form:\"oper_id\" validate:\"required\"`\n\t})\n\tif err := c.Bind(v); err != nil {\n\t\treturn\n\t}\n\tif err := creSvc.DB.Model(&blocked.LabourQuestion{}).Where(v.IDS).Updates(map[string]interface{}{\"status\": v.Status, \"oper_id\": v.OID}).Error; err != nil {\n\t\thttpCode(c, err)\n\t\treturn\n\t}\n\thttpCode(c, nil)\n}"} {"input": "package archive\n\nimport \"golang.org/x/sys/unix\"\n\n\n\nfunc mknod(path string, mode uint32, dev uint64) error {\n\treturn unix.Mknod(path, mode, dev)\n}\n\n\n\n\nfunc lsetxattrCreate(link string, attr string, data []byte) error ", "output": "{\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}"} {"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\nfunc (self *CmdGetDataCost) RpcResult() interface{} {\n\treturn &engine.DataCost{}\n}\n\n\n\nfunc (self *CmdGetDataCost) ClientArgs() []string ", "output": "{\n\treturn self.clientArgs\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\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\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) Metadata() barcode.Metadata ", "output": "{\n\treturn barcode.Metadata{barcode.TypePDF, 2}\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\n\n\nfunc (self *CmdRemoveBalance) RpcResult() interface{} {\n\tvar s string\n\treturn &s\n}\n\nfunc (self *CmdRemoveBalance) PostprocessRpcParams() error ", "output": "{\n\treturn nil\n}"} {"input": "package plan9\n\nimport \"syscall\"\n\nfunc fixwd() {\n\tsyscall.Fixwd()\n}\n\n\n\nfunc Chdir(path string) error {\n\treturn syscall.Chdir(path)\n}\n\nfunc Getwd() (wd string, err error) ", "output": "{\n\treturn syscall.Getwd()\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\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\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) Close() error ", "output": "{\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}"} {"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\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\n\n\nfunc (f *formatFn) SetArgs(args []sh.Obj) error ", "output": "{\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}"} {"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\nfunc InitLogDestination() error {\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}\n\n\n\n\nfunc Flog(format string, a ...interface{}) ", "output": "{\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}"} {"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\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\n\n\nfunc (l *MultiLoader) Add(add Loader) ", "output": "{\n\tl.loaders = append(l.loaders, add)\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\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) Delete(id string) error ", "output": "{\n\treturn nil\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\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) setAddr(defaultPort string) ", "output": "{\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}"} {"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\n\n\nfunc (light *LightData) IsLight() bool {\n\treturn light.isLight\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 NewLightDataNone() *LightData ", "output": "{\n\treturn &LightData{false, core.NewVec3Zero()}\n}"} {"input": "package main\n\n\n\nimport (\n\t\"fmt\"\n)\n\n\n\n\n\n\n\n\n\n\nfunc main() {\n\n\tfmt.Println(\"20!=\", Silnia(20))\n}\n\nfunc Silnia(n uint64) uint64 ", "output": "{\n\n\n\tif n <= 1 {\n\t\treturn 1\n\t}\n\n\treturn n * Silnia(n-1)\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\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\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) Add(s string) ", "output": "{\n\ta.w.Insert([]string{s})\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\n\n\nfunc systemDirs(dir string) (directories []string) {\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}\n\nfunc listPackages(dir string) (directories []string) ", "output": "{\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}"} {"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\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\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 TestIsAuthType(t *testing.T) ", "output": "{\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}"} {"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\n\n\n\nfunc (response TerminateDbSystemResponse) HTTPResponse() *http.Response {\n\treturn response.RawResponse\n}\n\nfunc (response TerminateDbSystemResponse) String() string ", "output": "{\n\treturn common.PointerString(response)\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\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\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 startServer() ", "output": "{\n\twebApp.Run(\":3000\")\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\nfunc NewApplicationSettingsNotificationsVpn() *ApplicationSettingsNotificationsVpn {\n\treturn &ApplicationSettingsNotificationsVpn{}\n}\n\n\n\nfunc (a *ApplicationSettingsNotificationsVpn) IsApplicationInstance() bool ", "output": "{\n\treturn true\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\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\n\n\nfunc Int64ToBytes(n int64) []byte ", "output": "{\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}"} {"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\nfunc (table *Table) Metadata() interface{} {\n\treturn table.metadata\n}\n\n\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) SetMetadata(metadata interface{}) ", "output": "{\n\ttable.metadata = metadata\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\n\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) SystemStreamAcl() *StreamAcl ", "output": "{ return s.systemStreamAcl }"} {"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\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\nfunc (this *NoteContentHistoryService) ListHistories(noteId, userId string) []info.EachHistory {\n\thistories := info.NoteContentHistory{}\n\tdb.GetByIdAndUserId(db.NoteContentHistories, noteId, userId, &histories)\n\treturn histories.Histories\n}\n\nfunc (this *NoteContentHistoryService) AddHistory(noteId, userId string, eachHistory info.EachHistory) ", "output": "{\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}"} {"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\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\n\n\nfunc (this *StateInMemory) Trap(message string, args ...interface{}) error ", "output": "{\n\treturn ParsexError{(*this).pos,\n\t\tfmt.Sprintf(message, args...)}\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\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 decodeEmptyRequest(ctx context.Context, r *http.Request) (interface{}, error) ", "output": "{\n\treturn nil, nil\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\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\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 mustCreateConn() *clientv3.Client ", "output": "{\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}"} {"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\nfunc (r *EscalateToNextRequest) GenerateUrl() (string, url.Values, error) {\n\tpath, params, err := r.Identifier.GenerateUrl()\n\treturn path + \"/escalate\", params, err\n}\n\n\n\nfunc (r *EscalateToNextRequest) GetApiKey() string ", "output": "{\n\treturn r.ApiKey\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\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\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) EscapeCharacter() rune ", "output": "{\n\treturn db.escapeChar\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\nfunc TestDeleteFailureUnmarshal(t *testing.T) {\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}\n\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 TestDeleteFailureMarshal(t *testing.T) ", "output": "{\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}"} {"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\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) BinaryRequestBody() (*common.OCIReadSeekCloser, bool) ", "output": "{\n\n\treturn nil, false\n\n}"} {"input": "package main\n\nimport (\n\t\"encoding/json\"\n\t\"io/ioutil\"\n\t\"fmt\"\n\t\"gsf/log\"\n)\n\ntype Config struct {\n\tDaemon \t\tint \t\t\t\t\t\t`json:\"daemon\"`\t\t\t\t\t\n\tServerAddr \tstring \t\t\t\t\t\t`json:\"server_addr\"`\t\t\t\n\tLogConf \tlog.LoggerConfig\t\t\t`json:\"log_conf\"`\t\t\t\t\n}\n\nvar config = &Config{}\nvar logger *log.Logger = nil\n\n\n\nfunc (c *Config) String() string {\n\tdata, err := json.Marshal(c)\n\tif err != nil {\n\t\treturn fmt.Sprintf(\"config json failed, err:\", err)\n\t}\n\treturn string(data)\n}\n\nfunc (c *Config) Init(filename string) error ", "output": "{\n\tdata, err := ioutil.ReadFile(filename)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = json.Unmarshal(data, c)\n\tif err != nil {\n\t\treturn err\n\t}\n\tlogger, err = log.NewByConfig(&config.LogConf)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\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\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\n\n\nfunc (o *DaemonSetControllerOptions) Validate() []error ", "output": "{\n\tif o == nil {\n\t\treturn nil\n\t}\n\n\terrs := []error{}\n\treturn errs\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\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\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 init() ", "output": "{\n\tif err := mb.Registry.AddMetricSet(\"docker\", \"info\", New, docker.HostParser); err != nil {\n\t\tpanic(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\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 (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 elasticsearch_test\n\nimport (\n\t\"fmt\"\n\t\"path/filepath\"\n\t\"reflect\"\n\t\"runtime\"\n\t\"testing\"\n)\n\n\n\n\ntype Test struct{}\n\n\nfunc (t *Test) 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 (t *Test) 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 (t *Test) 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 s0095\n\nimport \"github.com/peterstace/project-euler/number\"\n\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\nfunc findChain(x int, sumProperDivisors []int) (chainLength, smallestInChain int, ok bool) {\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}\n\nfunc Answer() interface{} ", "output": "{\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}"} {"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\nfunc (s Secret) Bytes() ([]byte, error) {\n\treturn base32.StdEncoding.DecodeString(s.String())\n}\n\n\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) String() string ", "output": "{\n\treturn string(s)\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() }\n\nfunc (W _container_heap_Interface) Swap(i int, j int) { W.WSwap(i, j) }\n\nfunc (W _container_heap_Interface) Push(x interface{}) ", "output": "{ W.WPush(x) }"} {"input": "package http\n\nimport (\n\t\"math/rand\"\n\t\"time\"\n)\n\n\n\n\n\n\n\nfunc backoff(base, max, jitter, factor float64, retries int) time.Duration {\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}\n\nfunc defaultBackoff(base, max float64, retries int) time.Duration ", "output": "{\n\treturn backoff(base, max, .2, 1.6, retries)\n}"} {"input": "package hammer\n\n\nvar (\n\tconsumers []consumer\n\tconsumerMap map[string]consumerFunc\n)\n\n\n\nfunc init() ", "output": "{\n\tconsumerMap = make(map[string]consumerFunc)\n}"} {"input": "package server\n\nimport (\n\t\"context\"\n\t\"reflect\"\n\t\"testing\"\n\n\t\"github.com/divisionone/go-micro/registry\"\n)\n\ntype testHandler struct{}\n\ntype testRequest struct{}\n\ntype testResponse struct{}\n\n\n\nfunc TestExtractEndpoint(t *testing.T) {\n\thandler := &testHandler{}\n\ttyp := reflect.TypeOf(handler)\n\n\tvar endpoints []*registry.Endpoint\n\n\tfor m := 0; m < typ.NumMethod(); m++ {\n\t\tif e := extractEndpoint(typ.Method(m)); e != nil {\n\t\t\tendpoints = append(endpoints, e)\n\t\t}\n\t}\n\n\tif i := len(endpoints); i != 1 {\n\t\tt.Errorf(\"Expected 1 endpoint, have %d\", i)\n\t}\n\n\tif endpoints[0].Name != \"Test\" {\n\t\tt.Errorf(\"Expected handler Test, got %s\", endpoints[0].Name)\n\t}\n\n\tif endpoints[0].Request == nil {\n\t\tt.Error(\"Expected non nil request\")\n\t}\n\n\tif endpoints[0].Response == nil {\n\t\tt.Error(\"Expected non nil request\")\n\t}\n\n\tif endpoints[0].Request.Name != \"testRequest\" {\n\t\tt.Errorf(\"Expected testRequest got %s\", endpoints[0].Request.Name)\n\t}\n\n\tif endpoints[0].Response.Name != \"testResponse\" {\n\t\tt.Errorf(\"Expected testResponse got %s\", endpoints[0].Response.Name)\n\t}\n\n\tif endpoints[0].Request.Type != \"testRequest\" {\n\t\tt.Errorf(\"Expected testRequest type got %s\", endpoints[0].Request.Type)\n\t}\n\n\tif endpoints[0].Response.Type != \"testResponse\" {\n\t\tt.Errorf(\"Expected testResponse type got %s\", endpoints[0].Response.Type)\n\t}\n\n}\n\nfunc (t *testHandler) Test(ctx context.Context, req *testRequest, rsp *testResponse) error ", "output": "{\n\treturn nil\n}"} {"input": "package framework\n\ntype HorizontalAlignment int\n\nconst (\n\tAlignLeft HorizontalAlignment = iota\n\tAlignCenter\n\tAlignRight\n)\n\n\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 }\nfunc (a VerticalAlignment) AlignMiddle() bool { return a == AlignMiddle }\nfunc (a VerticalAlignment) AlignBottom() bool { return a == AlignBottom }\n\nfunc (a HorizontalAlignment) AlignLeft() bool ", "output": "{ return a == AlignLeft }"} {"input": "package vt100\n\n\n\n\nfunc TermSize() (uint, uint, error) ", "output": "{\n\treturn 80, 25, nil\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\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 forbiddenMessage(attributes authorizer.Attributes) string ", "output": "{\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}"} {"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\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 (m *MockPrinter) Help() ", "output": "{\n\tm.Called()\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\nfunc (s *Setting) GetJson(value interface{}) error {\n\treturn json.Unmarshal([]byte(s.Value), value)\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\n\n\nfunc ReadSettingsToGlobal() error ", "output": "{\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}"} {"input": "package printers\n\nimport (\n\t\"io\"\n\n\t\"k8s.io/apimachinery/pkg/runtime\"\n\t\"k8s.io/apimachinery/pkg/runtime/schema\"\n)\n\n\ntype ResourcePrinter interface {\n\tPrintObj(runtime.Object, io.Writer) error\n}\n\n\ntype ResourcePrinterFunc func(runtime.Object, io.Writer) error\n\n\n\n\n\ntype PrintOptions struct {\n\tOutputFormatType string\n\tOutputFormatArgument string\n\n\tNoHeaders bool\n\tWithNamespace bool\n\tWithKind bool\n\tWide bool\n\tShowLabels bool\n\tAbsoluteTimestamps bool\n\tKind schema.GroupKind\n\tColumnLabels []string\n\n\tSortBy string\n\n\tAllowMissingKeys bool\n}\n\nfunc (fn ResourcePrinterFunc) PrintObj(obj runtime.Object, w io.Writer) error ", "output": "{\n\treturn fn(obj, w)\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\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 TestNewMake(t *testing.T) ", "output": "{\n\ttc, _, _ := createTestConfigs(t, nil, nil)\n\t_, err := NewMake(tc)\n\tok(t, err)\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}\nfunc (r response) Body() io.ReadCloser {\n\treturn ioutil.NopCloser(bytes.NewBufferString(\"the content\"))\n}\n\n\n\nfunc TestResponseReaderFunc(t *testing.T) ", "output": "{\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}"} {"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\nfunc IndexNewsIDS(redisPool *redis.Pool, newsIDChan chan []bson.ObjectId) {\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}\n\n\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 RetrieveCachedNews(key string, redisPool *redis.Pool) ([]bson.ObjectId, error) ", "output": "{\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}"} {"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\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) SetMaster(master *os.File) ", "output": "{\n\tt.master = master\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\n\n\nfunc (t ContentType) Equal(v ContentType) bool {\n\treturn t == v\n}\n\nfunc (t ContentType) Valid() bool ", "output": "{\n\treturn strings.HasPrefix(t.String(), PREFIX_FADERDATATYPE)\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\nfunc (uo *UpdateOptions) SetUpsert(b bool) *UpdateOptions {\n\tuo.Upsert = &b\n\treturn uo\n}\n\n\n\n\nfunc MergeUpdateOptions(opts ...*UpdateOptions) *UpdateOptions ", "output": "{\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}"} {"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\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) KeepaliveLoop(ka time.Duration) error ", "output": "{\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}"} {"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\nfunc InstallExternalLegacyUser(scheme *runtime.Scheme) {\n\tschemeBuilder := runtime.NewSchemeBuilder(\n\t\taddUngroupifiedUserTypes,\n\t\tcorev1.AddToScheme,\n\t)\n\tutilruntime.Must(schemeBuilder.AddToScheme(scheme))\n}\n\n\n\nfunc addUngroupifiedUserTypes(scheme *runtime.Scheme) error ", "output": "{\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}"} {"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\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\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 TestPostgresPut(t *testing.T) ", "output": "{\n\ttestServicePut(t, preparePostgres)\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\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\n\n\nfunc VersionCmp(a, b string) int ", "output": "{\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}"} {"input": "package common\n\nimport (\n\t\"os/exec\"\n)\n\n\n\nfunc CheckExec(commandName string, args ...string) (string, error) {\n\tb, err := exec.Command(commandName, args...).CombinedOutput()\n\treturn string(b), err\n}\n\nfunc IsExecWorking(commandName string, args ...string) bool ", "output": "{\n\tout, err := CheckExec(commandName, args...)\n\treturn err == nil && len(out) > 0\n}"} {"input": "package main\n\nimport (\n\tirc \"github.com/thoj/go-ircevent\"\n)\n\n\n\nfunc main() {\n\n\tconfig := readConfig()\n\tconn := connect(config)\n\tconn.AddCallback(\"001\", func(event *irc.Event) {\n\t\tfor _, channel := range config.Channels {\n\t\t\tconn.Join(channel)\n\t\t}\n\t})\n\tgo loadPlugins(conn)\n\n\tconn.Loop()\n}\n\nfunc connect(config Config) *irc.Connection ", "output": "{\n\tconn := irc.IRC(config.Name, config.Name)\n\tconn.Connect(config.Server)\n\treturn conn\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\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 Parse(_ string) (XPathExec, error) ", "output": "{\n\treturn XPathExec{}, nil\n}"} {"input": "package tango\n\nimport (\n\t\"bytes\"\n\t\"net/http\"\n\t\"net/http/httptest\"\n\t\"testing\"\n)\n\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\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 TestDir1(t *testing.T) ", "output": "{\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}"} {"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\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\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) String() string ", "output": "{\n\treturn tok.TokenType.String() + \": \" + tok.Raw\n}"} {"input": "package api\n\nimport (\n\t\"errors\"\n\t\"net/http\"\n\t\"os\"\n)\n\n\ntype Config struct {\n\tScheme string\n\n\tAddress string\n\n\tKey string\n\n\tSecret string\n\n\tHttpClient *http.Client\n}\n\n\n\n\nfunc DefaultConfig() (*Config, error) ", "output": "{\n\tkey := os.Getenv(\"MIXPANEL_API_KEY\")\n\tsecret := os.Getenv(\"MIXPANEL_SECRET\")\n\tif key == \"\" || secret == \"\" {\n\t\treturn nil, errors.New(\"Mixpanel API credentials not found.\")\n\t}\n\n\treturn &Config{\n\t\tScheme: \"http\",\n\t\tAddress: \"data.mixpanel.com\",\n\t\tKey: key,\n\t\tSecret: secret,\n\t\tHttpClient: http.DefaultClient,\n\t}, nil\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\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 GenerateRandomBytes(n int) ([]byte, error) ", "output": "{\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}"} {"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\nfunc (s *InsecureServingOptions) AddFlags(fs *pflag.FlagSet) {\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}\n\n\n\n\n\nfunc (s *InsecureServingOptions) ApplyTo(c **genericcontrollermanager.InsecureServingInfo) error ", "output": "{\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}"} {"input": "package winapi\n\nimport (\n\t\"unsafe\"\n)\n\n\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\nfunc DefMDIChildProc(hWnd uintptr, uMsg uintptr, wParam uintptr, lParam uintptr) (uintptr, error) {\n\tr1, _, err := procDefMDIChildProc.Call(hWnd, uMsg, wParam, lParam)\n\treturn r1, err\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 CreateMDIWindow(lpClassName string, lpWindowName string, dwStyle uintptr, X int32, Y int32, nWidth uintptr, nHeight uintptr, hWndParent uintptr, hInstance uintptr, lParam uintptr) (uintptr, error) ", "output": "{\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}"} {"input": "package jwt\n\nimport (\n\t\"time\"\n\n\t\"github.com/dgrijalva/jwt-go\"\n)\n\n\ntype AccessToken struct {\n\tType string `json:\"token_type\"`\n\tToken string `json:\"access_token\"`\n\tExpires int64 `json:\"expires_in\"`\n}\n\n\n\n\nfunc IssueAdminToken(signingMethod SigningMethod, claims jwt.MapClaims, expireIn time.Duration) (*AccessToken, error) ", "output": "{\n\ttoken := jwt.New(jwt.GetSigningMethod(signingMethod.Alg))\n\texp := time.Now().Add(expireIn).Unix()\n\n\ttoken.Claims = claims\n\tclaims[\"exp\"] = exp\n\tclaims[\"iat\"] = time.Now().Unix()\n\n\taccessToken, err := token.SignedString([]byte(signingMethod.Key))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &AccessToken{\n\t\tType: \"Bearer\",\n\t\tToken: accessToken,\n\t\tExpires: exp,\n\t}, nil\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\nfunc tagsFromMapRedshift(m map[string]interface{}) []*redshift.Tag {\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}\n\n\n\nfunc tagsToMapRedshift(ts []*redshift.Tag) map[string]string ", "output": "{\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}"} {"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\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\nfunc (m bootvolumesourcedetails) String() string {\n\treturn common.PointerString(m)\n}\n\nfunc (m *bootvolumesourcedetails) UnmarshalJSON(data []byte) error ", "output": "{\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}"} {"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\nfunc (s *EnvSuite) SetUpSuite(c *C) {\n\ts.environ = os.Environ()\n}\n\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) SetUpTest(c *C) ", "output": "{\n\tos.Clearenv()\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\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) String() string ", "output": "{\n\treturn fmt.Sprintf(\"RelayPort: %d\", op.DownstreamSourcePort)\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\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) Volumes() VolumeIterator ", "output": "{\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}"} {"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\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) Write(body []byte) (n int, err error) ", "output": "{\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}"} {"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\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_StopTask(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\terr = manager.StopTask(task.Name)\n\tassertion.Nil(err)\n\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\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\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 RemoveCleanupAction(p CleanupActionHandle) ", "output": "{\n\tcleanupActionsLock.Lock()\n\tdefer cleanupActionsLock.Unlock()\n\tdelete(cleanupActions, p)\n}"} {"input": "package core\n\nimport (\n\t\"os/exec\"\n)\n\n\n\nfunc Open(url string) error ", "output": "{\n\treturn exec.Command(\"xdg-open\", url).Run()\n}"} {"input": "package lang\n\nimport \"math\"\nimport \"gojvm/native\"\nimport \"gojvm/rtda\"\n\nconst jlDouble = \"java/lang/Double\"\n\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\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 init() ", "output": "{\n\tnative.Register(jlDouble, \"doubleToRawLongBits\", \"(D)J\", doubleToRawLongBits)\n\tnative.Register(jlDouble, \"longBitsToDouble\", \"(J)D\", longBitsToDouble)\n}"} {"input": "package config\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\n\n\nfunc assertHoardConfigSerialisation(t *testing.T,\n\tserialise func(*HoardConfig) string,\n\tdeserialise func(string) (*HoardConfig, error),\n\thoardConfig *HoardConfig) {\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}\n\nfunc TestDefaultHoardConfig(t *testing.T) ", "output": "{\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}"} {"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\n\n\n\nfunc (response GetCrossConnectResponse) HTTPResponse() *http.Response {\n\treturn response.RawResponse\n}\n\nfunc (response GetCrossConnectResponse) String() string ", "output": "{\n\treturn common.PointerString(response)\n}"} {"input": "package apicaller\n\nimport (\n\t\"github.com/juju/errors\"\n\n\t\"github.com/juju/juju/agent\"\n\t\"github.com/juju/juju/api/base\"\n\t\"github.com/juju/juju/worker\"\n\t\"github.com/juju/juju/worker/dependency\"\n)\n\n\ntype ManifoldConfig struct {\n\tAgentName string\n}\n\n\n\nfunc Manifold(config ManifoldConfig) dependency.Manifold {\n\treturn dependency.Manifold{\n\t\tInputs: []string{\n\t\t\tconfig.AgentName,\n\t\t},\n\t\tOutput: outputFunc,\n\t\tStart: startFunc(config),\n\t}\n}\n\n\n\nfunc startFunc(config ManifoldConfig) dependency.StartFunc {\n\treturn func(getResource dependency.GetResourceFunc) (worker.Worker, error) {\n\n\t\tvar a agent.Agent\n\t\tif err := getResource(config.AgentName, &a); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tconn, err := openConnection(a)\n\t\tif err != nil {\n\t\t\treturn nil, errors.Annotate(err, \"cannot open api\")\n\t\t}\n\n\t\tcurrentConfig := a.CurrentConfig()\n\t\tif currentConfig.Environment().Id() == \"\" {\n\t\t\terr := a.ChangeConfig(func(setter agent.ConfigSetter) error {\n\t\t\t\tenvironTag, err := conn.EnvironTag()\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn errors.Annotate(err, \"no environment uuid set on api\")\n\t\t\t\t}\n\t\t\t\treturn setter.Migrate(agent.MigrateParams{\n\t\t\t\t\tEnvironment: environTag,\n\t\t\t\t})\n\t\t\t})\n\t\t\tif err != nil {\n\t\t\t\tlogger.Warningf(\"unable to save environment uuid: %v\", err)\n\t\t\t}\n\t\t}\n\n\t\treturn newApiConnWorker(conn)\n\t}\n}\n\n\n\n\nfunc outputFunc(in worker.Worker, out interface{}) error ", "output": "{\n\tinWorker, _ := in.(*apiConnWorker)\n\toutPointer, _ := out.(*base.APICaller)\n\tif inWorker == nil || outPointer == nil {\n\t\treturn errors.Errorf(\"expected %T->%T; got %T->%T\", inWorker, outPointer, in, out)\n\t}\n\t*outPointer = inWorker.conn\n\treturn nil\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\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\n\n\nfunc tileNameFormatValidate(cmd *cobra.Command, args []string) (err error) ", "output": "{\n\tformat, err = NewFormat(tileListFormat)\n\treturn err\n}"} {"input": "package main\n\nimport (\n\t\"log\"\n\n\t\"github.com/zeromq/goczmq\"\n)\n\n\n\n\n\n\n\n\n\n\n\nfunc SimpleHelloWorldServer() {\n\tlog.Printf(\"server starting...\")\n\n\n\tserver, err := goczmq.NewRep(\"tcp://*:5555\")\n\tif err != nil {\n\t\tlog.Fatalf(\"server.NewRep error: %s\", err)\n\t}\n\n\n\tdefer server.Destroy()\n\n\n\trequest, err := server.RecvMessage()\n\tif err != nil {\n\t\tlog.Fatalf(\"server.RecvMessage error: %s\", err)\n\t}\n\n\tlog.Printf(\"server.RecvMessage: '%s'\", request)\n\n\n\treply := [][]byte{[]byte(\"World\")}\n\n\n\terr = server.SendMessage(reply)\n\tif err != nil {\n\t\tlog.Fatalf(\"server.SendMessage error: %s\", err)\n\t}\n\n\tlog.Printf(\"server.SendMessage: '%s'\", reply)\n}\n\n\n\nfunc main() {\n\tgo SimpleHelloWorldServer()\n\tSimpleHelloWorldClient()\n}\n\nfunc SimpleHelloWorldClient() ", "output": "{\n\tlog.Printf(\"client starting...\")\n\n\n\tclient, err := goczmq.NewReq(\"tcp://localhost:5555\")\n\tif err != nil {\n\t\tlog.Fatalf(\"client.NewReq error: %s\", err)\n\t}\n\n\n\tdefer client.Destroy()\n\n\n\trequest := [][]byte{[]byte(\"Hello\")}\n\n\n\terr = client.SendMessage(request)\n\tif err != nil {\n\t\tlog.Fatalf(\"client.SendMessage error: %s\", err)\n\t}\n\n\tlog.Printf(\"client.SendMessage '%s'\", request)\n\n\n\treply, err := client.RecvMessage()\n\tif err != nil {\n\t\tlog.Fatalf(\"client.RecvMessage error: %s\", err)\n\t}\n\n\tlog.Printf(\"client.RecvMessage: '%s'\", reply)\n}"} {"input": "package testblas\n\nimport (\n\t\"math/rand\"\n\t\"testing\"\n\n\t\"github.com/gonum/blas\"\n)\n\nfunc DgemvBenchmark(b *testing.B, blasser Dgemver, tA blas.Transpose, m, n, incX, incY int) {\n\tvar lenX, lenY int\n\tif tA == blas.NoTrans {\n\t\tlenX = n\n\t\tlenY = m\n\t} else {\n\t\tlenX = m\n\t\tlenY = n\n\t}\n\txr := make([]float64, lenX)\n\tfor i := range xr {\n\t\txr[i] = rand.Float64()\n\t}\n\tx := makeIncremented(xr, incX, 0)\n\tyr := make([]float64, lenY)\n\tfor i := range yr {\n\t\tyr[i] = rand.Float64()\n\t}\n\ty := makeIncremented(yr, incY, 0)\n\ta := make([]float64, m*n)\n\tfor i := range a {\n\t\ta[i] = rand.Float64()\n\t}\n\n\tb.ResetTimer()\n\tfor i := 0; i < b.N; i++ {\n\t\tblasser.Dgemv(tA, m, n, 2, a, n, x, incX, 3, y, incY)\n\t}\n}\n\n\n\nfunc DgerBenchmark(b *testing.B, blasser Dgerer, m, n, incX, incY int) ", "output": "{\n\txr := make([]float64, m)\n\tfor i := range xr {\n\t\txr[i] = rand.Float64()\n\t}\n\tx := makeIncremented(xr, incX, 0)\n\tyr := make([]float64, n)\n\tfor i := range yr {\n\t\tyr[i] = rand.Float64()\n\t}\n\ty := makeIncremented(yr, incY, 0)\n\ta := make([]float64, m*n)\n\tfor i := range a {\n\t\ta[i] = rand.Float64()\n\t}\n\n\tb.ResetTimer()\n\tfor i := 0; i < b.N; i++ {\n\t\tblasser.Dger(m, n, 2, x, incX, y, incY, a, n)\n\t}\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\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\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 TestPackage(t *testing.T) ", "output": "{\n\tTestingT(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\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\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) publishEvent() ", "output": "{\n\tj.mu.RLock()\n\tj.eventCh <- j.jobCounter\n\tj.mu.RUnlock()\n}"} {"input": "package client\n\nimport (\n\t\"golang.org/x/net/context\"\n\t\"google.golang.org/grpc\"\n)\n\n\n\n\n\n\nfunc wrap(ui grpc.UnaryInvoker, interceptors ...grpc.UnaryClientInterceptor) grpc.UnaryInvoker {\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}\n\nfunc WrapperUnaryClient(interceptors ...grpc.UnaryClientInterceptor) grpc.UnaryClientInterceptor ", "output": "{\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}"} {"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\n\nfunc (a ByNumericalValue) Swap(i, j int) { a[i], a[j] = a[j], a[i] }\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) Len() int ", "output": "{ return len(a) }"} {"input": "package css\n\nimport (\n\t\"github.com/stretchr/testify/assert\"\n\t\"testing\"\n)\n\n\n\nfunc TestRuleTypeString(t *testing.T) ", "output": "{\n\tassert.Equal(t, STYLE_RULE.Text(), \"\")\n\tassert.Equal(t, CHARSET_RULE.Text(), \"@charset\")\n\tassert.Equal(t, IMPORT_RULE.Text(), \"@import\")\n\tassert.Equal(t, MEDIA_RULE.Text(), \"@media\")\n\tassert.Equal(t, FONT_FACE_RULE.Text(), \"@font-face\")\n\tassert.Equal(t, PAGE_RULE.Text(), \"@page\")\n}"} {"input": "package structs\n\nimport \"fmt\"\n\n\ntype Bitmap []byte\n\n\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\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 NewBitmap(size uint) (Bitmap, error) ", "output": "{\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}"} {"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\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 ContainerAgentConf(info AgentInfo, renderer shell.Renderer, containerType string) common.Conf ", "output": "{\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}"} {"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\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 (c *Concentration) Parse(parser structure.ObjectParser) ", "output": "{\n\tc.Units = parser.String(\"units\")\n\tc.Value = parser.Float64(\"value\")\n}"} {"input": "package main\n\nimport (\n \"fmt\"\n \"github.com/cailei/gopm_index/gopm/index\"\n \"github.com/hailiang/gosocks\"\n \"io\"\n \"io/ioutil\"\n \"log\"\n \"net/http\"\n \"net/url\"\n \"os\"\n)\n\ntype Agent struct {\n client *http.Client\n}\n\nfunc newAgent() *Agent {\n client := http.DefaultClient\n\n \n proxy_addr := os.Getenv(\"GOPM_PROXY\")\n if proxy_addr != \"\" {\n fmt.Printf(\"NOTE: Using socks5 proxy: %v\\n\", proxy_addr)\n proxy := socks.DialSocksProxy(socks.SOCKS5, proxy_addr)\n transport := &http.Transport{Dial: proxy}\n client = &http.Client{Transport: transport}\n }\n\n return &Agent{client}\n}\n\nfunc (agent *Agent) getFullIndexReader() io.Reader {\n request := remote_db_host + \"/all\"\n return agent._get_body_reader(request)\n}\n\n\n\nfunc (agent *Agent) _get_body_reader(request string) io.ReadCloser {\n \n response, err := agent.client.Get(request)\n if err != nil {\n log.Fatalln(err)\n }\n\n \n if response.StatusCode != 200 {\n body, err := ioutil.ReadAll(response.Body)\n if err != nil {\n log.Fatalln(err)\n }\n\n if len(body) > 0 {\n fmt.Println(string(body))\n }\n\n log.Fatalln(response.Status)\n }\n\n return response.Body\n}\n\nfunc (agent *Agent) uploadPackage(meta index.PackageMeta) ", "output": "{\n request := fmt.Sprintf(\"%v/publish\", remote_db_host)\n\n \n json, err := meta.ToJson()\n if err != nil {\n log.Fatalln(err)\n }\n\n \n response, err := http.PostForm(request, url.Values{\"pkg\": {string(json)}})\n if err != nil {\n log.Fatalln(err)\n }\n\n body, err := ioutil.ReadAll(response.Body)\n defer response.Body.Close()\n if err != nil {\n log.Fatalln(err)\n }\n\n if len(body) > 0 {\n fmt.Println(string(body))\n }\n\n \n if response.StatusCode != 200 {\n log.Fatalln(response.Status)\n }\n}"} {"input": "package main\n\nimport (\n \"os\"\n \"os/exec\"\n \"log\"\n)\n\nfunc vim(files []string) {\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}\n\n\n\nfunc mvim(files []string) ", "output": "{\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}"} {"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\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 TestNotifyLockOnUnlock(t *testing.T) ", "output": "{\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}"} {"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\nfunc (l *lexerStream) rewind(amount int) {\n\tl.position -= amount\n}\n\n\n\nfunc (l lexerStream) canRead() bool ", "output": "{\n\treturn l.position < l.length\n}"} {"input": "package util\n\nimport (\n\t\"context\"\n\t\"syscall\"\n\t\"testing\"\n)\n\n\n\nfunc TestCancelOnInterrupt(t *testing.T) ", "output": "{\n\tctx := CancelOnInterrupt(context.Background())\n\tclose := make(chan struct{})\n\n\tgo func() {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\tclose <- struct{}{}\n\t\t}\n\t}()\n\n\tsyscall.Kill(syscall.Getpid(), syscall.SIGINT)\n\n\t<-close\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/DataDog/datadog-go/statsd\"\n\n\tlog \"github.com/sirupsen/logrus\"\n)\n\nfunc loadStatsd(conf configuration) (*statsd.Client, error) {\n\tstatsdClient, err := statsd.NewBuffered(conf.Statsd.Addr, conf.Statsd.Buflen)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error constructing statsdClient: %w\", err)\n\t}\n\tstatsdClient.Namespace = conf.Statsd.Namespace\n\n\treturn statsdClient, nil\n}\n\n\n\nfunc (a *autographer) addStats(conf configuration) (err error) ", "output": "{\n\ta.stats, err = loadStatsd(conf)\n\tlog.Infof(\"Statsd enabled at %s with namespace %s\", conf.Statsd.Addr, conf.Statsd.Namespace)\n\treturn err\n}"} {"input": "package main\n\nimport \"fmt\"\n\n\n\nfunc main() {\n\tdata := string(\"ABC\")\n\tbyteArray := []byte(data)\n\n\tpermutation(byteArray, 0, len(byteArray)-1)\n}\n\nfunc permutation(data []byte, start, end int) ", "output": "{\n\tif start == end {\n\t\tfmt.Println(string(data))\n\t} else {\n\t\tfor i := start; i <= end; i++ {\n\t\t\tdata[start], data[i] = data[i], data[start]\n\t\t\tpermutation(data, start+1, end)\n\t\t\tdata[start], data[i] = data[i], data[start]\n\t\t}\n\t}\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\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\nfunc (c *Config) GetServerPort() (token string) {\n\treturn \"8080\"\n}\n\nfunc (c *Config) FindByKey(key string) (value string, err error) ", "output": "{\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}"} {"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\nfunc (this *Stream) Write(data []byte, n *int) (err error) {\n\t*n, err = this.stream.Write(data)\n\treturn err\n}\n\n\n\nfunc (this *Stream) Close(dummy int, nothing *int) error ", "output": "{\n\terr := this.stream.Close()\n\treturn err\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\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\n\n\nfunc TestValidateTemplateExists(t *testing.T) ", "output": "{\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}"} {"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\n\n\nfunc (s *IdxfileSuite) TestDecodeEncode(c *C) {\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}\n\nfunc (s *IdxfileSuite) TestEncode(c *C) ", "output": "{\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}"} {"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\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\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) Syslog(p pri.Priority, msg interface{}) error ", "output": "{\n\tt.LastPri = p\n\tt.LastMsg = msg\n\treturn t.triggerError()\n}"} {"input": "package travis\n\nimport (\n\tservices \"github.com/de1ux/prowler/services/v1\"\n\tvcs \"github.com/de1ux/prowler/vcs/v1\"\n)\n\n\n\ntype Client struct {\n\tconfig *Config\n}\n\nfunc (c *Client) GetStatusByPullRequest(pr *vcs.PullRequest) (*services.Status, error) {\n\treturn nil, nil\n}\n\nfunc NewClient(config *Config) services.Client ", "output": "{\n\treturn &Client{config: config}\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\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\n\n\nfunc (s *Vertex) BuildPath(qs graph.QuadStore, ns *voc.Namespaces) (*path.Path, error) ", "output": "{\n\treturn path.StartPath(qs, linkedql.AbsoluteValues(s.Values, ns)...), nil\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\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.Len += n\n\t}\n\treturn n, err\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\nfunc (a *adler32Hash) Sum32() uint32 {\n\treturn uint32(a.adler)\n}\n\n\n\n\n\n\n\n\n\nfunc Adler32Combine(adler1, adler2 uint32, len2 int) uint32 ", "output": "{\n\treturn uint32(C.adler32_combine(C.uLong(adler1), C.uLong(adler2), C.z_off_t(len2)))\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\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\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 *ConstantIntegerInfo) Value() int32 ", "output": "{\n\treturn self.val\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\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 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\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) HTTPRequest(method, path string, binaryRequestBody *common.OCIReadSeekCloser) (http.Request, error) ", "output": "{\n\n\treturn common.MakeDefaultHTTPRequestWithTaggedStruct(method, path, request)\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\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 (self *ClassReader) readUint8() uint8 ", "output": "{\n\tval := self.data[0]\n\tself.data = self.data[1:]\n\treturn val\n}"} {"input": "package c\n\nimport (\n\t\"a\"\n\t\"b\"\n)\n\ntype BI interface {\n\tSomething(s int64) int64\n\tAnother(pxp a.G) int32\n}\n\n\n\nfunc BRS(sd *b.ServiceDesc, server BI, xyz int) *b.Service ", "output": "{\n\treturn b.RS(sd, server, 7)\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\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\nfunc (c *TableClient) UpdateTable(ctx context.Context, current, expected chunk.TableDesc) error {\n\treturn nil\n}\n\nfunc (*TableClient) Stop() {}\n\nfunc (c *TableClient) ListTables(ctx context.Context) ([]string, error) ", "output": "{\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}"} {"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\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 New(c rest.Interface) *EventsV1beta1Client ", "output": "{\n\treturn &EventsV1beta1Client{c}\n}"} {"input": "package lexer\n\nimport (\n\t\"strings\"\n\t\"testing\"\n)\n\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\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 EqualSentences(a, 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 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\nfunc (c *listKeysCommand) Info() *cmd.Info {\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}\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\n\n\nfunc (c *listKeysCommand) Run(context *cmd.Context) error ", "output": "{\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}"} {"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\nfunc (s Status) String() string {\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}\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\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 (p *Printer) SetStatus(status Status) ", "output": "{\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}"} {"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\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 Min(col Columnar) ColumnElem ", "output": "{\n\treturn Function(MIN, col)\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\nfunc (ua *UnsubackPacket) Type() byte {\n\treturn ua.FixedHeader.MessageType\n}\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) String() string ", "output": "{\n\tstr := fmt.Sprintf(\"%s\\n\", ua.FixedHeader)\n\tstr += fmt.Sprintf(\"MessageID: %d\", ua.MessageID)\n\treturn str\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\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\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 (d *dialer) Dial(netw, addr string) (net.Conn, error) ", "output": "{\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}"} {"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\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\n\n\nfunc (df DomainFilter) IsConfigured() bool ", "output": "{\n\tif len(df.filters) == 1 {\n\t\treturn df.filters[0] != \"\"\n\t}\n\treturn len(df.filters) > 0\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\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) SetupK8sDockerRegistry(setupData *K8sDockerRegistryData) bool ", "output": "{\n\tdata.K8sDockerRegistryData = setupData\n\treturn true\n}"} {"input": "package execdrivers\n\nimport (\n\t\"path\"\n\n\t\"github.com/docker/docker/daemon/execdriver\"\n\t\"github.com/docker/docker/daemon/execdriver/native\"\n\t\"github.com/docker/docker/pkg/sysinfo\"\n)\n\n\n\n\nfunc NewDriver(options []string, root, libPath, initPath string, sysInfo *sysinfo.SysInfo) (execdriver.Driver, error) ", "output": "{\n\treturn native.NewDriver(path.Join(root, \"execdriver\", \"native\"), initPath, options)\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\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 keyExistsIface(m *map[string]interface{}, key string) bool ", "output": "{\n\t_, ok := (*m)[key]\n\treturn ok\n}"} {"input": "package http\n\nimport (\n\tgohttp \"net/http\"\n\t\"time\"\n)\n\n\n\nfunc MakeBackendHttpClient(timeout time.Duration) *gohttp.Client ", "output": "{\n\treturn &gohttp.Client{\n\t\tTimeout: time.Duration(timeout),\n\t\tTransport: &gohttp.Transport{\n\t\t\tDisableKeepAlives: true,\n\t\t},\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\n\n\n\nfunc SSEHandler(w http.ResponseWriter, r *http.Request) {\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}\n\nfunc (sse *serverSentEventsConnection) Send(data []byte) (err error) ", "output": "{\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}"} {"input": "package filesystem\n\nimport (\n\t\"gopkg.in/src-d/go-git.v4/plumbing/cache\"\n\t\"gopkg.in/src-d/go-git.v4/storage\"\n\t\"gopkg.in/src-d/go-git.v4/storage/filesystem/dotgit\"\n)\n\ntype ModuleStorage struct {\n\tdir *dotgit.DotGit\n}\n\n\n\nfunc (s *ModuleStorage) Module(name string) (storage.Storer, error) ", "output": "{\n\tfs, err := s.dir.Module(name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn NewStorage(fs, cache.NewObjectLRUDefault()), nil\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\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) ValidateWithPath(path string) error ", "output": "{\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}"} {"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\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\n\n\nfunc (s ByLen) Swap(i, j int) ", "output": "{ s[i], s[j] = s[j], s[i] }"} {"input": "package test\n\nimport (\n\t\"github.com/borgstrom/reeve/modules\"\n)\n\n\n\nfunc Ping(in modules.Args, out modules.Args) error {\n\tout[\"reply\"] = \"pong\"\n\treturn nil\n}\n\nfunc init() ", "output": "{\n\tmodules.Register(\"test\", modules.Functions{\n\t\t\"ping\": Ping,\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\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\n\n\nfunc (mr *MockMathMockRecorder) Sum(arg0, arg1 interface{}) *gomock.Call ", "output": "{\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Sum\", reflect.TypeOf((*MockMath)(nil).Sum), arg0, arg1)\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\n\n\nfunc getC() Client {\n\treturn Client{stripe.GetBackend(stripe.APIBackend), stripe.Key}\n}\n\nfunc (i *Iter) BalanceTransaction() *stripe.BalanceTransaction ", "output": "{\n\treturn i.Current().(*stripe.BalanceTransaction)\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\nfunc TestAgeDefaultsToInfinite(t *testing.T) {\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}\n\n\n\n\nfunc TestSetConnectionAgeCommandlineOptions(t *testing.T) ", "output": "{\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}"} {"input": "package datastore\n\nimport \"testing\"\n\n\n\nfunc TestHasher(t *testing.T) ", "output": "{\n\n\ttestData := []struct {\n\t\tn string\n\t\td string\n\t}{\n\t\t{n: \"ZZ8FaUwURAkWvzbnRhTt2pWSJCYZMAELqPk9USTUJgC4\", d: \"\"},\n\t\t{n: \"Uy3RfJCyen9FrvTvpZCpnBLWJiBbkidTTHNcpo1PdYHD\", d: \"test\"},\n\t}\n\n\tfor _, d := range testData {\n\n\t\th := newHasher()\n\t\th.Write([]byte(d.d))\n\t\tn := h.Name()\n\t\tif n != d.n {\n\t\t\tt.Errorf(\"Invalid hashed name, got %s, expected %s\", n, d.n)\n\t\t}\n\t}\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\nfunc (h *basicHandler) Handle(argv ...string) (string, error) {\n\treturn h.handler(argv...)\n}\n\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) Help(argv ...string) string ", "output": "{\n\treturn h.help(argv...)\n}"} {"input": "package pop_test\n\nimport (\n\t\"testing\"\n\n\t\"github.com/gobuffalo/pop\"\n\t\"github.com/stretchr/testify/require\"\n)\n\nfunc Test_LoadsConnectionsFromConfig(t *testing.T) {\n\tr := require.New(t)\n\n\tconns := pop.Connections\n\tr.Equal(5, len(conns))\n}\n\n\n\nfunc Test_AddLookupPaths(t *testing.T) ", "output": "{\n\tr := require.New(t)\n\tpop.AddLookupPaths(\"./foo\")\n\tr.Contains(pop.LookupPaths(), \"./foo\")\n}"} {"input": "package monitor\n\nimport (\n\t\"sort\"\n\n\t\"github.com/spf13/pflag\"\n\n\tmonitorAPI \"github.com/cilium/cilium/pkg/monitor/api\"\n)\n\nvar _ pflag.Value = &monitorAPI.MessageTypeFilter{}\n\n\n\n\nfunc GetAllTypes() []string ", "output": "{\n\ttypes := make([]string, len(monitorAPI.MessageTypeNames))\n\ti := 0\n\tfor k := range monitorAPI.MessageTypeNames {\n\t\ttypes[i] = k\n\t\ti++\n\t}\n\tsort.Strings(types)\n\treturn types\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\nfunc read(n int) {\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}\n\n\n\nfunc write(n int) ", "output": "{\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}"} {"input": "package intsort\n\ntype Uints []uint\n\n\n\nfunc (s Uints) Less(i int, j int) bool {\n\treturn s[i] < s[j]\n}\n\nfunc (s Uints) Swap(i int, j int) {\n\ts[i], s[j] = s[j], s[i]\n}\n\nfunc (s Uints) Len() int ", "output": "{\n\treturn len(s)\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\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\n\n\nfunc ReadOpen(path string) (*os.File, error) ", "output": "{\n\n\tflag := os.O_RDONLY\n\tvar perm os.FileMode = 0\n\n\treturn os.OpenFile(path, flag, perm)\n}"} {"input": "package os\n\nimport (\n\t\"io\"\n\t\"runtime\"\n\t\"syscall\"\n)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nfunc RemoveAll(path string) error {\n\terr := Remove(path)\n\tif err == nil || IsNotExist(err) {\n\t\treturn nil\n\t}\n\n\tdir, serr := Lstat(path)\n\tif serr != nil {\n\t\tif serr, ok := serr.(*PathError); ok && (IsNotExist(serr.Err) || serr.Err == syscall.ENOTDIR) {\n\t\t\treturn nil\n\t\t}\n\t\treturn serr\n\t}\n\tif !dir.IsDir() {\n\t\treturn err\n\t}\n\n\tfd, err := Open(path)\n\tif err != nil {\n\t\tif IsNotExist(err) {\n\t\t\treturn nil\n\t\t}\n\t\treturn err\n\t}\n\n\terr = nil\n\tfor {\n\t\tif err == nil && (runtime.GOOS == \"plan9\" || runtime.GOOS == \"nacl\") {\n\t\t\tfd.Seek(0, 0)\n\t\t}\n\t\tnames, err1 := fd.Readdirnames(100)\n\t\tfor _, name := range names {\n\t\t\terr1 := RemoveAll(path + string(PathSeparator) + name)\n\t\t\tif err == nil {\n\t\t\t\terr = err1\n\t\t\t}\n\t\t}\n\t\tif err1 == io.EOF {\n\t\t\tbreak\n\t\t}\n\t\tif err == nil {\n\t\t\terr = err1\n\t\t}\n\t\tif len(names) == 0 {\n\t\t\tbreak\n\t\t}\n\t}\n\n\tfd.Close()\n\n\terr1 := Remove(path)\n\tif err1 == nil || IsNotExist(err1) {\n\t\treturn nil\n\t}\n\tif err == nil {\n\t\terr = err1\n\t}\n\treturn err\n}\n\nfunc MkdirAll(path string, perm FileMode) error ", "output": "{\n\tdir, err := Stat(path)\n\tif err == nil {\n\t\tif dir.IsDir() {\n\t\t\treturn nil\n\t\t}\n\t\treturn &PathError{\"mkdir\", path, syscall.ENOTDIR}\n\t}\n\n\ti := len(path)\n\tfor i > 0 && IsPathSeparator(path[i-1]) { \n\t\ti--\n\t}\n\n\tj := i\n\tfor j > 0 && !IsPathSeparator(path[j-1]) { \n\t\tj--\n\t}\n\n\tif j > 1 {\n\t\terr = MkdirAll(fixRootDirectory(path[:j-1]), perm)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\terr = Mkdir(path, perm)\n\tif err != nil {\n\t\tdir, err1 := Lstat(path)\n\t\tif err1 == nil && dir.IsDir() {\n\t\t\treturn nil\n\t\t}\n\t\treturn err\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}\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\n\n\nfunc tracking_notifyFault(err error){\n syscomponents.SetError(trackerObj.Name(), err)\n}\n\nfunc trackingSetup()", "output": "{\n trackerObj = DatabaseComponent{}\n syscomponents.Register(&trackerObj)\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\n\n\nfunc TestToIdentRef(t *testing.T) {\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}\n\nfunc TestCoerseValue(t *testing.T) ", "output": "{\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}"} {"input": "package http\n\nimport (\n\t\"net/http\"\n\n\t\"go-common/library/log\"\n\tbm \"go-common/library/net/http/blademaster\"\n)\n\n\n\n\nfunc ping(c *bm.Context) ", "output": "{\n\tvar err error\n\tif err = assSvc.Ping(c); err != nil {\n\t\tlog.Error(\"assist-service ping error(%v)\", err)\n\t\tc.AbortWithStatus(http.StatusServiceUnavailable)\n\t}\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\nfunc (enc Encoder) Encode(n int32) error {\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}\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\n\n\nfunc (dec Decoder) Decode() (n int32, err error) ", "output": "{\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}"} {"input": "package wait\n\nimport (\n\t\"fmt\"\n\t\"time\"\n)\n\n\n\n\n\n\n\n\n\n\n\nfunc NoError(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 := Predicate(pred, timeout); err != nil {\n\t\treturn predErr\n\t}\n\n\treturn nil\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 Predicate(pred func() bool, timeout time.Duration) error ", "output": "{\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}"} {"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\nfunc Register() {\n\tglobalLock.Lock()\n\tdefer globalLock.Unlock()\n\tregister()\n}\n\n\n\nfunc register() ", "output": "{\n\tprotolog.SetLogger(protolog.NewLogger(NewPusher(globalPusherOptions), globalLoggerOptions))\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\n\n\n\nfunc (n *node) Codec() codec.EncodeDecoder {\n\treturn n.s.codec\n}\n\nfunc (n *node) Bucket() []string ", "output": "{\n\treturn n.rootBucket\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"strings\"\n)\n\n\n\nfunc TestCurrentDir() error ", "output": "{\n\tfiles, err := ioutil.ReadDir(\".\")\n\tif err != nil {\n\t\treturn err\n\t}\n\tvar out []string\n\tfor _, f := range files {\n\t\tout = append(out, f.Name())\n\t}\n\n\tfmt.Println(strings.Join(out, \", \"))\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\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 MockKernelFeatures(f func() []string) (resture func()) ", "output": "{\n\told := kernelFeatures\n\tkernelFeatures = f\n\treturn func() {\n\t\tkernelFeatures = old\n\t}\n}"} {"input": "package v1beta1\n\n\n\ntype IngressRuleValueApplyConfiguration struct {\n\tHTTP *HTTPIngressRuleValueApplyConfiguration `json:\"http,omitempty\"`\n}\n\n\n\n\n\n\n\n\nfunc (b *IngressRuleValueApplyConfiguration) WithHTTP(value *HTTPIngressRuleValueApplyConfiguration) *IngressRuleValueApplyConfiguration {\n\tb.HTTP = value\n\treturn b\n}\n\nfunc IngressRuleValue() *IngressRuleValueApplyConfiguration ", "output": "{\n\treturn &IngressRuleValueApplyConfiguration{}\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\nfunc (this *SimpleMsg) FromBytes(buf []byte) *SimpleMsg {\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}\n\n\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) FromString(fromId int, toId int, msg string) *SimpleMsg ", "output": "{\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}"} {"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\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\nfunc checkPrivileges() bool {\n\n\tif user, err := user.Current(); err == nil && user.Gid == \"0\" {\n\t\treturn true\n\t}\n\treturn false\n}\n\nfunc IsExecutable(path string) (bool, error) ", "output": "{\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}"} {"input": "package utils\n\nimport (\n\t\"net\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\nfunc TestGetLocalIP(t *testing.T) {\n\tip, _ := HostIP()\n\tassert.NotNil(t, ip, \"assert we have an ip\")\n}\n\nfunc TestParseIPToUint32(t *testing.T) {\n\ttests := []struct {\n\t\tin string\n\t\tout uint32\n\t\terr error\n\t}{\n\t\t{\"1.2.3.4\", 1<<24 | 2<<16 | 3<<8 | 4, nil},\n\t\t{\"127.0.0.1\", 127<<24 | 1, nil},\n\t\t{\"localhost\", 127<<24 | 1, nil},\n\t\t{\"127.xxx.0.1\", 0, nil},\n\t\t{\"\", 0, ErrEmptyIP},\n\t\t{\"hostname\", 0, ErrNotFourOctets},\n\t}\n\n\tfor _, test := range tests {\n\t\tintIP, err := ParseIPToUint32(test.in)\n\t\tif test.err != nil {\n\t\t\tassert.Equal(t, test.err, err)\n\t\t} else {\n\t\t\tassert.Equal(t, test.out, intIP)\n\t\t}\n\n\t}\n}\n\nfunc TestParsePort(t *testing.T) {\n\ttests := []struct {\n\t\tin string\n\t\tout uint16\n\t\terr bool\n\t}{\n\t\t{\"123\", 123, false},\n\t\t{\"77777\", 0, true}, \n\t\t{\"bad-wolf\", 0, true},\n\t}\n\tfor _, test := range tests {\n\t\tp, err := ParsePort(test.in)\n\t\tif test.err {\n\t\t\tassert.Error(t, err)\n\t\t} else {\n\t\t\tassert.Equal(t, test.out, p)\n\t\t}\n\t}\n}\n\n\n\nfunc TestPackIPAsUint32(t *testing.T) ", "output": "{\n\tipv6a := net.IP{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 255, 255, 1, 2, 3, 4}\n\tipv6b := net.ParseIP(\"2001:0db8:85a3:0000:0000:8a2e:0370:7334\")\n\tassert.NotNil(t, ipv6a)\n\n\ttests := []struct {\n\t\tin net.IP\n\t\tout uint32\n\t}{\n\t\t{net.IPv4(1, 2, 3, 4), 1<<24 | 2<<16 | 3<<8 | 4},\n\t\t{ipv6a, 1<<24 | 2<<16 | 3<<8 | 4}, \n\t\t{ipv6b, 0},\n\t}\n\tfor _, test := range tests {\n\t\tip := PackIPAsUint32(test.in)\n\t\tassert.Equal(t, test.out, ip)\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\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\n\n\nfunc (c ConfigUpdater) UpdateRuntimeConfig(boshCLI AuthenticatedCLIRunner, filepath string, opsFilepaths []string, name string) error ", "output": "{\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}"} {"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\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_1) Execute(frame *runtime.Frame) ", "output": "{\n\t_executeRef(frame, 1)\n}"} {"input": "package logrus\n\nimport (\n\t\"io\"\n\t\"os\"\n\n\t\"golang.org/x/crypto/ssh/terminal\"\n)\n\n\n\nfunc checkIfTerminal(w io.Writer) bool ", "output": "{\n\tswitch v := w.(type) {\n\tcase *os.File:\n\t\treturn terminal.IsTerminal(int(v.Fd()))\n\tdefault:\n\t\treturn false\n\t}\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\n\n\nfunc (self *CountPerTimeInterval32) String() string {\n\treturn fmt.Sprintf(\"%.3f\", self.CalculatedValue())\n}\n\nfunc (self *CountPerTimeInterval32) CalculatedValue() float64 ", "output": "{\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}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\n\tdo \"gopkg.in/godo.v2\"\n)\n\n\n\nfunc main() {\n\tdo.Godo(tasks)\n}\n\nfunc tasks(p *do.Project) ", "output": "{\n\tif pwd, err := os.Getwd(); err == nil {\n\t\tdo.Env = fmt.Sprintf(\"GOPATH=%s/vendor::$GOPATH\", pwd)\n\t}\n\n\tp.Task(\"server\", nil, func(c *do.Context) {\n\t\tc.Start(\"main.go ./config/page.yaml\", do.M{\"$in\": \"./\"})\n\t}).Src(\"**/*.go\")\n}"} {"input": "package godo_test\n\nimport (\n\t\"github.com/luan/godo/godo\"\n\t. \"github.com/onsi/ginkgo\"\n\t. \"github.com/onsi/gomega\"\n\t\"testing\"\n)\n\n\n\nfunc TestGodo(t *testing.T) ", "output": "{\n\tRegisterFailHandler(Fail)\n\tdbmap := godo.InitDb(\"test_tasks.bin\")\n\tdefer dbmap.Db.Close()\n\tRunSpecs(t, \"Godo Suite\")\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\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\n\n\nfunc init() {\n\tstrings.Index(\"\", \".\")\n}\n\nfunc (obj *NextHop) GetField(key string) (interface{}, error) ", "output": "{\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}"} {"input": "package dis\n\nfunc Rearrange(s string, k int) string {\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}\n\n\n\nfunc findValidMax(count []int, valid []int, idx int) int ", "output": "{\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}"} {"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\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\nfunc (t *SuiteSuite) VerifyMethodsWrongSignatureSkipped2() int {\n\tt.Fatalf(\"This should never run.\")\n\treturn 0\n}\n\nfunc (t *SuiteSuite) GetFileLine() ", "output": "{\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}"} {"input": "package operations\n\n\n\n\nimport (\n\t\"net/http\"\n\n\t\"github.com/go-openapi/runtime\"\n)\n\n\nconst GetAuthLoginFoundCode int = 302\n\n\ntype GetAuthLoginFound struct {\n}\n\n\nfunc NewGetAuthLoginFound() *GetAuthLoginFound {\n\n\treturn &GetAuthLoginFound{}\n}\n\n\n\n\nfunc (o *GetAuthLoginFound) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) ", "output": "{\n\n\trw.Header().Del(runtime.HeaderContentType) \n\n\trw.WriteHeader(302)\n}"} {"input": "package errors\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/antlr/antlr4/runtime/Go/antlr\" \n)\n\n\n\ntype ParserListener struct {\n\t*antlr.DefaultErrorListener\n\tCode string\n}\n\n\n\n\nfunc (p *ParserListener) SyntaxError(recognizer antlr.Recognizer, offendingSymbol interface{}, line, column int, msg string, e antlr.RecognitionException) ", "output": "{\n\tif e != nil && e.GetOffendingToken() != nil {\n\t\tpanic(NewTranspilationError(line, column, fmt.Errorf(\"parser error at %q: %s\", e.GetOffendingToken().GetText(), msg)))\n\t}\n\n\tpanic(NewTranspilationError(line, column, fmt.Errorf(\"parser error at %q: %s\", nextToken(p.Code, line, column), msg)))\n}"} {"input": "package vulnerabilityscanning\n\nimport (\n\t\"github.com/oracle/oci-go-sdk/v46/common\"\n)\n\n\ntype ExportHostAgentScanResultCsvDetails struct {\n\n\tCompartmentId *string `mandatory:\"true\" json:\"compartmentId\"`\n\n\tTimeStartedAfter *common.SDKTime `mandatory:\"true\" json:\"timeStartedAfter\"`\n\n\tTimeStartedBefore *common.SDKTime `mandatory:\"true\" json:\"timeStartedBefore\"`\n\n\tHighestProblemSeverity ScanResultProblemSeverityEnum `mandatory:\"false\" json:\"highestProblemSeverity,omitempty\"`\n\n\tInstanceId *string `mandatory:\"false\" json:\"instanceId\"`\n\n\tOperatingSystem *string `mandatory:\"false\" json:\"operatingSystem\"`\n}\n\n\n\nfunc (m ExportHostAgentScanResultCsvDetails) String() string ", "output": "{\n\treturn common.PointerString(m)\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}\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 DeserializeUserFrame(input string) *UserFrame ", "output": "{\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}"} {"input": "package main_test\n\nimport (\n\t\"testing\"\n\n\tmain \"github.com/influxdb/influxdb/cmd/influx\"\n)\n\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\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_CommandsExist(t *testing.T) ", "output": "{\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}"} {"input": "package cfn\n\nconst (\n\tCREATE_COMPLETE = \"CREATE_COMPLETE\"\n\tCREATE_FAILED = \"CREATE_FAILED\"\n\tCREATE_IN_PROGRESS = \"CREATE_IN_PROGRESS\"\n\tDELETE_COMPLETE = \"DELETE_COMPLETE\"\n\tDELETE_FAILED = \"DELETE_FAILED\"\n\tDELETE_IN_PROGRESS = \"DELETE_IN_PROGRESS\"\n\tROLLBACK_COMPLETE = \"ROLLBACK_COMPLETE\"\n\tROLLBACK_FAILED = \"ROLLBACK_FAILED\"\n\tROLLBACK_IN_PROGRESS = \"ROLLBACK_IN_PROGRESS\"\n\tUPDATE_COMPLETE = \"UPDATE_COMPLETE\"\n\tUPDATE_COMPLETE_CLEANUP_IN_PROGRESS = \"UPDATE_COMPLETE_CLEANUP_IN_PROGRESS\"\n\tUPDATE_IN_PROGRESS = \"UPDATE_IN_PROGRESS\"\n\tUPDATE_ROLLBACK_COMPLETE = \"UPDATE_ROLLBACK_COMPLETE\"\n\tUPDATE_ROLLBACK_COMPLETE_CLEANUP_IN_PROGRESS = \"UPDATE_ROLLBACK_COMPLETE_CLEANUP_IN_PROGRESS\"\n\tUPDATE_ROLLBACK_FAILED = \"UPDATE_ROLLBACK_FAILED\"\n\tUPDATE_ROLLBACK_IN_PROGRESS = \"UPDATE_ROLLBACK_IN_PROGRESS\"\n)\n\n\n\n\n\n\n\nfunc CheckHotswapStatus(status string) bool {\n\tswitch status {\n\tcase CREATE_COMPLETE,\n\t\tUPDATE_COMPLETE,\n\t\tUPDATE_COMPLETE_CLEANUP_IN_PROGRESS,\n\t\tUPDATE_IN_PROGRESS,\n\t\tUPDATE_ROLLBACK_COMPLETE,\n\t\tUPDATE_ROLLBACK_COMPLETE_CLEANUP_IN_PROGRESS,\n\t\tUPDATE_ROLLBACK_FAILED,\n\t\tUPDATE_ROLLBACK_IN_PROGRESS:\n\t\treturn true\n\tdefault:\n\t\treturn false\n\t}\n}\n\nfunc AnyStatus(status string) bool {\n\treturn true\n}\n\nfunc PrunableStatus(status string) bool ", "output": "{\n\tswitch status {\n\tcase CREATE_COMPLETE,\n\t\tCREATE_FAILED,\n\t\tROLLBACK_COMPLETE,\n\t\tROLLBACK_FAILED,\n\t\tROLLBACK_IN_PROGRESS,\n\t\tUPDATE_COMPLETE,\n\t\tUPDATE_COMPLETE_CLEANUP_IN_PROGRESS,\n\t\tUPDATE_IN_PROGRESS,\n\t\tUPDATE_ROLLBACK_COMPLETE,\n\t\tUPDATE_ROLLBACK_COMPLETE_CLEANUP_IN_PROGRESS,\n\t\tUPDATE_ROLLBACK_FAILED,\n\t\tUPDATE_ROLLBACK_IN_PROGRESS:\n\t\treturn true\n\tdefault:\n\t\treturn false\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\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\nfunc (o *IAMInstanceProfile) String() string {\n\treturn fi.TaskAsString(o)\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 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\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) errorMessage() string ", "output": "{\n\treturn C.GoString(C.aug_error_message(a.handle))\n}"} {"input": "package openstack\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 TestAccDNSV2Zone_importBasic(t *testing.T) ", "output": "{\n\tvar zoneName = fmt.Sprintf(\"ACPTTEST%s.com.\", acctest.RandString(5))\n\tresourceName := \"openstack_dns_zone_v2.zone_1\"\n\n\tresource.Test(t, resource.TestCase{\n\t\tPreCheck: func() { testAccPreCheckDNSZoneV2(t) },\n\t\tProviders: testAccProviders,\n\t\tCheckDestroy: testAccCheckDNSV2ZoneDestroy,\n\t\tSteps: []resource.TestStep{\n\t\t\tresource.TestStep{\n\t\t\t\tConfig: testAccDNSV2Zone_basic(zoneName),\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 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\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 GetContainerStatus(statuses []ContainerStatus, name string) (ContainerStatus, bool) ", "output": "{\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}"} {"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\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) String() string ", "output": "{\n\ttype X *sampleState\n\tx := X(state)\n\treturn fmt.Sprintf(\"%+v\", x)\n}"} {"input": "package iso20022\n\n\ntype AllegementStatus3Choice struct {\n\n\tCode *AllegementStatus1Code `xml:\"Cd\"`\n\n\tProprietary *GenericIdentification30 `xml:\"Prtry\"`\n}\n\n\n\nfunc (a *AllegementStatus3Choice) AddProprietary() *GenericIdentification30 {\n\ta.Proprietary = new(GenericIdentification30)\n\treturn a.Proprietary\n}\n\nfunc (a *AllegementStatus3Choice) SetCode(value string) ", "output": "{\n\ta.Code = (*AllegementStatus1Code)(&value)\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\nfunc (b NDPNeighborSolicit) SetTargetAddress(addr tcpip.Address) {\n\tcopy(b[ndpNSTargetAddessOffset:][:IPv6AddressSize], addr)\n}\n\n\n\n\nfunc (b NDPNeighborSolicit) Options() NDPOptions ", "output": "{\n\treturn NDPOptions(b[ndpNSOptionsOffset:])\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\n\n\nfunc (s *TableServer) OnMessage(c *shttp.WSAsyncClient, msg shttp.WSMessage) {\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}\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) OnTableQuery(c *shttp.WSAsyncClient, msg shttp.WSMessage) ", "output": "{\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}"} {"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\nfunc getTelegramChatID(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\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}\n\n\n\nfunc getTelegramAuthCode(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\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}"} {"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\tv1alpha1 \"knative.dev/eventing-kafka-broker/control-plane/pkg/apis/eventing/v1alpha1\"\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(\"kafkasinks\"):\n\t\treturn &genericInformer{resource: resource.GroupResource(), informer: f.Eventing().V1alpha1().KafkaSinks().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 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\n\n\nfunc init() {\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}\n\nfunc (h *svgHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) ", "output": "{\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}"} {"input": "package client\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"net\"\n\t\"os\"\n)\n\n\n\nfunc handleError(err error) {\n\tif err != nil {\n\t\tlog.Println(\"error while bootstrapping. abort. %s\\n\", err)\n\t\tos.Exit(1)\n\t}\n}\n\nfunc Client(hostPort string) ", "output": "{\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}"} {"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\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\nfunc Backend() *backend {\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}\n\ntype backend struct {\n\t*framework.Backend\n\n\tMap *framework.PolicyMap\n}\n\nfunc Factory(conf *logical.BackendConfig) (logical.Backend, error) ", "output": "{\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}"} {"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\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\nfunc (z *ZZ) Inverse() *ZZ {\n\tz.g.ModInverse(z.g, z.modulo)\n\treturn z\n}\n\nfunc (z *ZZ) Bytes() []byte ", "output": "{\n\treturn z.g.Bytes()\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\nfunc (s Samples) Swap(i, j int) {\n\ts[i], s[j] = s[j], s[i]\n}\n\n\n\n\nfunc (s Samples) Equal(o Samples) bool ", "output": "{\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}"} {"input": "package models\n\nimport (\n\t\"net/http\"\n\t\"errors\"\n\t\"time\"\n\t\"fmt\"\n\n\t\"github.com/NyaaPantsu/nyaa/config\"\n\t\"github.com/NyaaPantsu/nyaa/utils/cache\"\n\t\"github.com/NyaaPantsu/nyaa/utils/log\"\n\t\"github.com/fatih/structs\"\n)\n\n\ntype Scrape struct {\n\tTorrentID uint `gorm:\"column:torrent_id;primary_key\"`\n\tSeeders uint32 `gorm:\"column:seeders\"`\n\tLeechers uint32 `gorm:\"column:leechers\"`\n\tCompleted uint32 `gorm:\"column:completed\"`\n\tLastScrape time.Time `gorm:\"column:last_scrape\"`\n}\n\n\nfunc (t Scrape) TableName() string {\n\treturn config.Get().Models.ScrapeTableName\n}\n\n\nfunc (s *Scrape) Update(unscope bool) (int, error) {\n\tdb := ORM\n\tif unscope {\n\t\tdb = ORM.Unscoped()\n\t}\n\n\tif db.Model(s).UpdateColumn(s.toMap()).Error != nil {\n\t\treturn http.StatusInternalServerError, errors.New(\"Scrape data was not updated\")\n\t}\n\n\tcache.C.Delete(s.Identifier())\n\n\treturn http.StatusOK, nil\n}\n\n\n\nfunc (s *Scrape) toMap() map[string]interface{} {\n\treturn structs.Map(s)\n}\n\n\nfunc (s *Scrape) Identifier() string {\n\treturn fmt.Sprintf(\"torrent_%d\", s.TorrentID)\n}\n\n\n\n\nfunc (s *Scrape) Create(torrentid uint, seeders uint32, leechers uint32, completed uint32, lastscrape time.Time) (*Scrape) ", "output": "{\n\tScrapeData := Scrape{\n\t\tTorrentID: torrentid,\n\t\tSeeders: \tseeders,\n\t\tLeechers: \tleechers,\n\t\tCompleted: completed,\n\t\tLastScrape: lastscrape}\n\n\terr := ORM.Create(&ScrapeData).Error\n\tlog.Infof(\"Scrape data ID %d created!\\n\", ScrapeData.TorrentID)\n\tif err != nil {\n\t\tlog.CheckErrorWithMessage(err, \"ERROR_SCRAPE_CREATE: Cannot create a scrape data\")\n\t}\n\n\tScrapeData.Update(false)\n\n\treturn &ScrapeData\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\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) Open() (*sqlx.DB, error) ", "output": "{\n\treturn sqlx.Open(\"mysql\", c.DSN())\n}"} {"input": "package elastic\n\nimport (\n\t\"encoding/json\"\n\t\"testing\"\n)\n\nfunc TestMatrixStatsAggregation(t *testing.T) {\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}\n\n\n\nfunc TestMatrixStatsAggregationWithMetaData(t *testing.T) ", "output": "{\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}"} {"input": "package main\n\nimport (\n\t\"log\"\n\t\"net\"\n\n\t\"golang.org/x/net/context\"\n\t\"google.golang.org/grpc\"\n\tpb \"google.golang.org/grpc/examples/helloworld/helloworld\"\n\t\"google.golang.org/grpc/reflection\"\n)\n\nconst (\n\tport = \":50051\"\n)\n\n\ntype server struct{}\n\n\n\n\nfunc main() {\n\tlis, err := net.Listen(\"tcp\", port)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to listen: %v\", err)\n\t}\n\ts := grpc.NewServer()\n\tpb.RegisterGreeterServer(s, &server{})\n\treflection.Register(s)\n\tif err := s.Serve(lis); err != nil {\n\t\tlog.Fatalf(\"failed to serve: %v\", err)\n\t}\n}\n\nfunc (s *server) SayHello(ctx context.Context, in *pb.HelloRequest) (*pb.HelloReply, error) ", "output": "{\n\treturn &pb.HelloReply{Message: \"Hello \" + in.Name}, 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\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\n\n\n\nfunc (t *Test) SetInterval(interval int) {\n\tt.interval = interval\n}\n\nfunc (t Test) String() string ", "output": "{\n\treturn t.Name() + \"Collector\"\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n)\n\n\n\nfunc main() {\n\tvar target string\n\tfmt.Scan(&target)\n\twords := make([]string, 0, 100)\n\tfor {\n\t\tvar w string\n\t\tif _, err := fmt.Scan(&w); err != nil {\n\t\t\tbreak\n\t\t}\n\t\twords = append(words, w)\n\t}\n\tans := Solve(target, words)\n\tfor i, w := range ans {\n\t\tif i > 0 {\n\t\t\tfmt.Print(\" \")\n\t\t}\n\t\tfmt.Print(w)\n\t}\n\tfmt.Println()\n}\n\nfunc Solve(target string, words []string) (ans []string) ", "output": "{\n\tfor _, w := range words {\n\t\tswitch {\n\t\tcase w == target:\n\t\t\tans = append(ans, \"[\"+w+\"]\")\n\t\tcase strings.Contains(w, target):\n\t\t\tans = append(ans, strings.Replace(w, target, \"=\"+target+\"=\", -1))\n\t\tdefault:\n\t\t\tans = append(ans, w)\n\t\t}\n\t}\n\treturn\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\n\n\n\nfunc (s *validatingWebhookConfigurationLister) List(selector labels.Selector) (ret []*admissionregistration.ValidatingWebhookConfiguration, err error) {\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}\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 NewValidatingWebhookConfigurationLister(indexer cache.Indexer) ValidatingWebhookConfigurationLister ", "output": "{\n\treturn &validatingWebhookConfigurationLister{indexer: indexer}\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\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) Height() uint64 ", "output": "{\n\treturn n.LedgerHeight\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\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) So(actual interface{},\n\tassert func(actual interface{}, expected ...interface{}) string, expected ...interface{}) ", "output": "{\n\tc.Lock()\n\tdefer c.Unlock()\n\tc.C.So(actual, assert, expected)\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\nfunc NewForConfig(c *restclient.Config) (*BatchClient, 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 &BatchClient{client}, nil\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\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 setConfigDefaults(config *restclient.Config) error ", "output": "{\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}"} {"input": "package plugins\n\nimport (\n\t\"github.com/hashicorp/terraform/plugin\"\n\t\"github.com/terraform-providers/terraform-provider-aws/aws\"\n)\n\n\n\nfunc init() ", "output": "{\n\texec := func() {\n\t\tplugin.Serve(&plugin.ServeOpts{\n\t\t\tProviderFunc: aws.Provider,\n\t\t})\n\t}\n\tKnownPlugins[\"terraform-provider-aws\"] = exec\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\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 newSQLTrace() *sqlTrace ", "output": "{\n\treturn &sqlTrace{\n\t\tLogger: log.New(os.Stdout, \"hdb \", log.Ldate|log.Ltime|log.Lshortfile),\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\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\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) String() string ", "output": "{\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}"} {"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\n\n\n\nfunc (n Network) EthernetCardBackingInfo(_ context.Context) (types.BaseVirtualDeviceBackingInfo, error) {\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}\n\nfunc NewNetwork(c *vim25.Client, ref types.ManagedObjectReference) *Network ", "output": "{\n\treturn &Network{\n\t\tCommon: NewCommon(c, ref),\n\t}\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\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\n\n\nfunc ExampleWriter_RegisterCompressor() ", "output": "{\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}"} {"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\n\n\nfunc checkArgs(args []string) {\n if len(args) < 2 {\n log.Fatal(\"Usage: cm-nextbus StopID\")\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 printResults(r Response) ", "output": "{\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}"} {"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\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) GetCurrent() (*User, error) ", "output": "{\n\tvar user = User{}\n\tvar err = s.run(\"GET\", \"/api/user\", nil, &user)\n\treturn &user, err\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 }\n\nfunc (r n) M9() int { return a.G9 }\nfunc (r n) M10() int { return a.G10 }\n\nfunc (r n) M8() int ", "output": "{ return a.G8 }"} {"input": "package gl\n\nimport (\n\t\"fmt\"\n\t\"github.com/tmacychen/UFG/framework\"\n\n\t\"github.com/goxjs/glfw\"\n)\n\n\n\nfunc getMouseState(w *glfw.Window) framework.MouseState {\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}\n\nfunc translateMouseButton(button glfw.MouseButton) framework.MouseButton ", "output": "{\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}"} {"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\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 getHomePath() (string, error) ", "output": "{\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}"} {"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\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\n\n\n\nfunc (response ResetDatabaseParametersResponse) HTTPResponse() *http.Response {\n\treturn response.RawResponse\n}\n\nfunc (response ResetDatabaseParametersResponse) String() string ", "output": "{\n\treturn common.PointerString(response)\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\nfunc getTweetKey(c context.Context) *datastore.Key {\n\treturn datastore.NewKey(c, tweetKey, tweetKeyID, 0, nil)\n}\n\n\n\n\nfunc LinkTweetFromDatastore(tweetID int64, c context.Context) *LinkTweet ", "output": "{\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}"} {"input": "package main\n\nimport \"fmt\"\n\n\n\nfunc main() {\n\ta, b := vals()\n\tfmt.Println(a)\n\tfmt.Println(b)\n\n\t_, c := vals()\n\tfmt.Println(c)\n}\n\nfunc vals() (int, int) ", "output": "{\n\treturn 3, 6\n}"} {"input": "package models\n\n\n\n\nimport (\n\t\"github.com/go-openapi/errors\"\n\t\"github.com/go-openapi/strfmt\"\n\t\"github.com/go-openapi/swag\"\n\t\"github.com/go-openapi/validate\"\n)\n\n\n\n\ntype DNSLookup struct {\n\n\tEndpointID int64 `json:\"endpoint-id,omitempty\"`\n\n\tExpirationTime strfmt.DateTime `json:\"expiration-time,omitempty\"`\n\n\tFqdn string `json:\"fqdn,omitempty\"`\n\n\tIps []string `json:\"ips\"`\n\n\tLookupTime strfmt.DateTime `json:\"lookup-time,omitempty\"`\n\n\tSource string `json:\"source,omitempty\"`\n\n\tTTL int64 `json:\"ttl,omitempty\"`\n}\n\n\n\n\nfunc (m *DNSLookup) validateExpirationTime(formats strfmt.Registry) error {\n\n\tif swag.IsZero(m.ExpirationTime) { \n\t\treturn nil\n\t}\n\n\tif err := validate.FormatOf(\"expiration-time\", \"body\", \"date-time\", m.ExpirationTime.String(), formats); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc (m *DNSLookup) validateLookupTime(formats strfmt.Registry) error {\n\n\tif swag.IsZero(m.LookupTime) { \n\t\treturn nil\n\t}\n\n\tif err := validate.FormatOf(\"lookup-time\", \"body\", \"date-time\", m.LookupTime.String(), formats); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\n\nfunc (m *DNSLookup) MarshalBinary() ([]byte, error) {\n\tif m == nil {\n\t\treturn nil, nil\n\t}\n\treturn swag.WriteJSON(m)\n}\n\n\nfunc (m *DNSLookup) UnmarshalBinary(b []byte) error {\n\tvar res DNSLookup\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 *DNSLookup) Validate(formats strfmt.Registry) error ", "output": "{\n\tvar res []error\n\n\tif err := m.validateExpirationTime(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateLookupTime(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/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\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\nfunc (response DeleteVolumeBackupPolicyResponse) HTTPResponse() *http.Response {\n\treturn response.RawResponse\n}\n\nfunc (request DeleteVolumeBackupPolicyRequest) String() string ", "output": "{\n\treturn common.PointerString(request)\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\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\nfunc (this *BasicConstraint) PostSolve() {\n\tif this.CallbackHandler != nil {\n\t\tthis.CallbackHandler.CollisionPostSolve(this)\n\t}\n}\n\nfunc NewConstraint(a, b *Body) BasicConstraint ", "output": "{\n\treturn BasicConstraint{BodyA: a, BodyB: b, MaxForce: Inf, MaxBias: Inf, ErrorBias: errorBias}\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\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\nfunc NewPluginReattachConfig(c *plugin.ReattachConfig) *PluginReattachConfig {\n\treturn &PluginReattachConfig{Pid: c.Pid, AddrNet: c.Addr.Network(), AddrName: c.Addr.String()}\n}\n\nfunc GetPluginMap(w io.Writer) map[string]plugin.Plugin ", "output": "{\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}"} {"input": "package google\n\nimport (\n\t\"fmt\"\n\t\"net/http\"\n\t\"os\"\n\n\t\"context\"\n\n\t\"github.com/otiai10/chant/server/middleware\"\n)\n\n\ntype Client struct {\n\tAPIKey string\n\tCustomSearchEngineID string\n\tReferer string\n\t*http.Client\n}\n\n\nfunc NewClient(ctx context.Context) (*Client, error) {\n\thttpclient := middleware.HTTPClient(ctx)\n\tkey := os.Getenv(\"GOOGLE_SEARCH_API_KEY\")\n\tif key == \"\" {\n\t\treturn nil, fmt.Errorf(\"Requiredd evn var `GOOGLE_SEARCH_API_KEY` is not set, please tell admin to add it to `app/secret.yaml`\")\n\t}\n\tengineID := os.Getenv(\"GOOGLE_SEARCH_ENGINE_ID\")\n\tif engineID == \"\" {\n\t\treturn nil, fmt.Errorf(\"Requiredd evn var `GOOGLE_SEARCH_ENGINE_ID` is not set, please tell admin to add it to `app/secret.yaml`\")\n\t}\n\treturn &Client{\n\t\tAPIKey: key,\n\t\tCustomSearchEngineID: engineID,\n\t\tClient: httpclient,\n\t}, nil\n}\n\n\n\n\nfunc (c *Client) Get(url string) (*http.Response, error) ", "output": "{\n\treq, err := http.NewRequest(\"GET\", url, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif c.Referer != \"\" {\n\t\treq.Header.Set(\"Referer\", c.Referer)\n\t}\n\treturn c.Do(req)\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\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\nfunc (gr *GR) Close() {\n\tgr.DB.Close()\n}\n\nfunc New(host, dbname, user, pass string, port uint16) error ", "output": "{\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}"} {"input": "package repo\n\nimport (\n\t\"fmt\"\n\t\"net/http\"\n\t\"strings\"\n\n\t\"code.gitea.io/gitea/models\"\n\t\"code.gitea.io/gitea/modules/context\"\n\t\"code.gitea.io/gitea/modules/log\"\n\t\"code.gitea.io/gitea/modules/setting\"\n)\n\n\n\n\nfunc UploadAttachment(ctx *context.Context) {\n\tif !setting.AttachmentEnabled {\n\t\tctx.Error(404, \"attachment is not enabled\")\n\t\treturn\n\t}\n\n\tfile, header, err := ctx.Req.FormFile(\"file\")\n\tif err != nil {\n\t\tctx.Error(500, fmt.Sprintf(\"FormFile: %v\", err))\n\t\treturn\n\t}\n\tdefer file.Close()\n\n\tbuf := make([]byte, 1024)\n\tn, _ := file.Read(buf)\n\tif n > 0 {\n\t\tbuf = buf[:n]\n\t}\n\tfileType := http.DetectContentType(buf)\n\n\tallowedTypes := strings.Split(setting.AttachmentAllowedTypes, \",\")\n\tallowed := false\n\tfor _, t := range allowedTypes {\n\t\tt := strings.Trim(t, \" \")\n\t\tif t == \"*/*\" || t == fileType {\n\t\t\tallowed = true\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif !allowed {\n\t\tlog.Info(\"Attachment with type %s blocked from upload\", fileType)\n\t\tctx.Error(400, ErrFileTypeForbidden.Error())\n\t\treturn\n\t}\n\n\tattach, err := models.NewAttachment(header.Filename, buf, file)\n\tif err != nil {\n\t\tctx.Error(500, fmt.Sprintf(\"NewAttachment: %v\", err))\n\t\treturn\n\t}\n\n\tlog.Trace(\"New attachment uploaded: %s\", attach.UUID)\n\tctx.JSON(200, map[string]string{\n\t\t\"uuid\": attach.UUID,\n\t})\n}\n\nfunc renderAttachmentSettings(ctx *context.Context) ", "output": "{\n\tctx.Data[\"RequireDropzone\"] = true\n\tctx.Data[\"IsAttachmentEnabled\"] = setting.AttachmentEnabled\n\tctx.Data[\"AttachmentAllowedTypes\"] = setting.AttachmentAllowedTypes\n\tctx.Data[\"AttachmentMaxSize\"] = setting.AttachmentMaxSize\n\tctx.Data[\"AttachmentMaxFiles\"] = setting.AttachmentMaxFiles\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\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 saveHandler(w http.ResponseWriter, r *http.Request) ", "output": "{\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}"} {"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\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) RewriteGetURL(u *url.URL, name string) (*url.URL, bool, error) ", "output": "{\n\treturn s.GetURL, s.OriginallySigned, nil\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\n\n\nfunc (b *buffer) Value() []interface{} {\n\treturn b.v\n}\n\nfunc (b *buffer) WriteValue(v ...interface{}) error ", "output": "{\n\tb.v = append(b.v, v...)\n\treturn nil\n}"} {"input": "package v1\n\nimport (\n\t\"fmt\"\n\t\"net/http\"\n\t\"net/url\"\n\t\"testing\"\n\n\t\"github.com/zhgwenming/vrouter/Godeps/_workspace/src/github.com/coreos/etcd/server\"\n\t\"github.com/coreos/etcd/tests\"\n\t\"github.com/coreos/etcd/third_party/github.com/stretchr/testify/assert\"\n)\n\n\n\n\n\n\n\n\nfunc TestV1DeleteKey(t *testing.T) ", "output": "{\n\ttests.RunServer(func(s *server.Server) {\n\t\tv := url.Values{}\n\t\tv.Set(\"value\", \"XXX\")\n\t\tresp, err := tests.PutForm(fmt.Sprintf(\"%s%s\", s.URL(), \"/v1/keys/foo/bar\"), v)\n\t\ttests.ReadBody(resp)\n\t\tresp, err = tests.DeleteForm(fmt.Sprintf(\"%s%s\", s.URL(), \"/v1/keys/foo/bar\"), url.Values{})\n\t\tassert.Equal(t, resp.StatusCode, http.StatusOK)\n\t\tbody := tests.ReadBody(resp)\n\t\tassert.Nil(t, err, \"\")\n\t\tassert.Equal(t, string(body), `{\"action\":\"delete\",\"key\":\"/foo/bar\",\"prevValue\":\"XXX\",\"index\":4}`, \"\")\n\t})\n}"} {"input": "package info\n\nimport (\n\t\"testing\"\n\n\t\"github.com/gobuffalo/genny/v2/gentest\"\n\t\"github.com/stretchr/testify/require\"\n)\n\n\n\nfunc Test_New(t *testing.T) ", "output": "{\n\tr := require.New(t)\n\n\tg, err := New(&Options{})\n\tr.NoError(err)\n\n\trun := gentest.NewRunner()\n\trun.With(g)\n\n\tr.NoError(run.Run())\n\n\tres := run.Results()\n\n\tr.Len(res.Commands, 0)\n\tr.Len(res.Files, 0)\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 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) {\n\treturn p.Paging,\n\t\tmvc.JsonOutputBody(\n\t\t\tdbOwl.ListGroupTags(p.Name, p.Paging),\n\t\t)\n}\n\n\n\nfunc getGroupTagById(\n\tp *struct {\n\t\tGroupTagId int32 `mvc:\"param[group_tag_id]\"`\n\t},\n) mvc.OutputBody ", "output": "{\n\treturn mvc.JsonOutputOrNotFound(\n\t\tdbOwl.GetGroupTagById(p.GroupTagId),\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) 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\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 decodeDefineProfileResponse(_ context.Context, r *http.Response) (interface{}, error) ", "output": "{\n\tvar resp defineProfileResponse\n\terr := httputil.DecodeJSONResponse(r, &resp)\n\treturn resp, err\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) }\nfunc (a ByIdentifier) Swap(i, j int) { a[i], a[j] = a[j], a[i] }\n\n\nfunc (a ByIdentifier) Less(i, j int) bool ", "output": "{ return a[i].Identifier < a[j].Identifier }"} {"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\n\n\nfunc NewDeleteCommand() *cobra.Command {\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}\n\nfunc deleteRun(c *cobra.Command, args []string) ", "output": "{\n\tc.Help()\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\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 parameterised(m matrix) interface{} ", "output": "{\n\tg, start, end := matrixToGraph(m)\n\treturn g.ShortestPath(start)[end]\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\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 Get(key string) interface{} ", "output": "{\n\treturn settings.Get(key)\n}"} {"input": "package action\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n)\n\ntype aclInfo struct {\n\t*config\n}\n\n\n\nfunc (a *aclInfo) CommandFlags() *flag.FlagSet {\n\treturn a.newFlagSet(FLAG_OUTPUT, FLAG_CONSISTENCY, FLAG_BLOCKING)\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 AclInfoAction() Action ", "output": "{\n\treturn &aclInfo{\n\t\tconfig: &gConfig,\n\t}\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\nfunc (c *CardPaymentTransaction42) SetInterchangeData(value string) {\n\tc.InterchangeData = (*Max140Text)(&value)\n}\n\n\n\nfunc (c *CardPaymentTransaction42) AddTransactionDetails() *CardPaymentTransactionDetails22 ", "output": "{\n\tc.TransactionDetails = new(CardPaymentTransactionDetails22)\n\treturn c.TransactionDetails\n}"} {"input": "package s3afero\n\nimport (\n\t\"crypto/md5\"\n\t\"io\"\n\t\"path/filepath\"\n\n\t\"github.com/spf13/afero\"\n)\n\n\n\nfunc hashFile(fs afero.Fs, path string) (hash []byte, err error) ", "output": "{\n\tf, err := fs.Open(filepath.FromSlash(path))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer f.Close()\n\n\th := md5.New()\n\tio.Copy(h, f)\n\treturn h.Sum(nil), 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\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) CreateNetwork(id types.UUID, option map[string]interface{}) error ", "output": "{\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\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\nfunc strDefault(a, defaults string) string {\n\tif len(a) == 0 {\n\t\treturn defaults\n\t}\n\treturn a\n}\n\nfunc TestData(t *testing.T) ", "output": "{\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}"} {"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\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\nfunc AddParameterService(proxyPath, url, parameterName, clientSecret string) Service {\n\treturn addParameterService{proxyPath, url, parameterName, clientSecret}\n}\n\nfunc (s basicAuthService) ProxyPath() string ", "output": "{\n\treturn s.proxyPath\n}"} {"input": "package main\n\nimport \"fmt\"\n\n\n\n\n\n\n\n\nfunc main() {\n\tname := \"Diff 21\"\n\tfmt.Println(name, \"1:\", diff21(19))\n\tfmt.Println(name, \"2:\", diff21(10))\n\tfmt.Println(name, \"3:\", diff21(21))\n}\n\n\n\nfunc diff21(n int) int ", "output": "{\n\tif n > 21 {\n\t\treturn (n - 21) * 2\n\t}\n\n\treturn 21 - n\n}"} {"input": "package main\n\nimport (\n\t\"regexp\"\n\n\t\"github.com/gin-gonic/gin\"\n\t\"net/http\"\n)\n\n\n\n\n\nfunc ValidateEmail(email string) bool {\n\tRe := regexp.MustCompile(`^[a-z0-9._%+\\-]+@[a-z0-9.\\-]+\\.[a-z]{2,3}$`)\n\treturn Re.MatchString(email)\n}\n\nfunc EmailHandler(c *gin.Context) ", "output": "{\n\temail := c.Query(\"email\")\n\tif (ValidateEmail(email)) {\n\t\tc.JSON(http.StatusOK, gin.H{\"email\": email, \"valid\": true, \"message\": \"Email is Validated\"})\n\t\treturn\n\t}\n\tc.JSON(http.StatusOK, gin.H{\"email\": email, \"valid\": false, \"message\": \"Email address is Invalid\"})\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\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 Date() string ", "output": "{\n\treturn time.Now().Format(\"2006-01-02\")\n}"} {"input": "package sync\n\nimport (\n \"ghighlighter/models\"\n \"ghighlighter/readmill/readmillreadings\"\n \"ghighlighter/readmill/readmillhighlights\"\n)\n\nfunc Sync() {\n config := models.Config()\n\n syncHighlights(config.AccessToken)\n syncReadings(config.UserId, config.AccessToken)\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 syncHighlights(accessToken string) ", "output": "{\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}"} {"input": "package gocdn\n\nimport (\n \"io/ioutil\"\n \"os\"\n \"path\"\n \"log\"\n)\n\n\n\nfunc cacheFile(fileName string, data []byte) (err error)", "output": "{\n\n\tfileName = path.Clean(fileName)\n\tdir := path.Dir(fileName)\n\n\tif err = os.MkdirAll(dir, os.FileMode(0775)); err != nil {\n log.Printf(\"Could not create directory: %s\", dir)\n\t\treturn\n\t}\n\n\tif err = ioutil.WriteFile(fileName, data, 0644); err != nil {\n log.Printf(\"Could not write file: %s\", dir)\n\t\treturn\n\t}\n\n return\n\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\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\n\n\nfunc (h *ttlHeap) Pop() interface{} ", "output": "{\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}"} {"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\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 TestEventerDeleteEvent(t *testing.T) ", "output": "{\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}"} {"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\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\n\n\nfunc (m *Match) update(r rune, distance, weight int) Match ", "output": "{\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}"} {"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\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 handle(h http.Handler) http.Handler ", "output": "{\n\n\treturn benchmarkHandler{handlers.CombinedLoggingHandler(os.Stdout, h)}\n\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\n\n\n\nfunc (s *Setting) GetJson(value interface{}) error {\n\treturn json.Unmarshal([]byte(s.Value), value)\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) GetString() string ", "output": "{\n\treturn s.Value\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\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 getTestCephHost() string ", "output": "{\n\treturn fmt.Sprintf(\"%v:%v\",\n\t\tgetenv(\"CEPH_HOST\", cephDefaultHost),\n\t\tgetenv(\"CEPH_PORT\", cephDefaultPort),\n\t)\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\n\n\nfunc (q *DongPlugin) ProcessCommand(cmd *ircclient.IRCCommand) {\n\treturn\n}\n\nfunc (q *DongPlugin) ProcessLine(msg *ircclient.IRCMessage) ", "output": "{\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}"} {"input": "package table2rst\n\nimport (\n\t\"bufio\"\n\t\"fmt\"\n\t\"github.com/PuerkitoBio/goquery\"\n\t\"os\"\n\t\"strings\"\n)\n\nfunc StringToLines(s string) []string {\n\tvar lines []string\n\n\tscanner := bufio.NewScanner(strings.NewReader(s))\n\tfor scanner.Scan() {\n\t\tlines = append(lines, scanner.Text())\n\t}\n\n\tif err := scanner.Err(); err != nil {\n\t\tfmt.Fprintln(os.Stderr, \"reading standard input:\", err)\n\t}\n\n\treturn lines\n}\n\nfunc rstListTablePrefixOfEachLine(indexOfTd, indexOfLine int) string {\n\tif indexOfTd == 0 {\n\t\tif indexOfLine == 0 {\n\t\t\treturn \" * - \"\n\t\t} else {\n\t\t\treturn \" \"\n\t\t}\n\t} else {\n\t\tif indexOfLine == 0 {\n\t\t\treturn \" - \"\n\t\t} else {\n\t\t\treturn \" \"\n\t\t}\n\t}\n}\n\n\n\nfunc htmlTableToRst(url, outputFilePath string) {\n\tdoc, err := goquery.NewDocument(url)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tfRstOutput, err := os.Create(outputFilePath)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tdoc.Find(\"table\").Each(func(_ int, table *goquery.Selection) {\n\t\tfmt.Fprintf(fRstOutput, \".. list-table:: \\n\\n\")\n\t\ttable.Find(\"tr\").Each(func(_ int, tr *goquery.Selection) {\n\t\t\tprocessTr(tr, fRstOutput)\n\t\t})\n\t\tfmt.Fprintf(fRstOutput, \"\\n\\n\")\n\t\tfmt.Fprintf(fRstOutput, \"|\\n|\\n\\n\")\n\t})\n}\n\nfunc processTr(tr *goquery.Selection, fRstOutput *os.File) ", "output": "{\n\ttr.Find(\"td\").Each(func(indexOfTd int, td *goquery.Selection) {\n\t\tlines := StringToLines(td.Text())\n\t\tfor indexOfLine, line := range lines {\n\t\t\tline = strings.TrimSpace(line)\n\t\t\tfmt.Fprintf(fRstOutput, rstListTablePrefixOfEachLine(indexOfTd, indexOfLine))\n\t\t\tfmt.Fprintf(fRstOutput, line)\n\t\t\tfmt.Fprintf(fRstOutput, \"\\n\")\n\t\t}\n\t})\n}"} {"input": "package clang\n\n\n\nimport \"C\"\n\nimport (\n\t\"time\"\n)\n\n\ntype File struct {\n\tc C.CXFile\n}\n\n\nfunc (c File) Name() string {\n\tcstr := cxstring{C.clang_getFileName(c.c)}\n\tdefer cstr.Dispose()\n\treturn cstr.String()\n}\n\n\n\n\nfunc (c File) ModTime() time.Time ", "output": "{\n\tsec := C.clang_getFileTime(c.c)\n\tconst nsec = 0\n\treturn time.Unix(int64(sec), nsec)\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\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 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\n\n\nfunc SaveDb() error {\n\treturn database.Save(DB)\n}\n\nfunc LoadDb() error {\n\treturn database.Load(&DB, BuildDb)\n}\n\nfunc DeleteDbEntry(entry Entry) ", "output": "{\n\tdelete(DB, entry.ID)\n}"} {"input": "package routers\n\nimport (\n\t\"github.com/gorilla/mux\"\n)\n\n\n\n\nfunc Init() (r *mux.Router) ", "output": "{\n\tr = mux.NewRouter()\n\tr.HandleFunc(\"/\", HomeHandler)\n\tr.HandleFunc(\"/products\", ProductsHandler)\n\tr.HandleFunc(\"/articles\", ArticlesHandler)\n}"} {"input": "package git\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 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\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\n\n\nfunc (e SDKError) New(errorType string, errorCode string, errorMessage string) SDKError ", "output": "{\n\treturn SDKError{errorType, errorCode, errorMessage}\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\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 setConfigDefaults(config *rest.Config) error ", "output": "{\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}"} {"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\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\n\n\nfunc NewError(t ErrType, err error) *Error ", "output": "{\n\treturn &Error{\n\t\tt: t,\n\t\terr: err,\n\t}\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\nfunc (v4 IPv4) String() string {\n\treturn v4.IP().String()\n}\n\n\n\n\nfunc (v4 *IPv4) DeepCopyInto(out *IPv4) ", "output": "{\n\tcopy(out[:], v4[:])\n\treturn\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\nfunc initTwitter(conf Conf) {\n\tanaconda.SetConsumerKey(conf.Env[\"TWITTER_KEY\"])\n\tanaconda.SetConsumerSecret(conf.Env[\"TWITTER_SECRET\"])\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\n\n\nfunc tweetImage(text string, img image.Image, twitterAPI *anaconda.TwitterApi) (tweetResponse, error) ", "output": "{\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}"} {"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\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\nfunc (r *AWSOpsWorksStack_ElasticIp) SetDeletionPolicy(policy policies.DeletionPolicy) {\n\tr._deletionPolicy = policy\n}\n\nfunc (r *AWSOpsWorksStack_ElasticIp) AWSCloudFormationType() string ", "output": "{\n\treturn \"AWS::OpsWorks::Stack.ElasticIp\"\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\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\n\n\nfunc (this *DB) QueryData(sql string, args ...interface{}) *sql.Row ", "output": "{\n\treturn this.DataBase.QueryRow(sql, args...)\n\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\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\n\n\nfunc init() ", "output": "{\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}"} {"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\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) DeleteGlobalStaticIP(name string) error ", "output": "{\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}"} {"input": "package rules\n\nimport (\n\t\"go/ast\"\n\t\"go/token\"\n\n\t\"istio.io/tools/pkg/checker\"\n)\n\n\n\n\n\n\ntype SkipIssue struct {\n\tskipArgsRegex string \n}\n\n\n\n\n\nfunc (lr *SkipIssue) GetID() string {\n\treturn GetCallerFileName()\n}\n\n\n\n\n\n\n\n\nfunc (lr *SkipIssue) Check(aNode ast.Node, fs *token.FileSet, lrp *checker.Report) {\n\tif fn, isFn := aNode.(*ast.FuncDecl); isFn {\n\t\tfor _, bd := range fn.Body.List {\n\t\t\tif ok, _ := matchFunc(bd, \"t\", \"SkipNow\"); ok {\n\t\t\t\tlrp.AddItem(fs.Position(bd.Pos()), lr.GetID(), \"Only t.Skip() is allowed and t.Skip() should contain an url to GitHub issue.\")\n\t\t\t} else if ok, _ := matchFunc(bd, \"t\", \"Skipf\"); ok {\n\t\t\t\tlrp.AddItem(fs.Position(bd.Pos()), lr.GetID(), \"Only t.Skip() is allowed and t.Skip() should contain an url to GitHub issue.\")\n\t\t\t} else if ok, fcall := matchFunc(bd, \"t\", \"Skip\"); ok && !matchFuncArgs(fcall, lr.skipArgsRegex) {\n\t\t\t\tlrp.AddItem(fs.Position(bd.Pos()), lr.GetID(), \"Only t.Skip() is allowed and t.Skip() should contain an url to GitHub issue.\")\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc NewSkipByIssue() *SkipIssue ", "output": "{\n\treturn &SkipIssue{\n\t\tskipArgsRegex: `https:\\/\\/github\\.com\\/istio\\/istio\\/issues\\/[0-9]+`,\n\t}\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\nfunc indexHandler(c *gin.Context) {\n\tvars := gin.H{}\n\tc.HTML(200, \"index.html\", vars)\n}\n\n\n\n\nfunc apiHandler(c *gin.Context) ", "output": "{\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}"} {"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\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) Pop() int ", "output": "{\n\tn := len(this.elements)\n\te := this.elements[n-1]\n\tthis.elements = this.elements[:n-1]\n\treturn e\n}"} {"input": "package assertions\n\nimport (\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"os\"\n\t\"os/exec\"\n)\n\nfunc Diffb(a string, b string) []byte {\n\n\tdirpath := NewSimpleTempDir(\"diffdir_\")\n\tdefer os.RemoveAll(dirpath)\n\n\tfa := SimpleTempFile(dirpath)\n\tfmt.Fprintf(fa, \"%s\\n\", a)\n\tfa.Close()\n\n\tfb := SimpleTempFile(dirpath)\n\tfmt.Fprintf(fb, \"%s\\n\", b)\n\tfb.Close()\n\n\tco, err := exec.Command(\"diff\", \"-b\", fa.Name(), fb.Name()).CombinedOutput()\n\tif err != nil {\n\t}\n\treturn co\n}\n\nfunc NewSimpleTempDir(prefix string) string {\n\tdirpath, err := ioutil.TempDir(\".\", prefix)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn dirpath\n}\n\n\n\nfunc SimpleTempFile(dirpath string) *os.File ", "output": "{\n\n\tf, err := ioutil.TempFile(dirpath, \"diff_file_\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn f\n}"} {"input": "package spec\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"strings\"\n\n\t\"github.com/google/go-github/github\"\n\t\"github.com/pkg/errors\"\n\n\t\"github.com/nmiyake/ghcli/license\"\n\t\"github.com/nmiyake/ghcli/repository\"\n)\n\ntype licenseAnalyzer struct {\n\tclient *github.Client\n\tauthorName string\n\tcache license.Cache\n}\n\nfunc NewLicenseAnalyzer(client *github.Client, authorName string) Analyzer {\n\treturn &licenseAnalyzer{\n\t\tclient: client,\n\t\tauthorName: authorName,\n\t\tcache: license.NewCache(client),\n\t}\n}\n\nfunc (d *licenseAnalyzer) Name() string {\n\treturn \"license\"\n}\n\n\n\nfunc (d *licenseAnalyzer) CanFix() bool {\n\treturn d.client != nil && d.cache != nil\n}\n\nfunc (d *licenseAnalyzer) Fix(def repository.Definition, info repository.Info, stdout io.Writer) error {\n\tprParams := license.DefaultPRParams(\"\")\n\tprParams.Body = \"Fix license for repository to match specification.\"\n\tif err := license.ApplyStandard(d.client, info, strings.TrimPrefix(def.License, \"custom-\"), d.authorName, prParams, d.cache, stdout); err != nil {\n\t\treturn errors.Wrapf(err, \"failed to fix license\")\n\t}\n\treturn nil\n}\n\nfunc (d *licenseAnalyzer) Diff(def repository.Definition, info repository.Info) string ", "output": "{\n\tif def.License == \"custom\" {\n\t\treturn \"\"\n\t}\n\twantLicenseType := strings.TrimPrefix(def.License, \"custom-\")\n\tvar gotLicense string\n\tif info.License != nil && info.License.SPDXID != nil {\n\t\tgotLicense = *info.License.SPDXID\n\t}\n\tif wantLicenseType == \"\" && gotLicense == \"\" {\n\t\treturn \"\"\n\t}\n\tif wantLicenseType != gotLicense {\n\t\treturn stringDiff(\"license type\", wantLicenseType, gotLicense)\n\t}\n\tif _, err := license.VerifyRepositoryLicenseCorrect(info.RepoLicense, &info.Repository, d.authorName, d.cache); license.IsIncorrect(err) {\n\t\treturn joinDiff(fmt.Sprintf(\"%s content (%s)\", *info.RepoLicense.Path, *info.RepoLicense.License.Name), strings.Split(license.Diff(err), \"\\n\")...)\n\t}\n\treturn \"\"\n}"} {"input": "package caasapplication_test\n\nimport (\n\t\"testing\"\n\n\tgc \"gopkg.in/check.v1\"\n)\n\n\n\nfunc TestAll(t *testing.T) ", "output": "{\n\tgc.TestingT(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\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\n\n\nfunc (o *DeleteTaskParams) bindID(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\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}"} {"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\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) OnOk(cmd *winapi.CMD) ", "output": "{\n\tp.End(winapi.IDOK)\n}"} {"input": "package marid\n\ntype FuncSet struct {\n\tf map[string]interface{}\n}\n\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\nfunc (f *FuncSet) GetFuncs() map[string]interface{} {\n\treturn f.f\n}\n\nfunc NewFuncSet() *FuncSet ", "output": "{\n\treturn &FuncSet{make(map[string]interface{})}\n}"} {"input": "package utils\n\nimport (\n \"io/ioutil\"\n \"strconv\"\n \"syscall\"\n)\n\n\n\nfunc CloseExecFrom(minFd int) error ", "output": "{\n fdList, err := ioutil.ReadDir(\"/proc/self/fd\")\n if err != nil {\n return err\n }\n for _, fi := range fdList {\n fd, err := strconv.Atoi(fi.Name())\n if err != nil {\n \n continue\n }\n\n if fd < minFd {\n \n continue\n }\n\n \n syscall.CloseOnExec(fd)\n \n }\n return nil\n}"} {"input": "package main\n\nimport (\n\t\"sort\"\n\t\"testing\"\n)\n\n\n\nfunc TestChannelSort(t *testing.T) ", "output": "{\n\tchannels := Channels{\n\t\t&ChannelData{3, 0.0, 0.0, 0.0, 0.0, 0},\n\t\t&ChannelData{1, 0.0, 0.0, 0.0, 0.0, 0},\n\t\t&ChannelData{4, 0.0, 0.0, 0.0, 0.0, 0},\n\t\t&ChannelData{2, 0.0, 0.0, 0.0, 0.0, 0},\n\t}\n\n\tsort.Sort(channels)\n\n\tif channels[0].Number() != 1 {\n\t\tt.Errorf(\"Sort failed for ForwardSignal\")\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\nfunc Trace(v ...interface{}) { tracer.Print(v...) }\n\n\n\n\n\nfunc Traceln(v ...interface{}) { tracer.Println(v...) }\n\nfunc Tracef(format string, v ...interface{}) ", "output": "{ tracer.Printf(format, v...) }"} {"input": "package protocol\n\n\n\nfunc CreatePasswordMessage(password string) []byte ", "output": "{\n\tmessage := NewMessageBuffer([]byte{})\n\n\tmessage.WriteByte(PasswordMessageType)\n\n\tmessage.WriteInt32(0)\n\n\tmessage.WriteString(password)\n\n\tmessage.ResetLength(PGMessageLengthOffset)\n\n\treturn message.Bytes()\n}"} {"input": "package main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"os\"\n\n\tpb \"github.com/azmodb/exp/azmo/azmopb\"\n\t\"golang.org/x/net/context\"\n)\n\nvar delCmd = command{\n\tHelp: `\nDelete removes a key/value pair.\n`,\n\tShort: \"removes a key/value pair\",\n\tArgs: \"key\",\n\tRun: put,\n}\n\n\n\nfunc del(ctx context.Context, d *dialer, args []string) error ", "output": "{\n\tflags := flag.FlagSet{}\n\tflags.Usage = func() {\n\t\tfmt.Fprintf(os.Stderr, \"%s: delete key\\n\", self)\n\t\tos.Exit(2)\n\t}\n\tflags.Parse(args)\n\tif flags.NArg() != 1 {\n\t\tflags.Usage()\n\t}\n\targs = flags.Args()\n\n\treq := &pb.DeleteRequest{\n\t\tKey: []byte(args[0]),\n\t}\n\n\tc := d.dial()\n\tdefer c.Close()\n\n\tev, err := c.Delete(ctx, req)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn encode(ev)\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\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 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\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\n\n\nfunc (c *listBlocksCommand) Run(ctx *cmd.Context) error ", "output": "{\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}"} {"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\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) Padding() int ", "output": "{\n\treturn 0\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\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\nfunc TestGenerate(t *testing.T) {\n i := 1\n for s := range Generate(text, 0) {\n t.Logf(\"Generate: %d) %v\", i, s)\n i++\n }\n}\n\nfunc TestProcessRandom(t *testing.T) ", "output": "{\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}"} {"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\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\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 newPortMap(containerip string, containerport int) *PortMap ", "output": "{\n\treturn &PortMap{\n\t\tcontainerIP: containerip,\n\t\tcontainerPort: containerport,\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\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\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 SetMgoSession(mgoSession *mgo.Session) ", "output": "{\n\tsession = mgoSession\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/2020-11-01\"\n}"} {"input": "package packets\n\nimport (\n\t\"io\"\n)\n\ntype WillMsgReqMessage struct {\n\tHeader\n}\n\n\n\nfunc (wm *WillMsgReqMessage) Write(w io.Writer) error {\n\tpacket := wm.Header.pack()\n\tpacket.WriteByte(wm.Header.MessageType)\n\t_, err := packet.WriteTo(w)\n\n\treturn err\n}\n\nfunc (wm *WillMsgReqMessage) Unpack(b io.Reader) {\n\n}\n\nfunc (wm *WillMsgReqMessage) MessageType() byte ", "output": "{\n\treturn WILLMSGREQ\n}"} {"input": "package main\n\n\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\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) isValidBucketPERM() bool ", "output": "{\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}"} {"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\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\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 RemovePackage(code []byte) []byte ", "output": "{\n\trPackage, _ := regexp.Compile(\"package collection\")\n\tresult := rPackage.ReplaceAll(code, make([]byte, 0))\n\n\treturn result\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\nfunc (self *Host) PreUpdate(exe gorp.SqlExecutor) error {\n\treturn self.PreInsert(exe)\n}\n\n\n\nfunc (self *Host) PostGet(exe gorp.SqlExecutor) error ", "output": "{\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}"} {"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\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 (l *Logger) Infof(f string, args ...interface{}) ", "output": "{\n\tif l.Info {\n\t\tl.logger.Printf(l.prefix+\": \"+f, args...)\n\t}\n}"} {"input": "package tftp\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n)\n\nvar validPacketStrings = []string{\n\t\"\\x00\\x01test\\x00mail\\x00\",\n\t\"\\x00\\x02test\\x00netascii\\x00\",\n\t\"\\x00\\x02test\\x00octet\\x00blksize\\x001024\\x00tsize\\x000\\x00timeout\\x0010\\x00multicast\\x00\\x00windowsize\\x0016\\x00\",\n\t\"\\x00\\x03\\xbb\\xaadata\",\n\t\"\\x00\\x04\\xbb\\xaa\",\n\t\"\\x00\\x05\\xee\\xccerror message\\x00\",\n\t\"\\x00\\x06blksize\\x001024\\x00tsize\\x000\\x00timeout\\x0010\\x00multicast\\x00\\x00windowsize\\x0016\\x00\",\n}\n\ntype parts struct {\n\topcode opcode\n\tfilename string\n\tmode Mode\n\tblock block\n}\n\nvar validParts = []parts{\n\t{RRQ, \"test\", Mail, 0},\n\t{WRQ, \"test\", Netascii, 0},\n\t{WRQ, \"test\", Octet, 0},\n\t{DATA, \"\", 0, 0xbbaa},\n\t{ACK, \"\", 0, 0xbbaa},\n\t{ERROR, \"\", 0, 0},\n\t{OACK, \"\", 0, 0},\n}\n\n\n\nfunc TestPacket(t *testing.T) ", "output": "{\n\n\tfor i, s := range validPacketStrings {\n\t\tp := packet(s)\n\t\tif p.opcode() != validParts[i].opcode {\n\t\t\tfmt.Println(p.opcode().String())\n\t\t\tt.Fail()\n\t\t}\n\t\tif p.filename() != validParts[i].filename {\n\t\t\tfmt.Println(p.filename())\n\t\t\tt.Fail()\n\t\t}\n\t\tif p.mode() != validParts[i].mode {\n\t\t\tfmt.Println(p.mode().String())\n\t\t\tt.Fail()\n\t\t}\n\t\tif p.block() != validParts[i].block {\n\t\t\tt.Fail()\n\t\t}\n\t\tfmt.Println(p.options())\n\t}\n\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\n\n\nfunc analyzeDDL(ddl *sqlparser.DDL, getTable TableGetter) *ExecPlan {\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}\n\nfunc DDLParse(sql string, alloc arena.ArenaAllocator) (plan *DDLPlan) ", "output": "{\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}"} {"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\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 (d TimeField) String() string ", "output": "{\n\treturn fmt.Sprintf(\"%s=%s\", d.name, d.Is.UTC().Format(format))\n}"} {"input": "package cvss\n\nimport \"testing\"\n\nfunc TestBaseParse(t *testing.T) {\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}\n\n\nfunc TestCalculateBaseScore(t *testing.T) ", "output": "{\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}"} {"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\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) Bool(key string, def bool) bool ", "output": "{\n\te.Load()\n\treturn e.env.Bool(key, def)\n}"} {"input": "package interactive\n\nimport (\n\t\"fmt\"\n\t\"github.com/pkg/errors\"\n)\n\n\n\nfunc (i *Interpreter) executeFromCommands(commands []Commander, specific bool, arguments []string) error ", "output": "{\n\tvar err error\n\tfor _, val := range commands {\n\t\tvar responsible bool\n\t\tresponsible, err = tryExecuteCommand(val, i, specific, arguments)\n\t\tif responsible {\n\t\t\treturn err\n\t\t}\n\t}\n\tif err != nil {\n\t\treturn err\n\t}\n\tif specific {\n\t\tif len(arguments) < 2 {\n\t\t\terr = errors.New(\"subcommand not provided\")\n\t\t} else {\n\t\t\terr = errors.New(fmt.Sprintf(\"'%s' is not a valid function\", arguments[1]))\n\t\t}\n\t\treturn err\n\t}\n\treturn errors.New(\"'\" + arguments[0] + \"' is not a valid function\")\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\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) LoadFromEnv() ", "output": "{\n\tc.CommonSpec.LoadFromEnv(c.Format())\n}"} {"input": "package fileutils\n\nimport (\n\t\"io/ioutil\"\n\t\"os\"\n)\n\n\n\nfunc TempFile(namePrefix string, cb func(tmpFile *os.File, err error)) {\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}\n\nfunc TempDir(namePrefix string, cb func(tmpDir string, err error)) ", "output": "{\n\ttmpDir, err := ioutil.TempDir(\"\", namePrefix)\n\n\tdefer func() {\n\t\tos.RemoveAll(tmpDir)\n\t}()\n\n\tcb(tmpDir, err)\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\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) Scenario(name string) *T ", "output": "{\n\tLoadScenario(name)\n\tt.UpdateLedgerState()\n\treturn t\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\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\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 TestInvalidJSONFile(t *testing.T) ", "output": "{\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}"} {"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\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) Discard(filter func(int) bool) Ints ", "output": "{\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}"} {"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\nfunc NewFileFoundEvent(name string) *FileEvent {\n\treturn &FileEvent{\n\t\tEvent: fsnotify.Event{\n\t\t\tName: name,\n\t\t},\n\t\tIsFound: true,\n\t}\n}\n\n\n\nfunc NewFileEvent(ev fsnotify.Event) *FileEvent ", "output": "{\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}"} {"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\n\n\n\n\nfunc (r *Route) serveMatchedRequest(rw http.ResponseWriter, req *http.Request, vars map[string]string) {\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}\n\nfunc GetAllValues(req *http.Request) map[string]string ", "output": "{\n\tglobalVars.RLock()\n\tvalues := globalVars.v[req]\n\tglobalVars.RUnlock()\n\treturn values\n}"} {"input": "package eviction\n\nimport \"k8s.io/klog\"\n\n\n\n\ntype unsupportedThresholdNotifier struct{}\n\nfunc (*unsupportedThresholdNotifier) Start(_ chan<- struct{}) {}\n\nfunc (*unsupportedThresholdNotifier) Stop() {}\n\nfunc NewCgroupNotifier(path, attribute string, threshold int64) (CgroupNotifier, error) ", "output": "{\n\tklog.V(5).Infof(\"cgroup notifications not supported\")\n\treturn &unsupportedThresholdNotifier{}, nil\n}"} {"input": "package webshell\n\nimport (\n\t\"testing\"\n)\n\n\n\nfunc TestServer(t *testing.T) ", "output": "{\n\tfmt.Println(\"This test will run until interrupted with ^c or until\")\n\tfmt.Println(\"the Go test runner decides the test has run for too\")\n\tfmt.Println(\"long.\")\n\tLoadEnv()\n\tServe(false, nil)\n\tt.FailNow()\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\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 (df *InMemoryDataFile) Close() error ", "output": "{\n\treturn df.CloseFunc()\n}"} {"input": "package fs\n\nimport (\n\t\"os\"\n\t\"path/filepath\"\n\t\"strings\"\n)\n\nvar execExts map[string]bool\n\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\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 init() ", "output": "{\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}"} {"input": "package mcquery_test\n\nimport (\n\t\"fmt\"\n\t\"time\"\n\n\t\"github.com/sean-callahan/mcquery\"\n)\n\n\n\nfunc ExampleMcQuery_GetStatus() {\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}\n\nfunc ExampleDial() ", "output": "{\n\t_, err := mcquery.Dial(\"127.0.0.1:25565\", time.Second)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}"} {"input": "package member\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_path\"\n\t\"github.com/watermint/toolbox/domain/dropbox/service/sv_sharedfolder_member\"\n\t\"github.com/watermint/toolbox/domain/dropbox/usecase/uc_sharedfolder\"\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\t\"github.com/watermint/toolbox/quality/recipe/qtr_endtoend\"\n)\n\ntype Delete struct {\n\tPeer dbx_conn.ConnScopedIndividual\n\tPath mo_path.DropboxPath\n\tEmail string\n\tLeaveCopy bool\n}\n\nfunc (z *Delete) Preset() {\n\tz.Peer.SetScopes(\n\t\tdbx_auth.ScopeFilesContentRead,\n\t\tdbx_auth.ScopeSharingRead,\n\t\tdbx_auth.ScopeSharingWrite,\n\t)\n}\n\n\n\nfunc (z *Delete) Test(c app_control.Control) error {\n\treturn rc_exec.ExecMock(c, &Delete{}, func(r rc_recipe.Recipe) {\n\t\tm := r.(*Delete)\n\t\tm.Email = \"emma@example.com\"\n\t\tm.Path = qtr_endtoend.NewTestDropboxFolderPath(\"delete\")\n\t})\n}\n\nfunc (z *Delete) Exec(c app_control.Control) error ", "output": "{\n\tsfr := uc_sharedfolder.NewResolver(z.Peer.Context())\n\n\tsf, err := sfr.Resolve(z.Path)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\topts := make([]sv_sharedfolder_member.RemoveOption, 0)\n\tif z.LeaveCopy {\n\t\topts = append(opts, sv_sharedfolder_member.LeaveACopy())\n\t}\n\terr = sv_sharedfolder_member.New(z.Peer.Context(), sf).Remove(sv_sharedfolder_member.RemoveByEmail(z.Email), opts...)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn 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\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\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 initWorker(addr string) *Worker", "output": "{\n w := &Worker{}\n w.addr = addr\n w.addUrlChannel = make(chan bool)\n return w\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\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 *packetServerPluginMessageCodec) Decode(reader io.Reader) (decode packet.Packet, err error) ", "output": "{\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}"} {"input": "package clang\n\n\n\n\nimport \"C\"\n\n\ntype Version struct {\n\tc C.CXVersion\n}\n\n\nfunc (v Version) Major() int {\n\treturn int(v.c.Major)\n}\n\n\n\n\n\nfunc (v Version) Subminor() int {\n\treturn int(v.c.Subminor)\n}\n\nfunc (v Version) Minor() int ", "output": "{\n\treturn int(v.c.Minor)\n}"} {"input": "package marathon\n\nimport (\n\t\"fmt\"\n)\n\n\ntype Queue struct {\n\tItems []Item `json:\"queue\"`\n}\n\n\ntype Item struct {\n\tCount int `json:\"count\"`\n\tDelay Delay `json:\"delay\"`\n\tApplication Application `json:\"app\"`\n}\n\n\ntype Delay struct {\n\tOverdue bool `json:\"overdue\"`\n\tTimeLeftSeconds int `json:\"timeLeftSeconds\"`\n}\n\n\nfunc (r *marathonClient) Queue() (*Queue, error) {\n\tvar queue *Queue\n\terr := r.apiGet(marathonAPIQueue, nil, &queue)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn queue, nil\n}\n\n\n\n\n\nfunc (r *marathonClient) DeleteQueueDelay(appID string) error ", "output": "{\n\tpath := fmt.Sprintf(\"%s/%s/delay\", marathonAPIQueue, trimRootPath(appID))\n\treturn r.apiDelete(path, nil, nil)\n}"} {"input": "package pipe\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n)\n\n\n\nfunc TestReduceChanTypeCoercion(t *testing.T) {\n\tappendToString := func(str string, item fmt.Stringer) string {\n\t\treturn fmt.Sprintf(\"%s%s\", str, item.String())\n\t}\n\n\tin := make(chan testStringer, 5)\n\n\tgo func() {\n\t\tin <- 1\n\t\tin <- 2\n\t\tin <- 3\n\t\tclose(in)\n\t}()\n\n\tout := ReduceChan(appendToString, \"a\", in).(string)\n\n\tif out != \"a123\" {\n\t\tt.Fatal(\"ReduceChan(appendToString, \\\"a\\\", chan testStringer) output \", out)\n\t}\n}\n\nfunc TestReduceChan(t *testing.T) ", "output": "{\n\tin := make(chan int, 5)\n\n\tgo func() {\n\t\tin <- 5\n\t\tin <- 10\n\t\tin <- 20\n\t\tclose(in)\n\t}()\n\n\tout := ReduceChan(sum, 0, in).(int)\n\n\tif out != 35 {\n\t\tt.Fatal(\"ReduceChan(sum, 0, []int{5, 10, 20}) output \", out)\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\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\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) Ensure(c context.Context, req *projects.EnsureRequest) (*projects.Config, error) ", "output": "{\n\tsrv.cfg.Store(req.GetId(), req.GetProject())\n\treturn req.GetProject(), nil\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\n\n\nfunc (linux *Linux) groupExistsByID(groupID string) bool {\n\tgroup, _ := linux.groupLookupByID(groupID)\n\treturn group != nil\n}\n\nfunc (linux *Linux) GroupExists(groupName string) bool ", "output": "{\n\tgroup, _ := linux.groupLookup(groupName)\n\treturn group != nil\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\nfunc init() {\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}\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\n\n\nfunc printSubscriber(sub subscriber.Subscriber) ", "output": "{\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}"} {"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\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 (iov *Iovec) SetLen(length int) ", "output": "{\n\tiov.Len = uint64(length)\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\nfunc (i *sourcedImage) Manifest() ([]byte, string, error) {\n\treturn i.manifestBlob, i.manifestMIMEType, nil\n}\n\n\n\nfunc (i *sourcedImage) LayerInfosForCopy() []types.BlobInfo {\n\treturn i.UnparsedImage.LayerInfosForCopy()\n}\n\nfunc (i *sourcedImage) Inspect() (*types.ImageInspectInfo, error) ", "output": "{\n\treturn inspectManifest(i.genericManifest)\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\nfunc TestTestConfigure(t *testing.T) {\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}\n\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 TestTestConfigureMetricName(t *testing.T) ", "output": "{\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}"} {"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\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 ContentType) String() string ", "output": "{\n\treturn string(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\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 (fs *FileStateOS) IsSame(state *FileStateOS) bool ", "output": "{\n\treturn fs.Inode == state.Inode && fs.Device == state.Device\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n\n\t\"github.com/kataras/iris/v12/httptest\"\n)\n\ntype testRoute struct {\n\tpath string\n\tmethod string\n\tsubdomain string\n}\n\n\n\nfunc TestSubdomainWWW(t *testing.T) {\n\tapp := newApp()\n\n\ttests := []testRoute{\n\t\t{\"/\", \"GET\", \"\"},\n\t\t{\"/about\", \"GET\", \"\"},\n\t\t{\"/contact\", \"GET\", \"\"},\n\t\t{\"/api/users\", \"GET\", \"\"},\n\t\t{\"/api/users/42\", \"GET\", \"\"},\n\t\t{\"/api/users\", \"POST\", \"\"},\n\t\t{\"/api/users/42\", \"PUT\", \"\"},\n\t\t{\"/\", \"GET\", \"www\"},\n\t\t{\"/about\", \"GET\", \"www\"},\n\t\t{\"/contact\", \"GET\", \"www\"},\n\t\t{\"/api/users\", \"GET\", \"www\"},\n\t\t{\"/api/users/42\", \"GET\", \"www\"},\n\t\t{\"/api/users\", \"POST\", \"www\"},\n\t\t{\"/api/users/42\", \"PUT\", \"www\"},\n\t}\n\n\thost := \"localhost:1111\"\n\te := httptest.New(t, app, httptest.Debug(false))\n\n\tfor _, test := range tests {\n\n\t\treq := e.Request(test.method, test.path)\n\t\tif subdomain := test.subdomain; subdomain != \"\" {\n\t\t\treq.WithURL(\"http://\" + subdomain + \".\" + host)\n\t\t}\n\n\t\treq.Expect().\n\t\t\tStatus(httptest.StatusOK).\n\t\t\tBody().Equal(test.response())\n\t}\n}\n\nfunc (r testRoute) response() string ", "output": "{\n\tmsg := fmt.Sprintf(\"\\nInfo\\n\\nMethod: %s\\nSubdomain: %s\\nPath: %s\", r.method, r.subdomain, r.path)\n\treturn msg\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\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 (s *rtStore) Delete(apiContext *types.APIContext, schema *types.Schema, id string) (map[string]interface{}, error) ", "output": "{\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}"} {"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\nfunc init() {\n\tInstall(legacyscheme.GroupFactoryRegistry, legacyscheme.Registry, legacyscheme.Scheme)\n\tlegacy.InstallLegacySecurity(legacyscheme.Scheme, legacyscheme.Registry)\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: 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}"} {"input": "package bot\n\nimport (\n\t\"net/http\"\n)\n\n\n\nfunc mapContainsKey(m map[string]interface{}, k string) bool {\n\t_, ok := m[k]\n\treturn ok\n}\n\nfunc getBodyContent(r *http.Request) []byte ", "output": "{\n\tbody := make([]byte, r.ContentLength)\n\tr.Body.Read(body)\n\treturn body\n}"} {"input": "package daemon\n\nimport (\n\t\"github.com/docker/docker/daemon/graphdriver\"\n)\n\n\n\nfunc migrateIfAufs(driver graphdriver.Driver, root string) error ", "output": "{\n\treturn nil\n}"} {"input": "package internal\n\nimport (\n\t\"os\"\n\t\"path/filepath\"\n\n\t\"github.com/BurntSushi/toml\"\n)\n\n\n\n\n\nfunc WriteTomlFile(filename string, perm os.FileMode, value interface{}) error ", "output": "{\n\tif err := os.MkdirAll(filepath.Dir(filename), 0755); err != nil {\n\t\treturn err\n\t}\n\n\tfile, err := os.OpenFile(filename, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, perm)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer file.Close()\n\n\treturn toml.NewEncoder(file).Encode(value)\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\nfunc (t *LoadBalancerHealthCheck) GetUUID() string {\n\treturn t.UUID\n}\n\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) GetName() string ", "output": "{\n\tif name := t.UUID; name != \"\" {\n\t\treturn name\n\t}\n\treturn t.GetUUID()\n}"} {"input": "package main\n\ntype instanceGroupManagers struct {\n\tbasicGCPResource\n}\n\nfunc (b instanceGroupManagers) ifNeedZone(zoneInParameters bool) bool {\n\treturn true\n}\n\nfunc (b instanceGroupManagers) ifIDWithZone(zoneInParameters bool) bool {\n\treturn false\n}\n\n\nfunc (b instanceGroupManagers) ifNeedRegion() bool ", "output": "{\n\treturn false\n}"} {"input": "package gisp\n\nimport (\n\t\"reflect\"\n)\n\n\ntype Var interface {\n\tGet() interface{}\n\tSet(interface{})\n\tType() reflect.Type\n}\n\n\ntype OptionVar struct {\n\tslot reflect.Value\n}\n\n\nfunc (optVar OptionVar) Get() interface{} {\n\tif optVar.slot.Elem().IsNil() {\n\t\treturn nil\n\t}\n\treturn reflect.Indirect(optVar.slot).Elem().Interface()\n}\n\n\n\n\n\nfunc (optVar OptionVar) Type() reflect.Type {\n\treturn optVar.slot.Type().Elem().Elem()\n}\n\n\nfunc DefOption(typ reflect.Type) OptionVar {\n\tslot := reflect.New(reflect.PtrTo(typ))\n\tnull := reflect.Zero(reflect.PtrTo(typ))\n\tslot.Elem().Set(null)\n\treturn OptionVar{slot}\n}\n\n\ntype StrictVar struct {\n\tslot reflect.Value\n}\n\n\nfunc (svar StrictVar) Get() interface{} {\n\tif svar.slot.IsNil() {\n\t\treturn nil\n\t}\n\treturn svar.slot.Elem().Interface()\n}\n\n\nfunc (svar *StrictVar) Set(value interface{}) {\n\tsvar.slot.Elem().Set(reflect.ValueOf(value))\n}\n\n\nfunc (svar StrictVar) Type() reflect.Type {\n\treturn svar.slot.Type().Elem()\n}\n\n\nfunc DefStrict(typ reflect.Type) StrictVar {\n\tslot := reflect.New(typ)\n\treturn StrictVar{slot}\n}\n\n\nfunc StrictVarAs(x interface{}) StrictVar {\n\tslot := DefStrict(reflect.TypeOf(x))\n\tslot.Set(x)\n\treturn slot\n}\n\n\nfunc VarSlot(typ Type) Var {\n\tif typ.Option() {\n\t\tret := DefOption(typ.Type)\n\t\treturn &ret\n\t}\n\tret := DefStrict(typ.Type)\n\treturn &ret\n}\n\nfunc (optVar *OptionVar) Set(value interface{}) ", "output": "{\n\tif value == nil {\n\t\tnull := reflect.Zero(reflect.PtrTo(optVar.Type()))\n\t\toptVar.slot.Elem().Set(null)\n\t\treturn\n\t}\n\tval := reflect.New(optVar.Type())\n\tval.Elem().Set(reflect.ValueOf(value))\n\treflect.Indirect(optVar.slot).Set(val)\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\nfunc (self *CmdAccountAddTriggers) Name() string {\n\treturn self.name\n}\n\nfunc (self *CmdAccountAddTriggers) RpcMethod() string {\n\treturn self.rpcMethod\n}\n\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) RpcParams(reset bool) interface{} ", "output": "{\n\tif reset || self.rpcParams == nil {\n\t\tself.rpcParams = &v1.AttrAddAccountActionTriggers{}\n\t}\n\treturn self.rpcParams\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\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 IsRrdFileExist(filename string) bool ", "output": "{\n\treturn file.IsExist(filename)\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\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\nfunc ParseRecord(domain, address string) *Record {\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}\n\nfunc (r Records) ByType(typ string) (res Records) ", "output": "{\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}"} {"input": "package cf_test\n\nimport (\n\t\"testing\"\n\n\t. \"github.com/onsi/ginkgo\"\n\t. \"github.com/onsi/gomega\"\n)\n\n\n\nfunc TestCFSuite(t *testing.T) ", "output": "{\n\tRegisterFailHandler(Fail)\n\tRunSpecs(t, \"cf\")\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\n\n\nfunc (i *DefaultUserIdentityInfo) GetExtra() map[string]string {\n\treturn i.Extra\n}\n\nfunc (i *DefaultUserIdentityInfo) GetProviderName() string ", "output": "{\n\treturn i.ProviderName\n}"} {"input": "package build\n\nimport \"go/ast\"\n\n\n\nfunc NewFile(pkg string, decl ...ast.Decl) *ast.File ", "output": "{\n\treturn &ast.File{\n\t\tName: &ast.Ident{\n\t\t\tName: pkg,\n\t\t},\n\t\tDecls: decl,\n\t}\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\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\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 (s *stubProvider) Retrieve() (Value, error) ", "output": "{\n\ts.creds.ProviderName = \"stubProvider\"\n\treturn s.creds, s.err\n}"} {"input": "package mapka\n\nimport (\n\t\"strings\"\n\n\t\"klogproc/load/accesslog\"\n)\n\n\n\n\ntype LineParser struct {\n\tparser accesslog.LineParser\n}\n\n\nfunc (lp *LineParser) ParseLine(s string, lineNum int64) (*InputRecord, error) {\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}\n\nfunc getAction(path string) (string, *RequestParams) ", "output": "{\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}"} {"input": "package app\n\nimport \"github.com/goadesign/goa\"\n\n\n\n\ntype Pong struct {\n\tMsg string `form:\"msg\" json:\"msg\" xml:\"msg\"`\n}\n\n\n\n\nfunc (mt *Pong) Validate() (err error) ", "output": "{\n\tif mt.Msg == \"\" {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`response`, \"msg\"))\n\t}\n\treturn\n}"} {"input": "package language\n\n\n\nconst (\n\tcurDigitBits = 3\n\tcurDigitMask = 1<> curDigitBits)\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\n\n\nfunc (fake *FakeInfoFactory) GetCallCount() int {\n\tfake.getMutex.RLock()\n\tdefer fake.getMutex.RUnlock()\n\treturn len(fake.getArgsForCall)\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) Get() (info.Info, error) ", "output": "{\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}"} {"input": "package internal\n\nimport (\n\tM \"github.com/ionous/sashimi/compiler/xmodel\"\n\t\"github.com/ionous/sashimi/util/ident\"\n\t\"strings\"\n)\n\n\n\n\ntype IBuildProperty interface {\n\tSetProperty(PropertyContext) error\n\tBuildProperty() (M.IProperty, error)\n}\n\n\n\n\n\n\ntype PropertyContext struct {\n\tinst ident.Id \n\ttables TableRelations \n\tclass *M.ClassInfo \n\tvalues PendingValues \n\trefs PartialMap \n\tvalue interface{} \n}\n\n\n\n\ntype PropertyBuilders struct {\n\tparent *PropertyBuilders\n\tprops map[ident.Id]IBuildProperty\n\tnames map[string]ident.Id\n}\n\nfunc NewProperties(parent *PropertyBuilders) PropertyBuilders {\n\treturn PropertyBuilders{parent, make(map[ident.Id]IBuildProperty), make(map[string]ident.Id)}\n}\n\n\n\n\n\n\n\n\n\nfunc (b *PropertyBuilders) findProperty(name string) (ret IBuildProperty, okay bool) {\n\tfor k, v := range b.names {\n\t\tif strings.EqualFold(name, k) {\n\t\t\tret, okay = b.props[v]\n\t\t\tbreak\n\t\t}\n\t}\n\tif !okay && b.parent != nil {\n\t\tret, okay = b.parent.findProperty(name)\n\t}\n\treturn\n}\n\n\n\n\nfunc (b *PropertyBuilders) propertyById(id ident.Id) (IBuildProperty, bool) {\n\tprop, okay := b.props[id]\n\tif !okay && b.parent != nil {\n\t\tprop, okay = b.parent.propertyById(id)\n\t}\n\treturn prop, okay\n}\n\nfunc (b *PropertyBuilders) make(\n\tid ident.Id,\n\tname string,\n\tvalidator func(IBuildProperty) error,\n\tcreator func() (IBuildProperty, error),\n) (\n\tret IBuildProperty,\n\terr error,\n) ", "output": "{\n\tif old, existed := b.props[id]; !existed {\n\t\tif p, e := creator(); e != nil {\n\t\t\terr = e\n\t\t} else {\n\t\t\tb.props[id] = p\n\t\t\tb.names[name] = id\n\t\t\tret = p\n\t\t}\n\t} else {\n\t\tif validator != nil {\n\t\t\terr = validator(old)\n\t\t}\n\t\tif err == nil {\n\t\t\tret = old\n\t\t}\n\t}\n\treturn ret, 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\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 main\n\nimport (\n\t\"fmt\"\n\t\"sync\"\n\t\"testing\"\n)\n\ntype inspector struct {\n\terr error\n}\n\nfunc (i *inspector) imageInfo(imagePath string) (int, error) {\n\tif i.err != nil {\n\t\treturn 0, i.err\n\t}\n\treturn 10, nil\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\nfunc TestGetMinImageSize(t *testing.T) ", "output": "{\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}"} {"input": "package main\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"log\"\n\t\"net/http\"\n)\n\nconst url = \"https://httpbin.org/ip\"\n\nfunc main() {\n\tresp, err := http.Get(url)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tdefer resp.Body.Close()\n\n\tif resp.StatusCode != http.StatusOK {\n\t\tpanic(resp.Status)\n\t}\n\n\tb, err := ioutil.ReadAll(resp.Body)\n\n\tresult := ip{}\n\tif err := json.Unmarshal(b, &result); err != nil {\n\t\tpanic(err)\n\t}\n\n\tfmt.Printf(\"%s\\n\", result)\n}\n\n\ntype ip struct {\n\tOrigin string `json:\"origin\"`\n}\n\n\n\n\nfunc (i ip) String() string ", "output": "{\n\treturn fmt.Sprintf(\"%s\", i.Origin)\n}"} {"input": "package modules\n\nimport (\n\t\"bytes\"\n\t\"encoding/gob\"\n)\n\nfunc Encode(data interface{}) ([]byte, error) {\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}\n\n\n\nfunc Decode(data []byte, to interface{}) error ", "output": "{\n\tbuf := bytes.NewBuffer(data)\n\tdec := gob.NewDecoder(buf)\n\treturn dec.Decode(to)\n}"} {"input": "package common\n\nimport (\n\t\"fmt\"\n\t\"net/url\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"strings\"\n\t\"time\"\n)\n\n\n\n\nconst PackerKeyEnv = \"PACKER_KEY_INTERVAL\"\n\n\n\nconst PackerKeyDefault = 100 * time.Millisecond\n\n\n\n\n\n\nfunc ChooseString(vals ...string) string {\n\tfor _, el := range vals {\n\t\tif el != \"\" {\n\t\t\treturn el\n\t\t}\n\t}\n\n\treturn \"\"\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 ScrubConfig(target interface{}, values ...string) string ", "output": "{\n\tconf := fmt.Sprintf(\"Config: %+v\", target)\n\tfor _, value := range values {\n\t\tif value == \"\" {\n\t\t\tcontinue\n\t\t}\n\t\tconf = strings.Replace(conf, value, \"\", -1)\n\t}\n\treturn conf\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\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) States() ([]string, error) ", "output": "{\n\treturn nil, backend.ErrNamedStatesNotSupported\n}"} {"input": "package music\n\nimport (\n\t\"context\"\n\t\"testing\"\n\n\t\"github.com/smartystreets/goconvey/convey\"\n)\n\n\n\nfunc TestMusicMCategorys(t *testing.T) {\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}\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 TestMusicCategorys(t *testing.T) ", "output": "{\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}"} {"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\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 WithConstRandReader(testNonce string, f func()) ", "output": "{\n\n\toriginal := rand.Reader\n\trand.Reader = &constReader{nonce: testNonce}\n\n\tf()\n\n\trand.Reader = original\n\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\nfunc (f *Field) WithLock(fn func(*Field)) {\n\tf.Lock()\n\tfn(f)\n\tf.Unlock()\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\n\n\nfunc (f *Field) loop(handle HandleFunc) ", "output": "{\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}"} {"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\nfunc ReadConfig() Configuration {\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}\n\n\n\n\n\nfunc ParseTemplates() ", "output": "{\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}"} {"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\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 (rwci *rpcWrapCallInfoImpl) RemoteAddr() string ", "output": "{\n\treturn rwci.remoteAddr\n}"} {"input": "package drum\n\nimport (\n\t\"fmt\"\n\t\"os\"\n)\n\n\n\n\nfunc DecodeFile(path string) (*Pattern, error) {\n\tf, err := os.Open(path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar p *Pattern\n\tif p, err = decode(f); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn p, f.Close()\n}\n\n\n\ntype Pattern struct {\n\tVersion string\n\tTempo float32\n\tTracks []Track\n}\n\n\n\nfunc (p Pattern) String() string ", "output": "{\n\ts := fmt.Sprintln(\"Saved with HW Version:\", p.Version)\n\ts += fmt.Sprintln(\"Tempo:\", p.Tempo)\n\tfor _, t := range p.Tracks {\n\t\ts += fmt.Sprint(t)\n\t}\n\treturn s\n}"} {"input": "package euler\n\n\nfunc Problem21() int {\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}\n\n\n\n\n\n\n\n\n\n\nfunc isAmicable(a int) bool ", "output": "{\n\tb := PropDivSum(a)\n\treturn a != b && a == PropDivSum(b)\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\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 *FmtPrintlnAspect) Pointcut() asp.Pointcut ", "output": "{\n\ts := regexp.QuoteMeta(\"fmt.Println\")\n\treturn asp.NewCallPointcutFromRegexp(s)\n}"} {"input": "package grains\n\nimport \"errors\"\n\n\nconst numSquares = 64\n\n\nconst testVersion = 1\n\n\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\nfunc Total() uint64 {\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}\n\nfunc pow(a uint64, b uint64) (uint64, error) ", "output": "{\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}"} {"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\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\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) MatchString(key string, predicate getter.StringPredicate) bool ", "output": "{\n\tif b, err := obj.GetFieldString(key); err == nil {\n\t\treturn predicate(b)\n\t}\n\treturn false\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\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\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) CreateTopic(topic string) error ", "output": "{\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}"} {"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\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) Session() *mgo.Session ", "output": "{\n s := mongo.session.Copy()\n s.SetMode(mgo.Strong, true)\n return s\n}"} {"input": "package command_factory_test\n\nimport (\n\t. \"github.com/onsi/ginkgo\"\n\t. \"github.com/onsi/gomega\"\n\n\t\"testing\"\n)\n\n\n\nfunc TestCommandFactory(t *testing.T) ", "output": "{\n\tRegisterFailHandler(Fail)\n\tRunSpecs(t, \"Command Factory Suite\")\n}"} {"input": "package drum\n\nimport \"fmt\"\n\n\n\ntype Pattern struct {\n\tversion Version\n\ttempo Tempo\n\ttracks Tracks\n}\n\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\nfunc (n Note) String() string {\n\tif n {\n\t\treturn \"x\"\n\t}\n\treturn \"-\"\n}\n\nfunc (p Pattern) String() string ", "output": "{\n\treturn fmt.Sprintf(\"%s\\n%s\\n%s\", p.version.String(), p.tempo.String(), p.tracks.String())\n}"} {"input": "package common\n\nimport (\n\t\"github.com/mitchellh/multistep\"\n\t\"testing\"\n)\n\n\n\nfunc TestStepConnectSSH_Impl(t *testing.T) ", "output": "{\n\tvar raw interface{}\n\traw = new(StepConnectSSH)\n\tif _, ok := raw.(multistep.Step); !ok {\n\t\tt.Fatalf(\"connect ssh should be a step\")\n\t}\n}"} {"input": "package graphql\n\nimport (\n\t\"context\"\n\t\"encoding/json\"\n\t\"io\"\n\n\t\"github.com/dennwc/graphql/gqlerrors\"\n\n\t\"github.com/cayleygraph/cayley/graph\"\n\t\"github.com/cayleygraph/cayley/query\"\n)\n\ntype httpResult struct {\n\tData interface{} `json:\"data\"`\n\tErrors []gqlerrors.FormattedError `json:\"errors,omitempty\"`\n}\n\n\n\nfunc httpQuery(ctx context.Context, qs graph.QuadStore, w query.ResponseWriter, r io.Reader) {\n\tq, err := Parse(r)\n\tif err != nil {\n\t\thttpError(w, err)\n\t\treturn\n\t}\n\tm, err := q.Execute(ctx, qs)\n\tif err != nil {\n\t\thttpError(w, err)\n\t\treturn\n\t}\n\tjson.NewEncoder(w).Encode(httpResult{Data: m})\n}\n\nfunc httpError(w query.ResponseWriter, err error) ", "output": "{\n\tjson.NewEncoder(w).Encode(httpResult{\n\t\tErrors: []gqlerrors.FormattedError{{\n\t\t\tMessage: err.Error(),\n\t\t}},\n\t})\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\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) resolveType() ", "output": "{\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}"} {"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\n\n\nfunc getIds(path string) []string {\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}\n\nfunc Watch(period int, states chan map[string]string) ", "output": "{\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}"} {"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\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\n\n\nfunc modifierFromJSON(b []byte) (*parse.Result, error) ", "output": "{\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}"} {"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\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 TestDown(t *testing.T) ", "output": "{\n\terr := Down(\"hci0\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n}"} {"input": "package main\n\nimport (\n\t\"github.com/takama/daemon\"\n)\n\n\ntype Service struct {\n\tdaemon.Daemon\n}\n\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\nfunc (service *Service) Update() (string, error) {\n\treturn \"\", nil\n}\n\nfunc (service *Service) Start() (string, error) ", "output": "{\n\n\n\tgo URLScanner(results, control, urls)\n\treturn \"\", nil\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\n\n\nfunc (d *DirectDebitTransaction1) SetPreNotificationDate(value string) {\n\td.PreNotificationDate = (*ISODate)(&value)\n}\n\nfunc (d *DirectDebitTransaction1) SetPreNotificationIdentification(value string) ", "output": "{\n\td.PreNotificationIdentification = (*Max35Text)(&value)\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 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\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 FieldHasBoolExtension(field *descriptor.FieldDescriptorProto, extension *proto.ExtensionDesc) bool ", "output": "{\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}"} {"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\n\n\nfunc runFind(cmd *cobra.Command, args []string) {\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}\n\nvar findDescription = `\nVerify if group exists in the whitelist\n\n`\n\nfunc newFindCommand() *cobra.Command ", "output": "{\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}"} {"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\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 setup(c *caddy.Controller) error ", "output": "{\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}"} {"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\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 CopyFilesTo(mainOutput abstract.OutputInterface, helper *iotool.FileHelper, paths ...string) (e error) ", "output": "{\n\treturn CopyFilesFilteredTo(mainOutput, helper, nil, paths...)\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\n\n\nfunc (t *secretboxTransformer) TransformToStorage(data []byte, context value.Context) ([]byte, error) {\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}\n\nfunc (t *secretboxTransformer) TransformFromStorage(data []byte, context value.Context) ([]byte, bool, error) ", "output": "{\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}"} {"input": "package fileutil\n\nimport (\n\t\"io/ioutil\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"reflect\"\n\t\"testing\"\n)\n\n\n\nfunc TestReadDir(t *testing.T) {\n\ttmpdir, err := ioutil.TempDir(\"\", \"\")\n\tdefer os.RemoveAll(tmpdir)\n\tif err != nil {\n\t\tt.Fatalf(\"unexpected ioutil.TempDir error: %v\", err)\n\t}\n\tfiles := []string{\"def\", \"abc\", \"xyz\", \"ghi\"}\n\tfor _, f := range files {\n\t\tfh, err := os.Create(filepath.Join(tmpdir, f))\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"error creating file: %v\", err)\n\t\t}\n\t\tif err := fh.Close(); err != nil {\n\t\t\tt.Fatalf(\"error closing file: %v\", err)\n\t\t}\n\t}\n\tfs, err := ReadDir(tmpdir)\n\tif err != nil {\n\t\tt.Fatalf(\"error calling ReadDir: %v\", err)\n\t}\n\twfs := []string{\"abc\", \"def\", \"ghi\", \"xyz\"}\n\tif !reflect.DeepEqual(fs, wfs) {\n\t\tt.Fatalf(\"ReadDir: got %v, want %v\", fs, wfs)\n\t}\n}\n\nfunc TestIsDirWriteable(t *testing.T) ", "output": "{\n\ttmpdir, err := ioutil.TempDir(\"\", \"\")\n\tif err != nil {\n\t\tt.Fatalf(\"unexpected ioutil.TempDir error: %v\", err)\n\t}\n\tdefer os.RemoveAll(tmpdir)\n\tif err := IsDirWriteable(tmpdir); err != nil {\n\t\tt.Fatalf(\"unexpected IsDirWriteable error: %v\", err)\n\t}\n\tif err := os.Chmod(tmpdir, 0444); err != nil {\n\t\tt.Fatalf(\"unexpected os.Chmod error: %v\", err)\n\t}\n\tif err := IsDirWriteable(tmpdir); err == nil {\n\t\tt.Fatalf(\"expected IsDirWriteable to error\")\n\t}\n}"} {"input": "package system\n\nimport (\n\t\"github.com/kassisol/twic/version\"\n\t\"github.com/spf13/cobra\"\n)\n\n\n\nvar versionDescription = `\nAll software has versions. This is TWIC's\n\n`\n\nfunc NewVersionCommand() *cobra.Command ", "output": "{\n\tcmd := &cobra.Command{\n\t\tUse: \"version\",\n\t\tShort: \"Show the TWIC version information\",\n\t\tLong: versionDescription,\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\t\t\tinfo := version.New()\n\t\t\tinfo.ShowVersion()\n\t\t},\n\t}\n\n\treturn cmd\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\nfunc (ref *Reference) ShortName() string {\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}\n\n\n\n\nfunc (ref *Reference) RefGroup() string ", "output": "{\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}"} {"input": "package gobject\n\n\n\nfunc GetVampir() GObject ", "output": "{\n\tvar vampir GObject\n\tvampir.NewGObject(\"Vampir\", 50, 1, 10, 7, 15)\n\tvampir.StartSentence = \"Not a human.\\nOh it's a vampir.\"\n\tvampir.DieSentence = \"*Scream and decays into ash.\"\n\tvampir.NeutralSentence = \"Vampir: You was delicious.\"\n\tvampir.Sentences = append(vampir.Sentences, \"I love human blood.\",\n\t\t\"I would do anything for blood.\")\n\tvampir.FightOptions = append(vampir.FightOptions, GetNewFightOption(\"Spend Blood\", 15))\n\treturn vampir\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\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\n\n\nfunc WriteBytes(w Writer, v uint8, count int32) ", "output": "{\n\tfor i := int32(0); i < count; i++ {\n\t\tw.Uint8(v)\n\t}\n}"} {"input": "package alignmentprofile\n\nimport \"testing\"\n\nfunc TestUnmarshalEmpty(t *testing.T) {\n\tsrc := \"\"\n\t_, err := Parse(src)\n\tif err == nil {\n\t\tt.Errorf(\"Expected error on empty YAML file\")\n\t}\n}\n\n\n\nfunc TestInvalidProfile(t *testing.T) ", "output": "{\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}"} {"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\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) MarshalBinary() ([]byte, error) ", "output": "{\n\tif m == nil {\n\t\treturn nil, nil\n\t}\n\treturn swag.WriteJSON(m)\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\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\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 SerializeBytes(m interface{}) ([]byte, error) ", "output": "{\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}"} {"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\nfunc (response DeleteBudgetResponse) String() string {\n\treturn common.PointerString(response)\n}\n\n\n\n\nfunc (response DeleteBudgetResponse) HTTPResponse() *http.Response ", "output": "{\n\treturn response.RawResponse\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\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 (pc *PendingClient) Handle(raw IrcClientMessage) ", "output": "{\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}"} {"input": "package aggregators\n\nimport (\n\t\"github.com/poy/ledger/transaction\"\n)\n\n\n\nfunc NewSum() AggregatorFunc {\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}\n\nfunc init() ", "output": "{\n\tAddToStore(\"sum\", NewSum())\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\n\n\nfunc (tp *ThreadPool) onStop() {\n tp.m.Lock()\n tp.running--\n tp.m.Unlock()\n tp.run()\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 NewThreadPool(size int) *ThreadPool ", "output": "{\n tp := &ThreadPool{\n size: size,\n list: list.New(),\n }\n return tp\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 == 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 travel\n\nimport (\n\t\"os\"\n\n\t\"github.com/akerl/speculate/v2/creds\"\n)\n\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\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 clearEnvironment() error ", "output": "{\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}"} {"input": "package editor\n\nimport (\n\t\"os/user\"\n\t\"path/filepath\"\n)\n\ntype EditorConfig struct {\n\tDefaultKeymap KeyMap\n}\n\nfunc GetConfigFileLocation() (string, error) {\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}\n\n\n\nfunc LoadConfig(configFile string) (*EditorConfig, error) ", "output": "{\n\treturn nil, 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\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\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 NewRoundRobinGroup(routees ...*actor.PID) *actor.Props ", "output": "{\n\treturn actor.FromSpawnFunc(spawner(&roundRobinGroupRouter{GroupRouter{Routees: actor.NewPIDSet(routees...)}}))\n}"} {"input": "package leap\n\n\nconst testVersion = 2\n\n\n\n\nfunc IsLeapYear(year int) bool ", "output": "{\n\treturn year%4 == 0 && !(year%100 == 0 && year%400 != 0)\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\n\n\n\nfunc (i Image) Visibility() image.Visibility {\n\tif i.TenantID == \"\" {\n\t\treturn image.Public\n\t}\n\treturn image.Private\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 (state State) Status() image.Status ", "output": "{\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}"} {"input": "package main\n\nvar counter uint\nvar shift uint\n\nfunc GetValue() uint {\n\tcounter++;\n\treturn 1 << shift\n}\n\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 Send(a, b chan uint) int ", "output": "{\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}"} {"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\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 (\n\t\"flag\"\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n\t\"path\"\n\t\"strings\"\n\t\"text/tabwriter\"\n\n\t\"github.com/skriptble/froxy/cmd/froxy/Godeps/_workspace/src/github.com/BurntSushi/toml\"\n)\n\nvar (\n\tflagTypes = false\n)\n\n\n\nfunc usage() {\n\tlog.Printf(\"Usage: %s toml-file [ toml-file ... ]\\n\",\n\t\tpath.Base(os.Args[0]))\n\tflag.PrintDefaults()\n\n\tos.Exit(1)\n}\n\nfunc main() {\n\tif flag.NArg() < 1 {\n\t\tflag.Usage()\n\t}\n\tfor _, f := range flag.Args() {\n\t\tvar tmp interface{}\n\t\tmd, err := toml.DecodeFile(f, &tmp)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"Error in '%s': %s\", f, err)\n\t\t}\n\t\tif flagTypes {\n\t\t\tprintTypes(md)\n\t\t}\n\t}\n}\n\nfunc printTypes(md toml.MetaData) {\n\ttabw := tabwriter.NewWriter(os.Stdout, 0, 0, 2, ' ', 0)\n\tfor _, key := range md.Keys() {\n\t\tfmt.Fprintf(tabw, \"%s%s\\t%s\\n\",\n\t\t\tstrings.Repeat(\" \", len(key)-1), key, md.Type(key...))\n\t}\n\ttabw.Flush()\n}\n\nfunc init() ", "output": "{\n\tlog.SetFlags(0)\n\n\tflag.BoolVar(&flagTypes, \"types\", flagTypes,\n\t\t\"When set, the types of every defined key will be shown.\")\n\n\tflag.Usage = usage\n\tflag.Parse()\n}"} {"input": "package node\n\nimport (\n\t\"time\"\n\n\t\"github.com/tendermint/go-crypto\"\n)\n\ntype NodeID struct {\n\tName string\n\tPubKey crypto.PubKey\n}\n\ntype PrivNodeID struct {\n\tNodeID\n\tPrivKey crypto.PrivKey\n}\n\ntype NodeGreeting struct {\n\tNodeID\n\tVersion string\n\tChainID string\n\tMessage string\n\tTime time.Time\n}\n\ntype SignedNodeGreeting struct {\n\tNodeGreeting\n\tSignature crypto.Signature\n}\n\n\n\nfunc (pnid *PrivNodeID) SignGreeting() *SignedNodeGreeting ", "output": "{\n\treturn nil\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\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 parseutil\n\nimport (\n\t\"strings\"\n\n\t\"src.elv.sh/pkg/parse\"\n)\n\n\n\n\nfunc wordifyInner(n parse.Node, words []string) []string {\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}\n\nfunc isCompound(n parse.Node) bool {\n\t_, ok := n.(*parse.Compound)\n\treturn ok\n}\n\nfunc Wordify(src string) []string ", "output": "{\n\ttree, _ := parse.Parse(parse.Source{Code: src}, parse.Config{})\n\treturn wordifyInner(tree.Root, nil)\n}"} {"input": "package buckettree\n\nimport (\n\t\"testing\"\n\n\t\"github.com/openblockchain/obc-peer/openchain/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 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\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 ReadData(r io.Reader, intf interface{}) error ", "output": "{\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}"} {"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\n\n\nfunc ExampleP041() {\n\tmain()\n\n}\n\nfunc BenchmarkP041B(b *testing.B) ", "output": "{\n\tfor i := 0; i < b.N; i++ {\n\t\tp041B()\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\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\n\n\nfunc UpdateImage(c *gin.Context) ", "output": "{\n\tc.JSON(http.StatusOK, gin.H{\"status\": http.StatusOK, \"data\": \"ID of the image we updated goes here\"})\n}"} {"input": "package antibody\n\nimport (\n\t\"testing\"\n\n\t\"github.com/caarlos0/antibody/doubles\"\n\t\"github.com/stretchr/testify/assert\"\n)\n\n\n\nfunc TestClonesValidRepoTwoTimes(t *testing.T) {\n\thome := doubles.TempHome()\n\tbundle := NewGitBundle(\"caarlos0/zsh-pg\", home)\n\tbundle.Download()\n\terr := bundle.Download()\n\texpected := home + \"caarlos0-zsh-pg\"\n\tassert.Equal(t, expected, bundle.Folder())\n\tassert.NoError(t, err)\n\tassertBundledPlugins(t, 1, home)\n}\n\nfunc TestClonesInvalidRepo(t *testing.T) {\n\thome := doubles.TempHome()\n\terr := NewGitBundle(\"this-doesnt-exist\", home).Download()\n\tassert.Error(t, err)\n}\n\nfunc TestPullsRepo(t *testing.T) {\n\thome := doubles.TempHome()\n\tbundle := NewGitBundle(\"caarlos0/zsh-pg\", home)\n\tbundle.Download()\n\terr := bundle.Update()\n\tassert.NoError(t, err)\n}\n\nfunc TestSourceablesDotPluginZsh(t *testing.T) {\n\thome := doubles.TempHome()\n\tbundle := NewGitBundle(\"caarlos0/zsh-pg\", home)\n\tbundle.Download()\n\tsrcs := bundle.Sourceables()\n\tassert.Len(t, srcs, 1)\n}\n\nfunc TestSourceablesDotSh(t *testing.T) {\n\thome := doubles.TempHome()\n\tbundle := NewGitBundle(\"rupa/z\", home)\n\tbundle.Download()\n\tsrcs := bundle.Sourceables()\n\tassert.Len(t, srcs, 1)\n}\n\nfunc TestClonesValidRepo(t *testing.T) ", "output": "{\n\thome := doubles.TempHome()\n\tbundle := NewGitBundle(\"caarlos0/zsh-pg\", home)\n\terr := bundle.Download()\n\texpected := home + \"caarlos0-zsh-pg\"\n\n\tassert.Equal(t, expected, bundle.Folder())\n\tassert.NoError(t, err)\n\tassertBundledPlugins(t, 1, home)\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\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\n\n\nfunc (f *FormatEncoder) EncodeEntry(entry zapcore.Entry, fields []zapcore.Field) (*buffer.Buffer, error) ", "output": "{\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}"} {"input": "package terraform\n\n\ntype MockUIInput struct {\n\tInputCalled bool\n\tInputOpts *InputOpts\n\tInputReturnMap map[string]string\n\tInputReturnString string\n\tInputReturnError error\n\tInputFn func(*InputOpts) (string, error)\n}\n\n\n\nfunc (i *MockUIInput) Input(opts *InputOpts) (string, error) ", "output": "{\n\ti.InputCalled = true\n\ti.InputOpts = opts\n\tif i.InputFn != nil {\n\t\treturn i.InputFn(opts)\n\t}\n\tif i.InputReturnMap != nil {\n\t\treturn i.InputReturnMap[opts.Id], i.InputReturnError\n\t}\n\treturn i.InputReturnString, i.InputReturnError\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\nfunc (fr *FileReader) Close() error {\n\treturn fr.f.Close()\n}\n\n\n\n\n\nfunc (fr *FileReader) Next(v interface{}) error ", "output": "{\n\treturn fr.r.Next(v)\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\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\nfunc Convert_v1beta1_JSON_To_apiextensions_JSON(in *JSON, out *apiextensions.JSON, s conversion.Scope) error {\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}\n\nfunc Convert_apiextensions_JSONSchemaProps_To_v1beta1_JSONSchemaProps(in *apiextensions.JSONSchemaProps, out *JSONSchemaProps, s conversion.Scope) error ", "output": "{\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}"} {"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\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\n\n\nfunc (j *jobCounter) GetEventChannel() <-chan uint ", "output": "{\n\tj.mu.RLock()\n\tdefer j.mu.RUnlock()\n\treturn j.eventCh\n}"} {"input": "package dos\n\nimport (\n\t\"os\"\n\t\"path/filepath\"\n\t\"strings\"\n)\n\n\nfunc GetHome() string {\n\thome := os.Getenv(\"HOME\")\n\tif home == \"\" {\n\t\thome = os.Getenv(\"USERPROFILE\")\n\t}\n\treturn home\n}\n\n\n\n\n\nfunc ReplaceHomeToTildeSlash(wd string) string {\n\treturn filepath.ToSlash(ReplaceHomeToTilde(wd))\n}\n\nfunc ReplaceHomeToTilde(wd string) string ", "output": "{\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}"} {"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\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\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 NewVirtualHosts(vhosts map[string]http.Handler) *VirtualHosts ", "output": "{\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}"} {"input": "package model\n\nimport (\n\t\"os\"\n\t\"testing\"\n)\n\n\n\nfunc getTestPath() string {\n\treturn \"testdata/apikeys.json\"\n}\n\nfunc TestAPIKeyManager(t *testing.T) ", "output": "{\n\tCreateAPIKeyManager()\n\tm := GetAPIKeyManager()\n\tpath := getTestPath()\n\terr := m.readFile(path)\n\tif err != nil {\n\t\tt.Error(\"Error in readFile\", err)\n\t}\n\n\tak := m.CreateAPIKey()\n\tm.writeFile(path)\n\n\terr = m.readFile(path)\n\tif err != nil {\n\t\tt.Error(\"Error in readFile\", err)\n\t}\n\n\tif m.IsValidAPIKey(ak) == false {\n\t\tt.Error(\"Expected created API key to be valid\")\n\t}\n\n\tm.DeleteAPIKey(ak)\n\tif m.IsValidAPIKey(ak) == true {\n\t\tt.Error(\"Expected API key to be deleted\")\n\t}\n\n\tdefer os.Remove(path)\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\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\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) Close(inputs, secrets [][]byte) error ", "output": "{\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}"} {"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\n\n\nfunc Removexattr(path string, attr string) (err error) {\n\treturn syscall.Removexattr(path, attr)\n}\n\nfunc Setxattr(path string, attr string, data []byte, flags int) (err error) ", "output": "{\n\treturn syscall.Setxattr(path, attr, data, flags)\n}"} {"input": "package captcha\n\nimport (\n\t\"io/ioutil\"\n\t\"testing\"\n)\n\n\n\nfunc BenchmarkAudioWriteTo(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\ta := NewAudio(id, d, \"\")\n\t\tn, _ := a.WriteTo(ioutil.Discard)\n\t\tb.SetBytes(n)\n\t}\n}\n\nfunc BenchmarkNewAudio(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\tNewAudio(id, d, \"\")\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\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 (s *memProvider) LogStorage() storage.LogStorage ", "output": "{\n\treturn NewLogStorage(s.ts, s.mf)\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\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) SnapshotID(snapshotID string) *PodVolumeBackupBuilder ", "output": "{\n\tb.object.Status.SnapshotID = snapshotID\n\treturn b\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\n\n\nfunc (n *Node) IsAlive() bool {\n\treturn n.conn != nil\n}\n\nfunc (n *Node) String() string ", "output": "{\n\treturn fmt.Sprintf(\"%s(%s)\", n.Name, n.GRPCAddr)\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\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\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) request(req *http.Request) ([]byte, error) ", "output": "{\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}"} {"input": "package http\n\nimport (\n\t\"go-common/app/admin/main/workflow/model/param\"\n\t\"go-common/library/ecode\"\n\t\"go-common/library/log\"\n\tbm \"go-common/library/net/http/blademaster\"\n\t\"go-common/library/net/http/blademaster/binding\"\n)\n\n\n\nfunc addOrUpCallback(ctx *bm.Context) {\n\tcbp := ¶m.AddCallbackParam{}\n\tif err := ctx.BindWith(cbp, binding.JSON); err != nil {\n\t\treturn\n\t}\n\n\tif cbp.State > 0 {\n\t\tcbp.State = 1\n\t}\n\n\tcbID, err := wkfSvc.AddOrUpCallback(ctx, cbp)\n\tif err != nil {\n\t\tlog.Error(\"wkfSvc.AddUpCallback(%+v) error(%v)\", cbp, err)\n\t\tctx.JSON(nil, ecode.RequestErr)\n\t\treturn\n\t}\n\n\tctx.JSON(map[string]int32{\n\t\t\"callbackNo\": cbID,\n\t}, nil)\n}\n\nfunc listCallback(ctx *bm.Context) ", "output": "{\n\tctx.JSON(wkfSvc.ListCallback(ctx))\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\n\n\nfunc (c *simpleCache) get(key string) (*cacheRecord, bool) {\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}\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 newSimpleCache(clock clock.Clock) cache ", "output": "{\n\treturn &simpleCache{cache: utilcache.NewExpiringWithClock(clock)}\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\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) Clear(ch chan struct{}) ", "output": "{\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}"} {"input": "package p\n\ntype T int\n\n\n\ntype S struct {\n\tt T\n}\n\nfunc F() {\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}\n\nfunc (t *T) F() T ", "output": "{\n\treturn *t\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\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 DefaultPasswordPrompt(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 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\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) HasBasicAuth() bool ", "output": "{\n\treturn len(c.Username) != 0\n}"} {"input": "package test\n\nimport (\n\t\"strings\"\n\t\"testing\"\n)\n\n\ntype SuiteSuite struct {\n\tSuite\n}\n\n\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\nfunc (t *SuiteSuite) VerifyMethodsWrongSignatureSkipped2() int {\n\tt.Fatalf(\"This should never run.\")\n\treturn 0\n}\n\nfunc TestTestSuite(t *testing.T) ", "output": "{\n\tRunSuite(t, new(SuiteSuite))\n}"} {"input": "package testutil\n\nimport (\n\t\"testing\"\n\n\t. \"github.com/pingcap/check\"\n)\n\n\n\nvar _ = Suite(&testTestUtilSuite{})\n\ntype testTestUtilSuite struct {\n}\n\nfunc (s *testTestUtilSuite) TestCompareUnorderedString(c *C) {\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}\n\nfunc TestT(t *testing.T) ", "output": "{\n\tTestingT(t)\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\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\n\n\nfunc Exec(s string, args ...interface{}) (sql.Result, error) ", "output": "{\n\tres, err := db.Exec(s, args...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn res, nil\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\n\n\n\nfunc (op *BreakFreeReferralOperation) Data() interface{} {\n\treturn op\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) Type() OpType ", "output": "{\n\treturn TypeBreakFreeReferral\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\nfunc (c *simpleCache) get(key string) (*cacheRecord, bool) {\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}\n\nfunc (c *simpleCache) set(key string, value *cacheRecord, ttl time.Duration) {\n\tc.cache.Set(key, value, ttl)\n}\n\n\n\nfunc (c *simpleCache) remove(key string) ", "output": "{\n\tc.cache.Delete(key)\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\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) SetCreationDateTime(value string) ", "output": "{\n\th.CreationDateTime = (*ISODateTime)(&value)\n}"} {"input": "package rtmp\n\nimport \"github.com/winlinvip/go-srs/protocol\"\n\ntype SrsInfo struct {\n SrsVersion string\n SrsServerIp string\n SrsPid int\n SrsId int\n}\n\n\n\nfunc (si *SrsInfo) Parse(args *protocol.Amf0Object) ", "output": "{\n if args == nil {\n return\n }\n\n if v,ok := args.GetString(\"srs_version\"); ok {\n si.SrsVersion = string(v)\n }\n if v,ok := args.GetString(\"srs_server_ip\"); ok {\n si.SrsServerIp = string(v)\n }\n if v,ok := args.GetNumber(\"srs_pid\"); ok {\n si.SrsPid = int(v)\n }\n if v,ok := args.GetNumber(\"srs_id\"); ok {\n si.SrsId = int(v)\n }\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\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 TestProvider_impl(t *testing.T) ", "output": "{\n\tvar _ terraform.ResourceProvider = Provider()\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\n\n\n\n\nfunc NewQueryParamsHandler() types.Middleware {\n\treturn &queryParamsHandler{}\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 (h *queryParamsHandler) Name() string ", "output": "{\n\treturn \"query-params-handler\"\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\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 (i *realCloudInfo) GetCloudProvider() info.CloudProvider ", "output": "{\n\treturn i.cloudProvider\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\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 CannonX(initial float32, rate float32, elap time.Duration) (float32, float32) ", "output": "{\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}"} {"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\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 MigrationExists(db *gorm.DB, migrationName string) bool ", "output": "{\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}"} {"input": "package model\n\nimport \"github.com/gogo/protobuf/proto\"\n\nfunc (p *Packet) MarshalBinary() ([]byte, error) {\n\treturn proto.Marshal(p)\n}\n\n\n\nfunc (p *Packet) UnmarshalBinary(data []byte) error ", "output": "{\n\treturn proto.Unmarshal(data, p)\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\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\nfunc LogMessage(msg []byte, msgType events.LogMessage_MessageType) log_sender.LogChainer {\n\treturn logSender.LogMessage(msg, msgType)\n}\n\nfunc SendAppLog(appID, message, sourceType, sourceInstance string) error ", "output": "{\n\tif logSender == nil {\n\t\treturn nil\n\t}\n\treturn logSender.SendAppLog(appID, message, sourceType, sourceInstance)\n}"} {"input": "package http\n\nimport (\n\t\"github.com/coraldane/falcon-agent/g\"\n\t\"github.com/toolkits/nux\"\n\t\"github.com/toolkits/sys\"\n\t\"net/http\"\n)\n\n\n\nfunc configKernelRoutes() ", "output": "{\n\thttp.HandleFunc(\"/proc/kernel/hostname\", func(w http.ResponseWriter, r *http.Request) {\n\t\tdata, err := g.Hostname()\n\t\tAutoRender(w, data, err)\n\t})\n\n\thttp.HandleFunc(\"/proc/kernel/maxproc\", func(w http.ResponseWriter, r *http.Request) {\n\t\tdata, err := nux.KernelMaxProc()\n\t\tAutoRender(w, data, err)\n\t})\n\n\thttp.HandleFunc(\"/proc/kernel/maxfiles\", func(w http.ResponseWriter, r *http.Request) {\n\t\tdata, err := nux.KernelMaxFiles()\n\t\tAutoRender(w, data, err)\n\t})\n\n\thttp.HandleFunc(\"/proc/kernel/version\", func(w http.ResponseWriter, r *http.Request) {\n\t\tdata, err := sys.CmdOutNoLn(\"uname\", \"-r\")\n\t\tAutoRender(w, data, err)\n\t})\n\n}"} {"input": "package leetcode\n\n\n\nfunc missingNumber(nums []int) int ", "output": "{\n\tsum := len(nums)\n\tfor i, n := range nums {\n\t\tsum += i - n\n\t}\n\treturn sum\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\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\nfunc init() {\n\tsha2.RegisterAlgorithm(\"simd\", func() sha2.SumNumberAlgorithm {\n\t\treturn &generator{}\n\t})\n}\n\nfunc (g *generator) Sum256Number(data []byte) int64 ", "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.SumToNum256(start[:])\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\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\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 init() ", "output": "{\n\tcli.Register(\"host.account.update\", &update{})\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\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) 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 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\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 TestArtifactId(t *testing.T) ", "output": "{\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}"} {"input": "package iso20022\n\n\ntype RepairReason9Choice struct {\n\n\tCode *RepairReason7Code `xml:\"Cd\"`\n\n\tProprietary *GenericIdentification38 `xml:\"Prtry\"`\n}\n\n\n\nfunc (r *RepairReason9Choice) AddProprietary() *GenericIdentification38 {\n\tr.Proprietary = new(GenericIdentification38)\n\treturn r.Proprietary\n}\n\nfunc (r *RepairReason9Choice) SetCode(value string) ", "output": "{\n\tr.Code = (*RepairReason7Code)(&value)\n}"} {"input": "package runtime\n\nimport \"unsafe\"\n\nvar TestingWER = &testingWER\n\n\n\nfunc NumberOfProcessors() int32 ", "output": "{\n\tvar info systeminfo\n\tstdcall1(_GetSystemInfo, uintptr(unsafe.Pointer(&info)))\n\treturn int32(info.dwnumberofprocessors)\n}"} {"input": "package pktcls\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/antlr/antlr4/runtime/Go/antlr\"\n\n\t\"github.com/scionproto/scion/go/lib/log\"\n)\n\ntype ErrorListener struct {\n\t*antlr.DefaultErrorListener\n\tmsg string\n\terrorType string\n}\n\n\n\nfunc (l *ErrorListener) SyntaxError(recognizer antlr.Recognizer, offendingSymbol interface{}, line,\n\tcolumn int, msg string, e antlr.RecognitionException) ", "output": "{\n\tl.msg = msg\n\tlog.Debug(fmt.Sprintf(\"%s Error\", l.errorType), \"err\", msg)\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\nfunc NewReloadBookHandler(books *types.Books, index string) *ReloadBook {\n\treturn &ReloadBook{books: books, index: index}\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\n\n\nfunc (rk *ReloadKeyword) ServeHTTP(w http.ResponseWriter, r *http.Request) ", "output": "{\n\trk.store = fetch.F1Indexes(rk.books, rk.store)\n\n\tstat := rk.store.GetStatistics()\n\tjson.NewEncoder(w).Encode(stat)\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\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 New(c rest.Interface) *ExampleV1Client ", "output": "{\n\treturn &ExampleV1Client{c}\n}"} {"input": "package popcount1_test\n\nimport (\n \"testing\"\n\n \"ch02/popcount\"\n \"ch02/popcount1\"\n)\n\n\n\nfunc BenchmarkPopCount1(b *testing.B) {\n for i := 0; i < b.N; i++ {\n popcount1.PopCount(0x1234567890ABCDEF)\n }\n}\n\nfunc BenchmarkPopCount(b *testing.B) ", "output": "{\n for i := 0; i < b.N; i++ {\n popcount.PopCount(0x1234567890ABCDEF)\n }\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\n\n\nfunc (h *LogErrorHandler) Handle(ctx context.Context, err error) {\n\th.logger.Log(\"err\", err)\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 NewLogErrorHandler(logger log.Logger) *LogErrorHandler ", "output": "{\n\treturn &LogErrorHandler{\n\t\tlogger: logger,\n\t}\n}"} {"input": "package blake2b\n\n\n\nfunc hashBlocks(h *[8]uint64, c *[2]uint64, flag uint64, blocks []byte) ", "output": "{\n\thashBlocksGeneric(h, c, flag, blocks)\n}"} {"input": "package dynamic\n\nimport (\n\t\"sync\"\n\n\t\"k8s.io/client-go/1.5/pkg/api\"\n\t\"k8s.io/client-go/1.5/pkg/api/unversioned\"\n\t\"k8s.io/client-go/1.5/pkg/runtime\"\n\t\"k8s.io/client-go/1.5/pkg/runtime/serializer\"\n\t\"k8s.io/client-go/1.5/rest\"\n)\n\n\ntype ClientPool interface {\n\tClientForGroupVersion(groupVersion unversioned.GroupVersion) (*Client, error)\n}\n\n\ntype APIPathResolverFunc func(groupVersion unversioned.GroupVersion) string\n\n\nfunc LegacyAPIPathResolverFunc(groupVersion unversioned.GroupVersion) string {\n\tif len(groupVersion.Group) == 0 {\n\t\treturn \"/api\"\n\t}\n\treturn \"/apis\"\n}\n\n\ntype clientPoolImpl struct {\n\tlock sync.RWMutex\n\tconfig *rest.Config\n\tclients map[unversioned.GroupVersion]*Client\n\tapiPathResolverFunc APIPathResolverFunc\n}\n\n\nfunc NewClientPool(config *rest.Config, apiPathResolverFunc APIPathResolverFunc) ClientPool {\n\tconfCopy := *config\n\treturn &clientPoolImpl{\n\t\tconfig: &confCopy,\n\t\tclients: map[unversioned.GroupVersion]*Client{},\n\t\tapiPathResolverFunc: apiPathResolverFunc,\n\t}\n}\n\n\n\n\nfunc (c *clientPoolImpl) ClientForGroupVersion(groupVersion unversioned.GroupVersion) (*Client, error) ", "output": "{\n\tc.lock.Lock()\n\tdefer c.lock.Unlock()\n\n\tif existingClient, found := c.clients[groupVersion]; found {\n\t\treturn existingClient, nil\n\t}\n\n\tconfCopy := *c.config\n\tconf := &confCopy\n\n\tconf.APIPath = c.apiPathResolverFunc(groupVersion)\n\n\tconf.GroupVersion = &groupVersion\n\n\tif conf.NegotiatedSerializer == nil {\n\t\tstreamingInfo, _ := api.Codecs.StreamingSerializerForMediaType(\"application/json;stream=watch\", nil)\n\t\tconf.NegotiatedSerializer = serializer.NegotiatedSerializerWrapper(runtime.SerializerInfo{Serializer: dynamicCodec{}}, streamingInfo)\n\t}\n\n\tdynamicClient, err := NewClient(conf)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tc.clients[groupVersion] = dynamicClient\n\treturn dynamicClient, nil\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\nfunc (o *mapTransformer) Transform(m resmap.ResMap) error {\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}\n\n\n\nfunc (o *mapTransformer) addMap(in interface{}) (interface{}, error) ", "output": "{\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}"} {"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()) }\n\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 HexTo_N_(s string) _N_ ", "output": "{ return BytesTo_N_(FromHex(s)) }"} {"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\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\n\n\nfunc (s *Server) internalError(r *http.Request, w http.ResponseWriter, err error, msg string) ", "output": "{\n\ts.serveError(w, err, msg, \"Internal Server Error\", http.StatusInternalServerError)\n\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\nfunc TestCommunicator_impl(t *testing.T) {\n\tvar _ packer.Communicator = new(Communicator)\n}\n\n\n\nfunc TestCommunicator(t *testing.T) ", "output": "{\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}"} {"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\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\n\n\nfunc SetOrFail(ctx context.Context, t fail, key string, value interface{}) ", "output": "{\n\tstate := FromContext(ctx)\n\tif err := state.Set(ctx, key, value); err != nil {\n\t\tt.Error(err)\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\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 index(w http.ResponseWriter, r *http.Request) ", "output": "{\n\tfmt.Fprintf(w, \"Welcome to the home page!\")\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\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 fileWalkWorker(ft *FileWalk) ", "output": "{\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}"} {"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\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\nfunc init() {\n\tRegisterResource(\"compose\", composeFromConfig)\n}\n\nfunc (c *ComposeConfig) StopGraceString() string ", "output": "{\n\treturn strconv.Itoa(c.StopGrace)\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\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 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\nfunc (button *Button) AddEventListener(event string, responseChannel chan string) {\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}\n\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) RemoveEventListener(event string, listenerChannel chan string) ", "output": "{\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}"} {"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\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\n\n\nfunc GeneratePrivateRegistryDockerConfig(privateRegistry *rketypes.PrivateRegistry) (string, error) ", "output": "{\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}"} {"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\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 chown(paths []string, userName string, groupName string) error ", "output": "{\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}"} {"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\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) MarshalJSON() ([]byte, error) ", "output": "{\n\treturn json.Marshal(o.value)\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\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\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) ServeHTTPNext(inner 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\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}"} {"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\n\n\nfunc (s *Serial) EncodeAndOverwrite(file OverwriteableFile, outData interface{}) error {\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}\n\nfunc (s *Serial) DecodeAll(file io.ReadSeeker, outData interface{}) error ", "output": "{\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}"} {"input": "package eventgrid\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() + \" eventgrid/2019-02-01-preview\"\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\n\n\nfunc StartHttpCollector(kind, address string, l *logtap.Logtap) (io.Closer, error) {\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}\n\nfunc GenerateHttpCollector(kind string, l *logtap.Logtap) http.HandlerFunc ", "output": "{\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}"} {"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\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 (cm *CallbackMetric) Desc() *prometheus.Desc ", "output": "{\n\treturn cm.desc\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\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 TestChanSendSelectBarrier(t *testing.T) ", "output": "{\n\ttestChanSendBarrier(true)\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\nfunc Create(regionName string, size int) (sh SharedMemory, err error) {\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}\n\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 Open(regionName string) (sh SharedMemory, err error) ", "output": "{\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}"} {"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\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 (s pushStep) Take(i *Runtime) error ", "output": "{\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}"} {"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\n\n\nfunc (tp *fakeTargetProvider) Sources() []string {\n\treturn tp.sources\n}\n\nfunc (tp *fakeTargetProvider) Run(ch chan<- *config.TargetGroup, done <-chan struct{}) ", "output": "{\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}"} {"input": "package iso20022\n\n\ntype GovernanceIdentification1Choice struct {\n\n\tCode *GovernanceIdentification1Code `xml:\"Cd\"`\n\n\tProprietary *GenericIdentification1 `xml:\"Prtry\"`\n}\n\n\n\nfunc (g *GovernanceIdentification1Choice) AddProprietary() *GenericIdentification1 {\n\tg.Proprietary = new(GenericIdentification1)\n\treturn g.Proprietary\n}\n\nfunc (g *GovernanceIdentification1Choice) SetCode(value string) ", "output": "{\n\tg.Code = (*GovernanceIdentification1Code)(&value)\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\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\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) IsAbstract() bool ", "output": "{\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}"} {"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\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\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 (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 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\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) SetAmount(value, currency string) ", "output": "{\n\to.Amount = NewActiveOrHistoricCurrencyAndAmount(value, currency)\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\nfunc (this *SafeHostGroupsMap) GetGroupIds(hid int) ([]int, bool) {\n\tthis.RLock()\n\tdefer this.RUnlock()\n\tgids, exists := this.M[hid]\n\treturn gids, exists\n}\n\n\n\nfunc (this *SafeHostGroupsMap) Init() ", "output": "{\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}"} {"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\n\n\nfunc (t *AuthenticationRoute) HandleLogout(w http.ResponseWriter, r *http.Request){\n\ttoken := GetAuthtokenFromRequest(r)\n\tt.tokenStore.Remove(token.Token)\n}\n\nfunc (t *AuthenticationRoute) HandleLogin(w http.ResponseWriter, r *http.Request)", "output": "{\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}"} {"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\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 Trace(title string, data M) ", "output": "{\n\tlogWithLevel(title, kayvee.Trace, data)\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n)\n\n\n\nfunc power_3_digits_test(n int) bool {\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}\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 number_3_digits_test(n int) bool ", "output": "{\n\treturn (n > 99 && n < 1000)\n}"} {"input": "package main\n\nimport \"fmt\"\n\n\n\nfunc main() {\n f(\"direct\")\n go f(\"goroutine\")\n go func(msg string) {\n fmt.Print(msg)\n }(\"going\")\n \n var input string\n fmt.Scanln(&input)\n fmt.Println(\"done\")\n}\n\nfunc f(from string) ", "output": "{\n for i := 0; i<3; i++ {\n \tfmt.Println(from, \":\",i)\n }\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}\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) Message() string ", "output": "{\n\treturn \"the message\"\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\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\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) Compare(a, b []byte) int ", "output": "{\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}"} {"input": "package go_n1ql\n\ntype n1qlResult struct {\n\taffectedRows int64\n\tinsertId int64\n}\n\nfunc (res *n1qlResult) LastInsertId() (int64, error) {\n\treturn res.insertId, nil\n}\n\n\n\nfunc (res *n1qlResult) RowsAffected() (int64, error) ", "output": "{\n\treturn res.affectedRows, nil\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\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 (monitor *Monitor) Enter(thread interface{}) ", "output": "{\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}"} {"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\nfunc NewIndexController(common *ControllerCommon,\n) *ControllerIndex {\n\treturn &ControllerIndex{\n\t\tControllerCommon: common,\n\t}\n}\n\n\n\nfunc (c *ControllerIndex) Index(ctx echo.Context) error ", "output": "{\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}"} {"input": "package stream\n\nimport (\n\t\"fmt\"\n\t\"os\"\n)\n\nvar debugEnabled bool = false\n\n\n\n\nfunc debug(format string, args ...interface{}) {\n\tif debugEnabled {\n\t\tfmt.Fprintf(os.Stderr, \"rpc/dataconn/stream: %s\\n\", fmt.Sprintf(format, args...))\n\t}\n}\n\nfunc init() ", "output": "{\n\tif os.Getenv(\"ZREPL_RPC_DATACONN_STREAM_DEBUG\") != \"\" {\n\t\tdebugEnabled = true\n\t}\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\nfunc MustReadServerConfig(path string) *ServerConfig {\n\tconfig, err := ReadServerConfig(path)\n\tif err != nil {\n\t\tpanic(\"unable to read config: \" + err.Error())\n\t}\n\treturn config\n}\n\n\n\n\nfunc ReadServerConfig(path string) (*ServerConfig, error) ", "output": "{\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}"} {"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\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 (ic imagecache) put(hsh hashcode, png []byte) ", "output": "{\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}"} {"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\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) LocalAddr() 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 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\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) SetJwt(v string) ", "output": "{\n\tm.Identity = &CreateIamTokenRequest_Jwt{\n\t\tJwt: v,\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\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\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) Help() string ", "output": "{\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}"} {"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\n\n\nfunc TestFortiGateStopRadiusPacket(t *testing.T) {\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}\n\nfunc TestFortiGateStartRadiusPacket(t *testing.T) ", "output": "{\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}"} {"input": "package main\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"strings\"\n)\n\nconst (\n\tsemanticAlphabet = \"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-\"\n\n\tsemanticBuildAlphabet = \"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-.\"\n)\n\n\n\nconst (\n\tAppName string = \"dcrdata\"\n\tAppMajor uint = 6\n\tAppMinor uint = 1\n\tAppPatch uint = 0\n)\n\n\nvar (\n\tappPreRelease = \"pre\"\n\n\tappBuild = \"dev\"\n)\n\n\n\nfunc Version() string {\n\tversion := fmt.Sprintf(\"%d.%d.%d\", AppMajor, AppMinor, AppPatch)\n\n\tpreRelease := normalizePreRelString(appPreRelease)\n\tif preRelease != \"\" {\n\t\tversion = fmt.Sprintf(\"%s-%s\", version, preRelease)\n\t}\n\n\tbuild := normalizeBuildString(appBuild)\n\tif build != \"\" {\n\t\tversion = fmt.Sprintf(\"%s+%s\", version, build)\n\t}\n\n\treturn version\n}\n\n\n\nfunc normalizeSemString(str, alphabet string) string {\n\tvar result bytes.Buffer\n\tfor _, r := range str {\n\t\tif strings.ContainsRune(alphabet, r) {\n\t\t\tresult.WriteRune(r)\n\t\t}\n\t}\n\treturn result.String()\n}\n\n\n\n\n\n\n\n\n\n\n\nfunc normalizeBuildString(str string) string {\n\treturn normalizeSemString(str, semanticBuildAlphabet)\n}\n\nfunc normalizePreRelString(str string) string ", "output": "{\n\treturn normalizeSemString(str, semanticAlphabet)\n}"} {"input": "package sqlmock\n\nimport (\n\t\"database/sql/driver\"\n\t\"testing\"\n\t\"time\"\n)\n\ntype AnyTime struct{}\n\n\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\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 (a AnyTime) Match(v driver.Value) bool ", "output": "{\n\t_, ok := v.(time.Time)\n\treturn ok\n}"} {"input": "package slack\n\nimport (\n\t\"flag\"\n\t\"testing\"\n\n\t\"github.com/google/go-cmp/cmp\"\n)\n\n\n\nfunc TestHostsFlag(t *testing.T) ", "output": "{\n\tvar testArg HostsFlag\n\tflags := flag.NewFlagSet(\"foo\", flag.PanicOnError)\n\tflags.Var(&testArg, \"test-arg\", \"\")\n\tif err := flags.Parse([]string{\"--test-arg\", \"a=b\"}); err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif diff := cmp.Diff(HostsFlag(map[string]string{\"a\": \"b\"}), testArg); diff != \"\" {\n\t\tt.Fatalf(\"Arg parsing mismatch. Want(-), got(+):\\n%s\", diff)\n\t}\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\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) Calls() uint64 ", "output": "{\n\tif state != nil {\n\t\treturn state.sampleCount\n\t}\n\treturn 0\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\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\n\n\nfunc (l *CertPolicyOVRequiresProvinceOrLocal) Execute(cert *x509.Certificate) *lint.LintResult ", "output": "{\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}"} {"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\nfunc (c *CmdDomainDel) Synopsis() string {\n\treturn \"Delete and backup a domain.\"\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\n\n\nfunc (c *CmdDomainDel) Run(args []string) int ", "output": "{\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}"} {"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\nfunc StopTokenFilterConstructor(config map[string]interface{}, cache *registry.Cache) (analysis.TokenFilter, error) {\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}\n\n\n\nfunc init() ", "output": "{\n\tregistry.RegisterTokenFilter(StopName, StopTokenFilterConstructor)\n}"} {"input": "package fuzztraversal\n\nimport (\n\t\"github.com/hashicorp/hcl2/hcl\"\n\t\"github.com/hashicorp/hcl2/hcl/hclsyntax\"\n)\n\n\n\nfunc Fuzz(data []byte) int ", "output": "{\n\t_, diags := hclsyntax.ParseTraversalAbs(data, \"\", hcl.Pos{Line: 1, Column: 1})\n\n\tif diags.HasErrors() {\n\t\treturn 0\n\t}\n\n\treturn 1\n}"} {"input": "package nsqlookupd\n\nimport (\n\t\"net\"\n)\n\ntype ClientV1 struct {\n\tnet.Conn\n\tpeerInfo *PeerInfo\n}\n\n\n\nfunc (c *ClientV1) String() string {\n\treturn c.RemoteAddr().String()\n}\n\nfunc NewClientV1(conn net.Conn) *ClientV1 ", "output": "{\n\treturn &ClientV1{\n\t\tConn: conn,\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\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 (t *RewriteTransport) RoundTrip(req *http.Request) (*http.Response, error) ", "output": "{\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}"} {"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\n\n\n\nfunc TotalTicksAvailable() float64 {\n\treturn cpuTotalTicks\n}\n\nfunc CPUModelName() string ", "output": "{\n\treturn cpuModelName\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\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\n\n\nfunc (y YLocus) Self() *Peer ", "output": "{\n\treturn y.X.Call(\"Self\")[0].(*Peer)\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\n\n\n\nfunc DefMDIChildProc(hWnd uintptr, uMsg uintptr, wParam uintptr, lParam uintptr) (uintptr, error) {\n\tr1, _, err := procDefMDIChildProc.Call(hWnd, uMsg, wParam, lParam)\n\treturn r1, err\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 DefFrameProc(hWnd uintptr, hWndMDIClient uintptr, uMsg uintptr, wParam uintptr, lParam uintptr) (uintptr, error) ", "output": "{\n\tr1, _, err := procDefFrameProc.Call(hWnd, hWndMDIClient, uMsg, wParam, lParam)\n\treturn r1, err\n}"} {"input": "package appstream_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/appstream\"\n)\n\nvar _ aws.Config\nvar _ awserr.Error\nvar _ request.Request\n\n\n\nfunc TestInteg_00_DescribeStacks(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 := appstream.New(sess)\n\tparams := &appstream.DescribeStacksInput{}\n\t_, err := svc.DescribeStacksWithContext(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 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\n\n\nfunc TestFormatWithLineNo(t *testing.T) {\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}\n\nfunc TestFormatBytes(t *testing.T) ", "output": "{\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}"} {"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\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) WaitUntilConnectionCloses() ", "output": "{\n\tc.Called()\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\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 (e *ExtendedAgentSignerWrapper) Sign(rand io.Reader, data []byte) (*ssh.Signature, error) ", "output": "{\n\treturn e.Signer.SignWithOpts(rand, data, e.Opts)\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\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) Get(c context.Context, req *projects.GetRequest) (*projects.Config, error) ", "output": "{\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}"} {"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\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) DeleteChain(table iptables.Table, chain iptables.Chain) error ", "output": "{\n\treturn nil\n}"} {"input": "package utils\n\nimport (\n\t\"crypto/rand\"\n\t\"fmt\"\n)\n\n\n\nfunc RandomHexString(byteLength uint32) (str string, err error) ", "output": "{\n\tslice := make([]byte, byteLength)\n\tif _, err = rand.Read(slice); err == nil {\n\t\tstr = fmt.Sprintf(\"%x\", slice)\n\t}\n\treturn\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\nfunc run(params service.CollectorSettings) error {\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}\n\n\n\nfunc runService(params service.CollectorSettings) error ", "output": "{\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}"} {"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\nfunc (_m *MockEventMonitor) IsActive() bool {\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}\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) Subscribe(ID string) (*docker.Subscription, error) ", "output": "{\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}"} {"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\nfunc read1(path string) string {\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}\n\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 read2(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\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}"} {"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\n\n\n\n\nfunc (b *ListBuilder) WithFilter(pred ...Predicate) *ListBuilder {\n\tb.filters = append(b.filters, pred...)\n\treturn b\n}\n\nfunc (b *ListBuilder) List() *PodList ", "output": "{\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}"} {"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\n\n\n\nfunc Version() string {\n\treturn version.Number\n}\n\nfunc UserAgent() string ", "output": "{\n\treturn \"Azure-SDK-For-Go/\" + version.Number + \" managedservices/2019-04-01-preview\"\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\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(\"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}\n\nfunc (f *genericInformer) Informer() cache.SharedIndexInformer ", "output": "{\n\treturn f.informer\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\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 assertInt(t *testing.T, expect, got int) ", "output": "{\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}"} {"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\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\nfunc (m *memconn) Addr() net.Addr {\n\treturn m.addr\n}\n\nfunc (m *memconn) Dial() (net.Conn, error) ", "output": "{\n\tr, w := pipe(&m.addr, m.pool)\n\tgo func() {\n\t\tm.chcn <- r\n\t}()\n\treturn w, nil\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\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\n\n\nfunc TestObservationRunSetsValues(t *testing.T) ", "output": "{\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}"} {"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\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\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 NewTemplateRenderer() handlers.TemplateRenderer ", "output": "{\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}"} {"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\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 (sr *ServiceResource) RegMicroApp(c *gin.Context) ", "output": "{\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}"} {"input": "package floatingips\n\nimport \"github.com/gophercloud/gophercloud\"\n\nconst resourcePath = \"floatingips\"\n\n\n\nfunc resourceURL(c *gophercloud.ServiceClient, id string) string {\n\treturn c.ServiceURL(resourcePath, id)\n}\n\nfunc rootURL(c *gophercloud.ServiceClient) string ", "output": "{\n\treturn c.ServiceURL(resourcePath)\n}"} {"input": "package netchan\n\nimport (\n\t\"net/url\"\n\t\"testing\"\n\t\"time\"\n)\n\n\n\nfunc TestWsTransport(t *testing.T) ", "output": "{\n\tmarshaler := NewJsonMarshaler()\n\ttransport := NewWsTransport(\n\t\tmarshaler,\n\t\t&url.URL{\n\t\t\tScheme: \"ws\",\n\t\t\tHost: \":25000\",\n\t\t},\n\t\tnil,\n\t\tnil)\n\tdefer func() {\n\t\ttransport.Close()\n\t\ttime.Sleep(100 * time.Millisecond)\n\t}()\n\n\ttestTransport(t, transport, \"ws\")\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\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 Fatalf(format string, args ...interface{}) ", "output": "{\n\tlogger.Fatalf(format, args...)\n\tos.Exit(1)\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\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) validateGroupID(formats strfmt.Registry) error ", "output": "{\n\n\tif swag.IsZero(m.GroupID) { \n\t\treturn nil\n\t}\n\n\treturn nil\n}"} {"input": "package api\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"net/http\"\n)\n\n\ntype Response struct {\n\tResult string `json:\"result\"`\n\tErrorType string `json:\"error_type\"`\n\tMessage string `json:\"message\"`\n\tInfo Info\n\tBody []byte\n}\n\n\ntype Info struct {\n\tSitename string `json:\"sitename\"`\n\tHits int32 `json:\"hits\"`\n\tCreatedAt string `json:\"created_at\"`\n\tLastUpdated string `json:\"last_updated\"`\n\tDomain string `json:\"domain\"`\n\tTags []string `json:\"tags\"`\n}\n\n\n\n\n\nfunc (r *Response) Print() {\n\tfmt.Println(\"Result: \", r.Result)\n\n\tif r.ErrorType != \"\" {\n\t\tfmt.Println(\"ErrorType:\", r.ErrorType)\n\t}\n\n\tfmt.Println(\"Message: \", r.Message)\n}\n\nfunc (r *Response) PopulateFromHTTPResponse(res *http.Response) error ", "output": "{\n\tbody, err := ioutil.ReadAll(res.Body)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer res.Body.Close()\n\n\terr = json.Unmarshal(body, &r)\n\n\tr.Body = body\n\n\treturn err\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\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\n\n\nfunc NewQueueTask(redisValue string) (task QueueTask, err error) ", "output": "{\n\treader := strings.NewReader(redisValue)\n\tparser := json.NewDecoder(reader)\n\terr = parser.Decode(&task)\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\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\nfunc (f *frame) Reset() {\n\tf.SetSlaveName(\"\")\n\tf.SetData(nil)\n\tf.SetProgress(0)\n\tf.SetCompleted(false)\n}\n\nfunc (f *frame) Job() *job ", "output": "{\n\treturn f.job\n}"} {"input": "package routes\n\nimport (\n\t\"net/http\"\n\n\trestful \"github.com/emicklei/go-restful\"\n\n\t\"k8s.io/klog/v2\"\n\t\"k8s.io/kubernetes/pkg/serviceaccount\"\n)\n\n\n\n\n\n\nconst (\n\theaderCacheControl = \"Cache-Control\"\n\tcacheControl = \"public, max-age=3600\" \n\n\tmimeJWKS = \"application/jwk-set+json\"\n)\n\n\ntype OpenIDMetadataServer struct {\n\tconfigJSON []byte\n\tkeysetJSON []byte\n}\n\n\n\n\nfunc NewOpenIDMetadataServer(configJSON, keysetJSON []byte) *OpenIDMetadataServer {\n\treturn &OpenIDMetadataServer{\n\t\tconfigJSON: configJSON,\n\t\tkeysetJSON: keysetJSON,\n\t}\n}\n\n\n\n\n\nfunc fromStandard(h http.HandlerFunc) restful.RouteFunction {\n\treturn func(req *restful.Request, resp *restful.Response) {\n\t\th(resp, req.Request)\n\t}\n}\n\nfunc (s *OpenIDMetadataServer) serveConfiguration(w http.ResponseWriter, req *http.Request) {\n\tw.Header().Set(restful.HEADER_ContentType, restful.MIME_JSON)\n\tw.Header().Set(headerCacheControl, cacheControl)\n\tif _, err := w.Write(s.configJSON); err != nil {\n\t\tklog.Errorf(\"failed to write service account issuer metadata response: %v\", err)\n\t\treturn\n\t}\n}\n\nfunc (s *OpenIDMetadataServer) serveKeys(w http.ResponseWriter, req *http.Request) {\n\tw.Header().Set(restful.HEADER_ContentType, mimeJWKS)\n\tw.Header().Set(headerCacheControl, cacheControl)\n\tif _, err := w.Write(s.keysetJSON); err != nil {\n\t\tklog.Errorf(\"failed to write service account issuer JWKS response: %v\", err)\n\t\treturn\n\t}\n}\n\nfunc (s *OpenIDMetadataServer) Install(c *restful.Container) ", "output": "{\n\tcfg := new(restful.WebService).\n\t\tProduces(restful.MIME_JSON)\n\n\tcfg.Path(serviceaccount.OpenIDConfigPath).Route(\n\t\tcfg.GET(\"\").\n\t\t\tTo(fromStandard(s.serveConfiguration)).\n\t\t\tDoc(\"get service account issuer OpenID configuration, also known as the 'OIDC discovery doc'\").\n\t\t\tOperation(\"getServiceAccountIssuerOpenIDConfiguration\").\n\t\t\tReturns(http.StatusOK, \"OK\", \"\"))\n\tc.Add(cfg)\n\n\tjwks := new(restful.WebService).\n\t\tProduces(mimeJWKS)\n\n\tjwks.Path(serviceaccount.JWKSPath).Route(\n\t\tjwks.GET(\"\").\n\t\t\tTo(fromStandard(s.serveKeys)).\n\t\t\tDoc(\"get service account issuer OpenID JSON Web Key Set (contains public token verification keys)\").\n\t\t\tOperation(\"getServiceAccountIssuerOpenIDKeyset\").\n\t\t\tReturns(http.StatusOK, \"OK\", \"\"))\n\tc.Add(jwks)\n}"} {"input": "package buildserver\n\nimport (\n\t\"encoding/json\"\n\t\"net/http\"\n\n\t\"github.com/concourse/atc\"\n\t\"github.com/concourse/atc/api/present\"\n)\n\n\n\nfunc (s *Server) ListBuilds(w http.ResponseWriter, r *http.Request) ", "output": "{\n\tbuilds, err := s.db.GetAllBuilds()\n\tif err != nil {\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tw.WriteHeader(http.StatusOK)\n\n\tatc := make([]atc.Build, len(builds))\n\tfor i := 0; i < len(builds); i++ {\n\t\tatc[i] = present.Build(builds[i])\n\t}\n\n\tjson.NewEncoder(w).Encode(atc)\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\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\n\n\nfunc ExampleErrIfNotJSON() ", "output": "{\n\tfmt.Println(\"Good is nil:\", ErrIfNotJSON(json.RawMessage(\"{}\"), \"my-field\") == nil)\n\tfmt.Println(\"Bad:\", ErrIfNotJSON(json.RawMessage(\"\"), \"my-field\"))\n\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\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\n\n\nfunc TestCheckVolumeUsage_Error(t *testing.T) ", "output": "{\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}"} {"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\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\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 (r Response) String() string ", "output": "{\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}"} {"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\nfunc (s *EnvSuite) SetUpSuite(c *C) {\n\ts.environ = os.Environ()\n}\n\nfunc (s *EnvSuite) SetUpTest(c *C) {\n\tos.Clearenv()\n}\n\n\n\nfunc (s *EnvSuite) TearDownSuite(c *C) {\n}\n\nfunc (s *EnvSuite) TearDownTest(c *C) ", "output": "{\n\tfor _, envstring := range s.environ {\n\t\tkv := strings.SplitN(envstring, \"=\", 2)\n\t\tos.Setenv(kv[0], kv[1])\n\t}\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\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 (m *jsonMessage) Bytes() json.RawMessage ", "output": "{\n\treturn m.data\n}"} {"input": "package goyeppp\n\nimport (\n\t\"testing\"\n)\n\n\n\nfunc TestVersion(t *testing.T) ", "output": "{\n\tt.Logf(\"Yeppp major version: %v\\n\", MajorVersion())\n\tt.Logf(\"Yeppp minor version: %v\\n\", MinorVersion())\n\tt.Logf(\"Yeppp patch version: %v\\n\", PatchVersion())\n\tt.Logf(\"Yeppp build version: %v\\n\", BuildVersion())\n\tt.Logf(\"Yeppp release name: %v\\n\", ReleaseName())\n\tt.Logf(\"Yeppp full name: %v\\n\", FullName())\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\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\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 ioc(dir, t, nr, size uintptr) uintptr ", "output": "{\n\treturn (dir << directionShift) | (t << typeShift) | (nr << numberShift) | (size << sizeShift)\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\nfunc (r *FieldValueSetRequest) Get(ctx context.Context) (resObj *FieldValueSet, err error) {\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}\n\n\n\n\n\nfunc (r *FieldValueSetRequest) Delete(ctx context.Context) error {\n\treturn r.JSONRequest(ctx, \"DELETE\", \"\", nil, nil)\n}\n\nfunc (r *FieldValueSetRequest) Update(ctx context.Context, reqObj *FieldValueSet) error ", "output": "{\n\treturn r.JSONRequest(ctx, \"PATCH\", \"\", reqObj, nil)\n}"} {"input": "package ipc\n\n\n\n\n\n\n\nimport (\n\t\"errors\"\n\t\"encoding/base64\"\n)\n\n\n\n\n\n\n\nfunc ErrorFromBase64EncodedErrorMessage(errorMessage64 string) error {\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}\n\nfunc ErrorFromErrorMessage(errorMessage string) error ", "output": "{\n\tif errorMessage == \"\" {\n\t\treturn nil\n\t}\n\n\treturn errors.New(errorMessage)\n}"} {"input": "package cli_test\n\nimport (\n\t\"flag\"\n\t\"testing\"\n\n\t\"github.com/zeroed/escli/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, nil)\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, nil)\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 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\nfunc unlockpt(f *os.File) error {\n\tvar u int32\n\treturn ioctl(f.Fd(), unix.TIOCSPTLCK, uintptr(unsafe.Pointer(&u)))\n}\n\n\n\n\nfunc ptsname(f *os.File) (string, error) ", "output": "{\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}"} {"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\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) SetFlags(f *gnuflag.FlagSet) ", "output": "{\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}"} {"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\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\nfunc (d *DirectDebitTransaction1) SetPreNotificationDate(value string) {\n\td.PreNotificationDate = (*ISODate)(&value)\n}\n\nfunc (d *DirectDebitTransaction1) AddMandateRelatedInformation() *MandateRelatedInformation1 ", "output": "{\n\td.MandateRelatedInformation = new(MandateRelatedInformation1)\n\treturn d.MandateRelatedInformation\n}"} {"input": "package command\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/urfave/cli\"\n)\n\n\n\nfunc (f *CommandFactory) Upgrade() cli.Command ", "output": "{\n\treturn cli.Command{\n\t\tName: \"upgrade\",\n\t\tUsage: \"upgrade a Layer0 instance to a new version\",\n\t\tArgsUsage: \"NAME VERSION\",\n\t\tFlags: []cli.Flag{\n\t\t\tcli.BoolFlag{\n\t\t\t\tName: \"force\",\n\t\t\t\tUsage: \"skips confirmation prompt\",\n\t\t\t},\n\t\t},\n\t\tAction: func(c *cli.Context) error {\n\t\t\targs, err := extractArgs(c.Args(), \"NAME\", \"VERSION\")\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tinstance := f.NewInstance(args[\"NAME\"])\n\t\t\tif err := instance.Upgrade(args[\"VERSION\"], c.Bool(\"force\")); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tfmt.Printf(\"Everything looks good! You are now ready to run 'l0-setup apply %s'\\n\", args[\"NAME\"])\n\t\t\treturn nil\n\t\t},\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\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\n\n\nfunc HandleErrorPanic(err *error, functionName string) ", "output": "{\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}"} {"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\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 TestUnmarshalling(t *testing.T) ", "output": "{\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}"} {"input": "package tests\n\nimport (\n\t\"encoding/json\"\n\t\"io/ioutil\"\n\t\"os\"\n\n\t\"kubevirt.io/kubevirt/tests/flags\"\n)\n\n\ntype KubeVirtTestsConfiguration struct {\n\tStorageClassLocal string `json:\"storageClassLocal\"`\n\tStorageClassHostPath string `json:\"storageClassHostPath\"`\n\tStorageClassBlockVolume string `json:\"storageClassBlockVolume\"`\n\tStorageClassRhel string `json:\"storageClassRhel\"`\n\tStorageClassWindows string `json:\"storageClassWindows\"`\n\tManageStorageClasses bool `json:\"manageStorageClasses\"`\n}\n\n\n\nfunc loadConfig() (*KubeVirtTestsConfiguration, error) ", "output": "{\n\tjsonFile, err := os.Open(flags.ConfigFile)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdefer jsonFile.Close()\n\n\tbyteValue, _ := ioutil.ReadAll(jsonFile)\n\n\tconfig := &KubeVirtTestsConfiguration{}\n\terr = json.Unmarshal(byteValue, config)\n\n\treturn config, err\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\n\n\n\n\nfunc (f *sharedInformerFactory) ForResource(resource schema.GroupVersionResource) (GenericInformer, error) {\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}\n\nfunc (f *genericInformer) Lister() cache.GenericLister ", "output": "{\n\treturn cache.NewGenericLister(f.Informer().GetIndexer(), f.resource)\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\n\n\n\nfunc Store(ctx context.Context, entry *logrus.Entry) context.Context {\n\tif entry == nil {\n\t\tpanic(\"nil logger given\")\n\t}\n\treturn context.WithValue(ctx, ctxKey, entry)\n}\n\nfunc FromContext(ctx context.Context) (*logrus.Entry, bool) ", "output": "{\n\ti, ok := ctx.Value(ctxKey).(*logrus.Entry)\n\treturn i, ok\n}"} {"input": "package media\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 + \" media/2018-06-01-preview\"\n}\n\n\n\n\nfunc Version() string ", "output": "{\n\treturn version.Number\n}"} {"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\nfunc allFilesExist(dir string, filenames []string) bool {\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}\n\n\n\n\n\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 copyAllFiles(sourceDirs []string, sourceFiles []string, dest string) (string, error) ", "output": "{\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}"} {"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\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\n\n\nfunc storeEnvironment(client ETCDInterface, env Environment, dir string) error ", "output": "{\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}"} {"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\nfunc (b Broker) Unsubscribe(c chan Event) {\n\tb.unsub <- sub{events: c}\n}\n\n\n\n\nfunc (b Broker) Publish(e Event) ", "output": "{\n\tb.events <- e\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\nfunc Test_SplitByLength(t *testing.T) {\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}\n\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_ToInterface(t *testing.T) ", "output": "{\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}"} {"input": "package baseutil\n\n\n\n\n\n\n\nfunc Check(e error) ", "output": "{\n\tif e != nil {\n\t\tpanic(e)\n\t}\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\nfunc Newf(path string, args ...interface{}) P {\n\treturn New(fmt.Sprintf(path, args...))\n}\n\n\n\n\n\nfunc (path P) Last() string { return path[len(path)-1] }\n\nfunc (path P) String() string ", "output": "{\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}"} {"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\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 (g *nullType) docString(field string, docPrefix string) string ", "output": "{\n\treturn docString(field, g.description, docPrefix, \"must be nothing (null)\")\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\nfunc (tpl *CentosHostInfo) Render(p urknall.Package) {\n\tp.AddTemplate(\"hostinfo\", &CentosHostInfoTemplate{})\n}\n\nfunc (tpl *CentosHostInfo) Options(t *templates.Template) {\n}\n\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) Run(target urknall.Target,inputs map[string]string) error ", "output": "{\n\treturn urknall.Run(target, &CentosHostInfo{},inputs)\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\nfunc (s *Schedule) Run() error {\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}\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\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) RunAlert(a *conf.Alert) ", "output": "{\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}"} {"input": "package daemon\n\nimport (\n\t\"io/ioutil\"\n\t\"os\"\n\t\"testing\"\n\n\t\"github.com/docker/docker/api/types\"\n\tcontainertypes \"github.com/docker/docker/api/types/container\"\n\t\"github.com/docker/docker/container\"\n)\n\n\n\nfunc TestContainerDoubleDelete(t *testing.T) ", "output": "{\n\ttmp, err := ioutil.TempDir(\"\", \"docker-daemon-unix-test-\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdefer os.RemoveAll(tmp)\n\tdaemon := &Daemon{\n\t\trepository: tmp,\n\t\troot: tmp,\n\t}\n\tdaemon.containers = &contStore{s: make(map[string]*container.Container)}\n\n\tcontainer := &container.Container{\n\t\tCommonContainer: container.CommonContainer{\n\t\t\tID: \"test\",\n\t\t\tState: container.NewState(),\n\t\t\tConfig: &containertypes.Config{},\n\t\t},\n\t}\n\tdaemon.containers.Add(container.ID, container)\n\n\tif err := container.SetRemovalInProgress(); err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tif err := daemon.ContainerRm(container.ID, &types.ContainerRmConfig{ForceRemove: true}); err != nil {\n\t\tt.Fatal(err)\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\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 (e *ExtendedAgentSignerWrapper) PublicKey() ssh.PublicKey ", "output": "{\n\treturn e.Signer.PublicKey()\n}"} {"input": "package system\n\n\n\n\n\nfunc Lsetxattr(path string, attr string, data []byte, flags int) error {\n\treturn ErrNotSupportedPlatform\n}\n\nfunc Lgetxattr(path string, attr string) ([]byte, error) ", "output": "{\n\treturn nil, ErrNotSupportedPlatform\n}"} {"input": "package main\n\nimport (\n\t\"hps\"\n\t\"hps/plugins\"\n)\n\n\n\nfunc getPlugins(logger hps.ILogger, rnd hps.IRnd) *plugins.PluginsContainer ", "output": "{\n\treturn plugins.CreatePluginsContainer()\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\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 init() ", "output": "{\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}"} {"input": "package gwent\n\nconst (\n\tAbilityNone = iota\n)\n\n\ntype CardUnit struct {\n\tUnitType CardType\n\tUnitRange CardRange\n\tUnitFaction CardFaction\n\n\tUnitPower, UnitAbility int\n\tUnitHero bool\n\n\tBasicCard\n}\n\n\nfunc (c *CardUnit) Play(p *Player, target Card) {\n\tc.PutOnTable(p)\n}\n\n\nfunc (c *CardUnit) PutOnTable(p *Player) {\n\tswitch c.Range() {\n\tcase RangeClose:\n\t\tp.RowClose = append(p.RowClose, c)\n\tcase RangeRanged:\n\t\tp.RowRanged = append(p.RowRanged, c)\n\tcase RangeSiege:\n\t\tp.RowSiege = append(p.RowSiege, c)\n\t}\n}\n\n\nfunc (c *CardUnit) Type() CardType {\n\treturn c.UnitType\n}\n\n\nfunc (c *CardUnit) Faction() CardFaction {\n\treturn c.UnitFaction\n}\n\n\nfunc (c *CardUnit) Range() CardRange {\n\treturn c.UnitRange\n}\n\n\n\n\n\nfunc (c *CardUnit) Hero() bool {\n\treturn c.UnitHero\n}\n\n\nfunc (c *CardUnit) Targettable() bool {\n\treturn false\n}\n\nfunc (c *CardUnit) Power(p *Player) int ", "output": "{\n\tpwr := c.UnitPower\n\n\tif !c.Hero() && ((c.Range() == RangeClose && p.Game.WeatherClose) ||\n\t\t(c.Range() == RangeRanged && p.Game.WeatherRanged) ||\n\t\t(c.Range() == RangeSiege && p.Game.WeatherSiege)) {\n\t\tpwr = 1\n\t}\n\n\tif (c.Range() == RangeClose && p.HornClose) ||\n\t\t(c.Range() == RangeRanged && p.HornRanged) ||\n\t\t(c.Range() == RangeSiege && p.HornSiege) {\n\t\tpwr *= 2\n\t}\n\n\treturn pwr\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\nfunc (s *WeightedMemberStatusValueSerializer) ToValueBytes(val cluster.MemberStatusValue) []byte {\n\tdVal, _ := val.(*WeightedMemberStatusValue)\n\treturn []byte(strconv.Itoa(dVal.Weight))\n}\n\n\n\nfunc (s *WeightedMemberStatusValueSerializer) FromValueBytes(val []byte) cluster.MemberStatusValue ", "output": "{\n\tweight, _ := strconv.Atoi(string(val))\n\treturn &WeightedMemberStatusValue{Weight: weight}\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\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\nfunc (f *FluxClient) Close() error {\n\treturn f.Conn.Close()\n}\n\nfunc NewFluxClient(dial string) (*FluxClient, error) ", "output": "{\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}"} {"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\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) TitleBarAppearsTransparent() bool ", "output": "{\n\tr, _, _ := NSWindow_titlebarAppearsTransparent.Call(uintptr(n))\n\treturn DBoolToGoBool(r)\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\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) QueryName(queryName string) *GeoPolygonQuery ", "output": "{\n\tq.queryName = queryName\n\treturn q\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\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) NetworkForDevice(sys *gohome.System, d *gohome.Device) gohome.Network ", "output": "{\n\treturn nil\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\n\n\nfunc (action *queryInfoAction) Execute() (string, error) {\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}\n\nfunc NewQueryInfoAction(args *QueryInfoArgs) (*queryInfoAction, error) ", "output": "{\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}"} {"input": "package producers\n\nimport (\n\t\"encoding/json\"\n\n\t\"github.com/matrix-org/dendrite/setup/jetstream\"\n\t\"github.com/matrix-org/dendrite/syncapi/types\"\n\t\"github.com/matrix-org/gomatrixserverlib\"\n\t\"github.com/nats-io/nats.go\"\n\tlog \"github.com/sirupsen/logrus\"\n)\n\n\ntype UserAPIStreamEventProducer struct {\n\tTopic string\n\tJetStream nats.JetStreamContext\n}\n\n\n\n\nfunc (p *UserAPIStreamEventProducer) SendStreamEvent(roomID string, event *gomatrixserverlib.HeaderedEvent, pos types.StreamPosition) error ", "output": "{\n\tm := &nats.Msg{\n\t\tSubject: p.Topic,\n\t\tHeader: nats.Header{},\n\t}\n\tm.Header.Set(jetstream.RoomID, roomID)\n\n\tdata := types.StreamedEvent{\n\t\tEvent: event,\n\t\tStreamPosition: pos,\n\t}\n\tvar err error\n\tm.Data, err = json.Marshal(data)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tlog.WithFields(log.Fields{\n\t\t\"room_id\": roomID,\n\t\t\"event_id\": event.EventID(),\n\t\t\"event_type\": event.Type(),\n\t\t\"stream_pos\": pos,\n\t}).Tracef(\"Producing to topic '%s'\", p.Topic)\n\n\t_, err = p.JetStream.PublishMsg(m)\n\treturn err\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"math\"\n)\n\ntype Vertex struct {\n\tX, Y float64\n}\n\n\n\nfunc main() {\n\tv := &Vertex{3, 4}\n\tfmt.Println(v.Abs())\n}\n\nfunc (v *Vertex) Abs() float64 ", "output": "{\n\treturn math.Sqrt(v.X * v.X + v.Y * v.Y)\n}"} {"input": "package utils\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n\t\"os/exec\"\n\t\"strings\"\n\n\t\"github.com/gemnasium/toolbelt/config\"\n\t\"github.com/mgutz/ansi\"\n)\n\nfunc PrintFatal(message string, args ...interface{}) {\n\tlog.Fatal(colorizeMessage(\"red\", \"error:\", message, args...))\n}\n\nfunc colorizeMessage(color, prefix, message string, args ...interface{}) string {\n\tprefResult := \"\"\n\tif prefix != \"\" {\n\t\tprefResult = ansi.Color(prefix, color+\"+b\") + \" \" + ansi.ColorCode(\"reset\")\n\t}\n\treturn prefResult + ansi.Color(fmt.Sprintf(message, args...), color) + ansi.ColorCode(\"reset\")\n}\n\n\n\n\n\n\n\nfunc GetCurrentRevision() string {\n\tif envRevision := os.Getenv(config.ENV_REVISION); envRevision != \"\" {\n\t\treturn envRevision\n\t}\n\tout, err := exec.Command(GitPath(), \"rev-parse\", \"--verify\", \"HEAD\").Output()\n\tif err != nil {\n\t\treturn \"\"\n\t}\n\treturn strings.TrimSpace(string(out))\n}\n\n\n\nfunc GetCurrentBranch() string {\n\tif envBranch := os.Getenv(config.ENV_BRANCH); envBranch != \"\" {\n\t\treturn envBranch\n\t}\n\tout, err := exec.Command(GitPath(), \"rev-parse\", \"--abbrev-ref\", \"HEAD\").Output()\n\tif err != nil {\n\t\treturn \"master\"\n\t}\n\treturn strings.TrimSpace(string(out))\n}\n\n\nfunc GitPath() string {\n\tpath, _ := exec.LookPath(\"git\")\n\treturn path\n}\n\nfunc StatusDots(status string) string ", "output": "{\n\tvar dots string\n\tswitch status {\n\tcase \"red\":\n\t\tdots = \"@k\\u2B24 @k\\u2B24 @r\\u2B24 @{|}(red)\"\n\tcase \"yellow\":\n\t\tdots = \"@k\\u2B24 @y\\u2B24 @k\\u2B24 @{|}(yellow)\"\n\tcase \"green\":\n\t\tdots = \"@g\\u2B24 @k\\u2B24 @k\\u2B24 @{|}(green)\"\n\tdefault:\n\t\tdots = \"@k\\u2B24 @k\\u2B24 @k\\u2B24 @{|}(none)\"\n\t}\n\treturn dots\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 getNameTagById(\n\tp *struct {\n\t\tNameTagId int16 `mvc:\"param[name_tag_id]\"`\n\t},\n) mvc.OutputBody {\n\treturn mvc.JsonOutputOrNotFound(\n\t\tdbOwl.GetNameTagById(p.NameTagId),\n\t)\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) ", "output": "{\n\treturn p.Paging,\n\t\tmvc.JsonOutputBody(\n\t\t\tdbOwl.ListNameTags(p.Value, p.Paging),\n\t\t)\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\n\n\nfunc (f *FinancialInstrument11) SetTransferType(value string) {\n\tf.TransferType = (*TransferType1Code)(&value)\n}\n\nfunc (f *FinancialInstrument11) SetName(value string) ", "output": "{\n\tf.Name = (*Max350Text)(&value)\n}"} {"input": "package vm\n\ntype Base struct {\n}\n\nvar SupportedAPICalls = []string{\n\t\"/api.Instance/Start\",\n\t\"/api.Instance/Run\",\n\t\"/api.Instance/Stop\",\n\t\"/api.Instance/Reboot\",\n\t\"/api.Instance/Console\",\n\t\"/api.Instance/Log\",\n}\n\n\n\nfunc (*Base) IsSupportAPI(method string) bool ", "output": "{\n\tfor _, m := range SupportedAPICalls {\n\t\tif m == method {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}"} {"input": "package iso20022\n\n\ntype Acquirer8 struct {\n\n\tIdentification *Max35Text `xml:\"Id\"`\n\n\tApplicationVersion *Max35Text `xml:\"ApplVrsn,omitempty\"`\n}\n\n\n\nfunc (a *Acquirer8) SetApplicationVersion(value string) {\n\ta.ApplicationVersion = (*Max35Text)(&value)\n}\n\nfunc (a *Acquirer8) SetIdentification(value string) ", "output": "{\n\ta.Identification = (*Max35Text)(&value)\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\nfunc TestNewFPFilter(t *testing.T) {\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}\n\n\n\nfunc TestAlwaysInFilter(t *testing.T) ", "output": "{\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}"} {"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\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 newNull() (api.BackingStore, error) ", "output": "{\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}"} {"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\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(\"\") }\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) Get(i int) types.Field ", "output": "{\n\tfield := r.def.Fields()[i]\n\tr.fields[i] = DatumForType(field.Type())\n\treturn r.fields[i]\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\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\nfunc (f *RstStreamFrame) GetStreamId() uint32 {\n\treturn f.StreamId\n}\n\nfunc NewRstStreamFrame(streamId uint32, errorCode ErrorCode) *RstStreamFrame ", "output": "{\n\treturn &RstStreamFrame{\n\t\tStreamId: streamId,\n\t\tErrorCode: errorCode,\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\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 RemoveRoom(r *Room) ", "output": "{\n\n\tindex, _ := FindRoom(r.Name)\n\n\tif index != -1 {\n\t\tRoomPool = append(RoomPool[:index], RoomPool[index + 1:]...)\n\t}\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\nfunc New(w io.Writer, mods ...Modifier) io.Writer {\n\treturn awr{w, mods}\n}\n\n\n\nfunc (a awr) Write(b []byte) (n int, err error) ", "output": "{\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}"} {"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\nfunc ExampleParseFloat() {\n\tf, _ := ParseFloat(\"eight and three quarters\")\n\tfmt.Println(f)\n\n}\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 ExampleParseInt() ", "output": "{\n\ti, _ := ParseInt(\"fourteen ninety two\")\n\tfmt.Println(i)\n\n}"} {"input": "package api\n\nimport (\n\t\"fmt\"\n\n\t\"k8s.io/kubernetes/pkg/api/validation\"\n)\n\n\nfunc GetNameValidationFunc(nameFunc validation.ValidateNameFunc) validation.ValidateNameFunc {\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}\n\n\n\n\n\n\n\nfunc GetFieldLabelConversionFunc(supportedLabels map[string]string, overrideLabels map[string]string) func(label, value string) (string, string, error) ", "output": "{\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}"} {"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\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\nfunc ExampleAcceleratorTypesClient_List() {\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}\n\nfunc ExampleNewAcceleratorTypesRESTClient() ", "output": "{\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}"} {"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\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\nfunc (w *whisperFilter) activity() time.Time {\n\tw.lock.RLock()\n\tdefer w.lock.RUnlock()\n\n\treturn w.update\n}\n\nfunc newWhisperFilter(id int, ref *Whisper) *whisperFilter ", "output": "{\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}"} {"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\n\n\nfunc (n NSWindow) SetStyleMask(mask uint) {\n\tNSWindow_setStyleMask.Call(uintptr(n), uintptr(mask))\n}\n\nfunc (n NSWindow) StyleMask() uint ", "output": "{\n\tr, _, _ := NSWindow_styleMask.Call(uintptr(n))\n\treturn uint(r)\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\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 makeBackend(log *zap.Logger, settings Settings) (Backend, error) ", "output": "{\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}"} {"input": "package gitlab\n\nimport (\n\t\"net/http\"\n\t\"net/url\"\n\t\"strings\"\n\n\t\"github.com/openshift/origin/pkg/oauthserver/oauth/external\"\n\n\t\"github.com/golang/glog\"\n)\n\n\n\nconst gitlabHostedDomain = \"gitlab.com\"\n\nfunc NewProvider(providerName, URL, clientID, clientSecret string, transport http.RoundTripper, legacy *bool) (external.Provider, error) {\n\tif isLegacy(legacy, URL) {\n\t\tglog.Infof(\"Using legacy OAuth2 for GitLab identity provider %s url=%s clientID=%s\", providerName, URL, clientID)\n\t\treturn NewOAuthProvider(providerName, URL, clientID, clientSecret, transport)\n\t}\n\tglog.Infof(\"Using OIDC for GitLab identity provider %s url=%s clientID=%s\", providerName, URL, clientID)\n\treturn NewOIDCProvider(providerName, URL, clientID, clientSecret, transport)\n}\n\n\n\nfunc isLegacy(legacy *bool, URL string) bool ", "output": "{\n\tif legacy != nil {\n\t\treturn *legacy\n\t}\n\n\tif u, err := url.Parse(URL); err == nil && strings.EqualFold(u.Hostname(), gitlabHostedDomain) {\n\t\treturn false\n\t}\n\n\treturn true\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\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\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 New(out, err io.Writer) *Runner ", "output": "{\n\treturn &Runner{out, err}\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\nfunc PodsWithDeletiontimestamps(pods []*v1.Pod) string {\n\treturn aggregatePods(pods, PodWithDeletionTimestamp)\n}\n\n\n\nfunc aggregatePods(pods []*v1.Pod, handler podHandler) string ", "output": "{\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}"} {"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\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\n\n\nfunc (si *Size) KV() []map[string]interface{} ", "output": "{\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}"} {"input": "package util\n\nimport (\n\t\"io\"\n\t\"io/ioutil\"\n\t\"net\"\n\t\"net/http\"\n\t\"time\"\n)\n\n\ntype HTTPAlive struct {\n\tclient *http.Client\n\ttransport *http.Transport\n\tcustomHeader map[string]string\n}\n\n\ntype HTTPAliveResponse struct {\n\tStatusCode int\n\tBody []byte\n\tHeader http.Header\n}\n\n\nfunc (connection *HTTPAlive) Configure(timeout time.Duration,\n\taliveDuration time.Duration,\n\tmaxIdleConnections int) {\n\tif connection.transport == nil {\n\t\tconnection.transport = &http.Transport{\n\t\t\tDial: (&net.Dialer{\n\t\t\t\tTimeout: timeout,\n\t\t\t\tKeepAlive: aliveDuration,\n\t\t\t}).Dial,\n\t\t\tMaxIdleConnsPerHost: maxIdleConnections,\n\t\t}\n\t}\n\n\tif connection.client == nil {\n\t\tconnection.client = &http.Client{\n\t\t\tTransport: connection.transport,\n\t\t}\n\t}\n}\n\n\nfunc (connection *HTTPAlive) SetHeader(header map[string]string) {\n\tconnection.customHeader = header\n}\n\n\nfunc (connection *HTTPAlive) MakeRequest(method string,\n\turi string, body io.Reader) (*HTTPAliveResponse, error) {\n\n\tdefer connection.resetCustomHeader()\n\treq, err := http.NewRequest(method, uri, body)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfor key, value := range connection.customHeader {\n\t\treq.Header.Set(key, value)\n\t}\n\n\treturn connection.submitRequest(req)\n}\n\n\n\nfunc (connection *HTTPAlive) resetCustomHeader() {\n\tconnection.customHeader = make(map[string]string)\n}\n\nfunc discardResponseBody(body io.ReadCloser) {\n\tio.Copy(ioutil.Discard, body)\n\tbody.Close()\n}\n\nfunc (connection *HTTPAlive) submitRequest(req *http.Request) (*HTTPAliveResponse, error) ", "output": "{\n\trsp, err := connection.client.Do(req)\n\n\tif rsp != nil {\n\t\tdefer discardResponseBody(rsp.Body)\n\t}\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tbody, err := ioutil.ReadAll(rsp.Body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\thttpAliveResponse := new(HTTPAliveResponse)\n\thttpAliveResponse.Body = body\n\thttpAliveResponse.StatusCode = rsp.StatusCode\n\thttpAliveResponse.Header = rsp.Header\n\treturn httpAliveResponse, nil\n}"} {"input": "package measurers\n\nimport \"syscall\"\n\ntype DiskSpaceMeasurer struct {\n\tpath string\n}\n\n\n\nfunc (m *DiskSpaceMeasurer) Measure() (float64, error) {\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}\n\nfunc NewDiskSpaceMeasurer(path string) *DiskSpaceMeasurer ", "output": "{\n\treturn &DiskSpaceMeasurer{path: path}\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n)\n\n\n\nfunc listComPorts() ", "output": "{\n\tfmt.Fprintln(os.Stderr, \"the flag -l, --list are available on windows only.\")\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\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) ID() uint32 ", "output": "{\n\treturn c.id\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\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\nfunc (rs ResponseTimes) Swap(i, j int) {\n\trs[i], rs[j] = rs[j], rs[i]\n}\n\nfunc NewResponseTime(v int) ResponseTime ", "output": "{\n\tr := ResponseTime{Value: v, Time: time.Now()}\n\treturn r\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\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\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 Test() ", "output": "{\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}"} {"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\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\n\n\nfunc (self *Set) String() string ", "output": "{\n return fmt.Sprintf(\"(%s %s %s)\", constants.SET, self.Pattern, self.Value)\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\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: 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}\n\nfunc init() ", "output": "{\n\tInstall(core.GroupFactoryRegistry, core.Registry, core.Scheme)\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 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\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 (d TextField) String() string ", "output": "{\n\treturn fmt.Sprintf(\"%s=%s\", d.name, d.Is)\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\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\n\n\nfunc logWithLevel(title string, level kayvee.LogLevel, data M) ", "output": "{\n\tformatted := kayvee.FormatLog(\"moredis\", level, title, data)\n\tlog.Println(formatted)\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\nfunc gitDbranchAction(c *cli.Context) {\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}\n\n\n\nfunc deleteBranch(branch string) ", "output": "{\n\texecCmd(\"git branch -D \" + branch)\n\texecCmd(\"git push origin :\" + branch)\n}"} {"input": "package http\n\nimport (\n\tgohttp \"net/http\"\n)\n\n\ntype Client struct {\n\t*gohttp.Client\n}\n\n\n\n\nfunc (client *Client) Do(req *Request) (*Response, error) {\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}\n\nfunc NewClient() (*Client, error) ", "output": "{\n\tclient := &Client{}\n\tclient.Client = &gohttp.Client{}\n\treturn client, nil\n}"} {"input": "package mlock\n\nimport (\n \"syscall\"\n \"golang.org/x/sys/unix\"\n)\n\nfunc init() {\n supported = true\n}\n\n\n\nfunc lockMemory() error ", "output": "{\n \n return unix.Mlockall(syscall.MCL_CURRENT | syscall.MCL_FUTURE)\n}"} {"input": "package mocks\n\nimport \"github.com/myshkin5/jsonstruct\"\n\ntype MockWriter struct {\n\tMessages chan []byte\n}\n\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\nfunc (m *MockWriter) Close() error {\n\treturn nil\n}\n\nfunc NewMockWriter() *MockWriter ", "output": "{\n\treturn &MockWriter{\n\t\tMessages: make(chan []byte, 10000),\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\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\n\n\nfunc (r *BaseResource) DeleteResource(key string, value string) bool {\n\treturn r.parent.DeleteResource(key, value)\n}\n\nfunc (r *BaseResource) UpdateResource(key string, value string, v interface{}) interface{} ", "output": "{\n\tresource := r.parent.UpdateResource(key, value, v)\n\tif resource != nil {\n\t\treturn resource\n\t}\n\n\treturn 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\nfunc (m *MeetingCancellationReason2) AddCancellationReasonCode() *MeetingCancellationReason1Choice {\n\tm.CancellationReasonCode = new(MeetingCancellationReason1Choice)\n\treturn m.CancellationReasonCode\n}\n\n\n\nfunc (m *MeetingCancellationReason2) SetCancellationReason(value string) ", "output": "{\n\tm.CancellationReason = (*Max140Text)(&value)\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\nfunc (e *Elasticsearch) Initialize() error {\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}\n\n\n\n\nfunc (e *Elasticsearch) SendAnalytics(data string) error ", "output": "{\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}"} {"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\n\n\n\nfunc (tb *tokenBucket) capacityToken() time.Time {\n\treturn time.Now().Add(-tb.refillDuration).Truncate(tb.tokenInterval)\n}\n\nfunc (tb *tokenBucket) wait() ", "output": "{\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}"} {"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\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\n\n\nfunc ExecuteCmd(cmd Command, cache *cache.Cache) ([]byte, bool) ", "output": "{\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}"} {"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\nfunc (ls *ListAntiAffinityGroups) SetPageSize(pageSize int) {\n\tls.PageSize = pageSize\n}\n\n\n\n\nfunc (ListAntiAffinityGroups) Each(resp interface{}, callback IterateItemFunc) ", "output": "{\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}"} {"input": "package runtime\n\nimport (\n\t\"fmt\"\n\t\"reflect\"\n\n\t\"k8s.io/apimachinery/pkg/runtime/schema\"\n)\n\n\n\n\n\n\n\nfunc CheckCodec(c Codec, internalType Object, externalTypes ...schema.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 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\n\n\nfunc (s *StepPowerOffCompute) powerOffCompute(resourceGroupName string, computeName string) error {\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}\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 NewStepPowerOffCompute(client *AzureClient, ui packer.Ui) *StepPowerOffCompute ", "output": "{\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}"} {"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\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 kubeConfigSolution(isExplicitFile bool) string ", "output": "{\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}"} {"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\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) Index(index int) *Path ", "output": "{\n\treturn &Path{index: strconv.Itoa(index), parent: p}\n}"} {"input": "package event\n\nimport \"bytes\"\n\ntype ChannelCloseReqEvent struct {\n\tEventHeader\n}\n\nfunc (ev *ChannelCloseReqEvent) Encode(buffer *bytes.Buffer) {\n}\n\n\ntype ChannelCloseACKEvent struct {\n\tEventHeader\n}\n\nfunc (ev *ChannelCloseACKEvent) Encode(buffer *bytes.Buffer) {\n}\nfunc (ev *ChannelCloseACKEvent) Decode(buffer *bytes.Buffer) (err error) {\n\treturn nil\n}\n\nfunc (ev *ChannelCloseReqEvent) Decode(buffer *bytes.Buffer) (err error) ", "output": "{\n\treturn nil\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\nfunc (p *paramHeader) length() int {\n\treturn p.len\n}\n\n\n\n\nfunc (p paramHeader) String() string ", "output": "{\n\treturn fmt.Sprintf(\"%s (%d): %s\", p.typ, p.len, p.raw)\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\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\n\n\nfunc (r *AWSApplicationAutoScalingScalableTarget_ScheduledAction) SetDeletionPolicy(policy policies.DeletionPolicy) ", "output": "{\n\tr._deletionPolicy = policy\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\n\n\nfunc (this *SimpleScheduler) Count() int {\n\treturn len(this.queue)\n}\n\nfunc (this *SimpleScheduler) Poll() *robot.Request ", "output": "{\n\tif len(this.queue) == 0 {\n\t\treturn nil\n\t} else {\n\t\treturn <-this.queue\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\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\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) Write(r Record) error ", "output": "{\n\to.buffer.Put(r)\n\treturn nil\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\n\n\nfunc encodeHeader(s string) string {\n\treturn mime.QEncoding.Encode(\"utf-8\", s)\n}\n\nfunc decodeHeader(s string) (string, error) ", "output": "{\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}"} {"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 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 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 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\n\n\n\n\nfunc (c *Ctx) SetDHParameters(dh *DH) error {\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}\n\nfunc LoadDHParametersFromPEM(pem_block []byte) (*DH, error) ", "output": "{\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}"} {"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\nfunc (response ListMultipartUploadsResponse) String() string {\n\treturn common.PointerString(response)\n}\n\n\n\n\nfunc (response ListMultipartUploadsResponse) HTTPResponse() *http.Response ", "output": "{\n\treturn response.RawResponse\n}"} {"input": "package storage\n\nimport (\n\t\"time\"\n\n\t\"github.com/spf13/viper\"\n)\n\n\n\ntype minioConfig struct {\n\thost string\n\tport string\n\taccessKey string\n\tsecretKey string\n\ttoken string\n\tsecure bool\n\ttimes int\n\tpause time.Duration\n\ttimeout time.Duration\n\tlocation string\n\tprefix string\n}\n\nfunc newMinioConfig() minioConfig ", "output": "{\n\treturn minioConfig{\n\t\thost: viper.GetString(\"storage.minio.host\"),\n\t\tport: viper.GetString(\"storage.minio.port\"),\n\t\taccessKey: viper.GetString(\"storage.minio.accessKey\"),\n\t\tsecretKey: viper.GetString(\"storage.minio.secretKey\"),\n\t\ttoken: viper.GetString(\"storage.minio.token\"),\n\t\tsecure: viper.GetBool(\"storage.minio.secure\"),\n\t\ttimes: viper.GetInt(\"storage.minio.retry.times\"),\n\t\tpause: viper.GetDuration(\"storage.minio.retry.pause\"),\n\t\ttimeout: viper.GetDuration(\"storage.minio.retry.timeout\"),\n\t\tlocation: viper.GetString(\"storage.minio.location\"),\n\t\tprefix: viper.GetString(\"storage.minio.prefix\"),\n\t}\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\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\nfunc NewProcessor(w Widget, v Validater, f Filterer) *processor {\n\treturn &processor{w, v, f}\n}\n\nfunc newnamed(name string) *named ", "output": "{\n\treturn &named{name: name}\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\nfunc (ua *UnsubackPacket) Type() byte {\n\treturn ua.FixedHeader.MessageType\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\n\n\n\n\nfunc (ua *UnsubackPacket) Details() Details {\n\treturn Details{Qos: 0, MessageID: ua.MessageID}\n}\n\nfunc (ua *UnsubackPacket) Unpack(b io.Reader) error ", "output": "{\n\tua.MessageID = decodeUint16(b)\n\n\treturn nil\n}"} {"input": "package logs\n\nconst (\n\tErrorLevel = iota\n\tWarnLevel\n\tInfoLevel\n\tDebugLevel\n)\n\ntype Level uint32\n\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\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) EQ(lv Level) bool ", "output": "{\n\tif l == lv {\n\t\treturn true\n\t}\n\treturn false\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\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\nfunc BenchmarkLastIndex(b *testing.B) {\n\tfor i := 0; i < b.N; i++ {\n\t\tbasename.LastIndex(path)\n\t}\n}\n\nfunc TestLoop(t *testing.T) ", "output": "{\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}"} {"input": "package goarken\n\ntype Broadcaster struct {\n\tlisteners []chan interface{}\n}\n\n\n\nfunc (b *Broadcaster) Write(message interface{}) {\n\tfor _, channel := range b.listeners {\n\t\tchannel <- message\n\t}\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 NewBroadcaster() *Broadcaster ", "output": "{\n\tb := &Broadcaster{\n\t\tlisteners: []chan interface{}{},\n\t}\n\treturn b\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\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}\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 ElapsedTime(w http.ResponseWriter, r *http.Request, next http.HandlerFunc) ", "output": "{\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}"} {"input": "package pty\n\nimport \"os\"\n\n\n\n\nfunc InheritSize(pty, tty *os.File) error {\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}\n\n\n\n\n\nfunc Getsize(t *os.File) (rows, cols int, err error) ", "output": "{\n\tws, err := GetsizeFull(t)\n\treturn int(ws.Rows), int(ws.Cols), err\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\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 (c *Command) RegisterFlags(r codegen.FlagRegistry) ", "output": "{\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}"} {"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\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) Add(delta float64) ", "output": "{\n\tc.CounterValue += delta\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\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\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) BeforeActivation(b mvc.BeforeActivation) ", "output": "{\n\tb.Dependencies().Register(func(ctx iris.Context) (items []todo.Item) {\n\t\tctx.ReadJSON(&items)\n\t\treturn\n\t}) \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\n\n\n\n\nfunc (i *rawIterator) Path() string {\n\treturn i.path\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) Front() *Node ", "output": "{\n\treturn i.pos\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}\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 NewListClient(subscriptionID string) ListClient ", "output": "{\n\treturn original.NewListClient(subscriptionID)\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\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 (e *eventDemux) start() ", "output": "{\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}"} {"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\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 SendValue(name string, value float64, unit string) error ", "output": "{\n\tif metricSender == nil {\n\t\treturn nil\n\t}\n\treturn metricSender.SendValue(name, value, unit)\n}"} {"input": "package dao\n\nimport (\n\t\"context\"\n\t\"database/sql\"\n\t\"fmt\"\n\t\"go-common/library/log\"\n)\n\nconst (\n\t_queryBvcResource = \"select id from %s where svid = %d\"\n\t_queryCoverResource = \"select cover_url,cover_width,cover_height from video_repository where svid = ?\"\n)\n\n\n\n\nfunc (d *Dao) CheckSVResource(c context.Context, svid int64) (err error) ", "output": "{\n\tvar (\n\t\tID int64\n\t\tcURL string\n\t\tcH int64\n\t\tcW int64\n\t)\n\ttN := fmt.Sprintf(\"video_bvc_%02d\", svid%100)\n\n\tif err = d.db.QueryRow(c, fmt.Sprintf(_queryBvcResource, tN, svid)).Scan(&ID); err == sql.ErrNoRows {\n\t\tlog.Error(\"CheckSVResource bvc err,svid:%d,err:%v\", svid, err)\n\t\treturn\n\t}\n\tif err = d.db.QueryRow(c, _queryCoverResource, svid).Scan(&cURL, &cW, &cH); err == sql.ErrNoRows {\n\t\tlog.Error(\"CheckSVResource cover err,svid:%d,err:%v\", svid, err)\n\t\treturn\n\t}\n\treturn\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\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\nfunc (a Augeas) errorDetails() string {\n\treturn C.GoString(C.aug_error_details(a.handle))\n}\n\nfunc (err Error) Error() string ", "output": "{\n\treturn fmt.Sprintf(\"Message: %s - Minor message: %s - Details: %s\",\n\t\terr.Message, err.MinorMessage, err.Details)\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\nfunc NoError(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 := Predicate(pred, timeout); err != nil {\n\t\treturn predErr\n\t}\n\n\treturn nil\n}\n\n\n\n\n\n\n\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 Invariant(statement func() bool, timeout time.Duration) error ", "output": "{\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}"} {"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\nfunc (c *CardPaymentEnvironment37) AddPOIIdentification() *GenericIdentification53 {\n\tc.POIIdentification = new(GenericIdentification53)\n\treturn c.POIIdentification\n}\n\n\n\nfunc (c *CardPaymentEnvironment37) AddPOIComponent() *PointOfInteractionComponent5 ", "output": "{\n\tnewValue := new(PointOfInteractionComponent5)\n\tc.POIComponent = append(c.POIComponent, newValue)\n\treturn newValue\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\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) Stop() ", "output": "{\n\tif l.stop != nil {\n\t\tclose(l.stop)\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\n\n\n\nfunc (response CreateDbHomeResponse) HTTPResponse() *http.Response {\n\treturn response.RawResponse\n}\n\nfunc (response CreateDbHomeResponse) String() string ", "output": "{\n\treturn common.PointerString(response)\n}"} {"input": "package stdlib\n\nimport (\n\t\"crypto/ed25519\"\n\t\"go/constant\"\n\t\"go/token\"\n\t\"reflect\"\n)\n\n\n\nfunc init() ", "output": "{\n\tSymbols[\"crypto/ed25519\"] = map[string]reflect.Value{\n\t\t\"GenerateKey\": reflect.ValueOf(ed25519.GenerateKey),\n\t\t\"NewKeyFromSeed\": reflect.ValueOf(ed25519.NewKeyFromSeed),\n\t\t\"PrivateKeySize\": reflect.ValueOf(constant.MakeFromLiteral(\"64\", token.INT, 0)),\n\t\t\"PublicKeySize\": reflect.ValueOf(constant.MakeFromLiteral(\"32\", token.INT, 0)),\n\t\t\"SeedSize\": reflect.ValueOf(constant.MakeFromLiteral(\"32\", token.INT, 0)),\n\t\t\"Sign\": reflect.ValueOf(ed25519.Sign),\n\t\t\"SignatureSize\": reflect.ValueOf(constant.MakeFromLiteral(\"64\", token.INT, 0)),\n\t\t\"Verify\": reflect.ValueOf(ed25519.Verify),\n\n\t\t\"PrivateKey\": reflect.ValueOf((*ed25519.PrivateKey)(nil)),\n\t\t\"PublicKey\": reflect.ValueOf((*ed25519.PublicKey)(nil)),\n\t}\n}"} {"input": "package reboot\n\nimport (\n\t\"github.com/juju/errors\"\n\t\"github.com/juju/utils/clock\"\n\n\t\"github.com/juju/juju/agent\"\n\t\"github.com/juju/juju/api\"\n\t\"github.com/juju/juju/api/base\"\n\t\"github.com/juju/juju/worker\"\n\t\"github.com/juju/juju/worker/dependency\"\n)\n\n\ntype ManifoldConfig struct {\n\tAgentName string\n\tAPICallerName string\n\tMachineLockName string\n\tClock clock.Clock\n}\n\n\n\nfunc Manifold(config ManifoldConfig) dependency.Manifold {\n\treturn dependency.Manifold{\n\t\tInputs: []string{\n\t\t\tconfig.AgentName,\n\t\t\tconfig.APICallerName,\n\t\t},\n\t\tStart: func(context dependency.Context) (worker.Worker, error) {\n\t\t\tvar agent agent.Agent\n\t\t\tif err := context.Get(config.AgentName, &agent); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tvar apiCaller base.APICaller\n\t\t\tif err := context.Get(config.APICallerName, &apiCaller); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tif config.Clock == nil {\n\t\t\t\treturn nil, errors.NotValidf(\"missing Clock\")\n\t\t\t}\n\t\t\tif config.MachineLockName == \"\" {\n\t\t\t\treturn nil, errors.NotValidf(\"missing MachineLockName\")\n\t\t\t}\n\t\t\treturn newWorker(agent, apiCaller, config.MachineLockName, config.Clock)\n\t\t},\n\t}\n}\n\n\n\n\n\n\n\nfunc newWorker(a agent.Agent, apiCaller base.APICaller, machineLockName string, clock clock.Clock) (worker.Worker, error) ", "output": "{\n\tapiConn, ok := apiCaller.(api.Connection)\n\tif !ok {\n\t\treturn nil, errors.New(\"unable to obtain api.Connection\")\n\t}\n\trebootState, err := apiConn.Reboot()\n\tif err != nil {\n\t\treturn nil, errors.Trace(err)\n\t}\n\tw, err := NewReboot(rebootState, a.CurrentConfig(), machineLockName, clock)\n\tif err != nil {\n\t\treturn nil, errors.Annotate(err, \"cannot start reboot worker\")\n\t}\n\treturn w, nil\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\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\nfunc (r *Reader) Close() error {\n\treturn nil\n}\n\nfunc (r *Reader) BytesSafeAfterClose() bool ", "output": "{\n\treturn false\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\nfunc (files PackageFiles) Swap(i, j int) {\n\tfiles[i], files[j] = files[j], files[i]\n}\n\n\n\n\nfunc (files PackageFiles) Less(i, j int) bool ", "output": "{\n\treturn files[i].Filename < files[j].Filename\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\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\n\n\nfunc (p BackingProcess) Delete() error {\n\t_, err := p.containerdProcess.Delete(p.context)\n\treturn err\n}\n\nfunc (p BackingProcess) Signal(signal syscall.Signal) error ", "output": "{\n\treturn p.containerdProcess.Kill(p.context, signal)\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\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 (c Cat) Say() string ", "output": "{\n\treturn fmt.Sprintf(\"%v meows\", c.name)\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\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 runDownload(args []string) error ", "output": "{\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}"} {"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\nfunc (s *TableServer) OnMessage(c *shttp.WSAsyncClient, msg shttp.WSMessage) {\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}\n\n\n\nfunc NewServer(allocator *TableAllocator, wspool *shttp.WSAsyncClientPool) *TableServer ", "output": "{\n\ts := &TableServer{\n\t\tTableAllocator: allocator,\n\t\tWSAsyncClientPool: wspool,\n\t}\n\twspool.AddEventHandler(s)\n\n\treturn s\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\nfunc (p *propNoteClass) GetClassStr() string {\n\treturn string(p.Class)\n}\n\n\n\n\nfunc (p *propNoteClass) SetClassByStr(c string) ", "output": "{\n\tp.Class = ENoteClass(c)\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\n\n\nfunc (s *StandingSettlementInstruction9) AddOtherReceivingSettlementParties() *SettlementParties23 {\n\ts.OtherReceivingSettlementParties = new(SettlementParties23)\n\treturn s.OtherReceivingSettlementParties\n}\n\nfunc (s *StandingSettlementInstruction9) AddOtherDeliveringSettlementParties() *SettlementParties23 ", "output": "{\n\ts.OtherDeliveringSettlementParties = new(SettlementParties23)\n\treturn s.OtherDeliveringSettlementParties\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\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) HasTexture() bool ", "output": "{\n\treturn len(user.TextureBlob) > 0\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\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 OpenWriter(path string) (io.WriteCloser, error) ", "output": "{\n\treturn os.OpenFile(path, unix.O_WRONLY, os.ModeNamedPipe)\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\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\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) SetFlags(f *gnuflag.FlagSet) ", "output": "{\n\tf.StringVar(&c.ConfigPath, \"config\", \"\", \"charmd configuration file\")\n}"} {"input": "package rorm\n\ntype rorm struct {\n\tredisQuerier *RedisQuerier\n}\n\nfunc NewROrm() ROrmer {\n\treturn new(rorm).Using(\"default\")\n}\n\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\nfunc (r *rorm) Querier() Querier {\n\treturn r.redisQuerier\n}\n\nfunc (r *rorm) QueryHash(key string) HashQuerySeter ", "output": "{\n\treturn &hashQuerySet{\n\t\tquerySet: &querySet{\n\t\t\trorm: r,\n\t\t\tkey: key,\n\t\t},\n\t}\n}"} {"input": "package main\n\n\n\n\n\ntype Scope struct {\n\tparent *Scope \n\tentities map[string]*Decl\n}\n\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\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 NewScope(outer *Scope) *Scope ", "output": "{\n\ts := new(Scope)\n\ts.parent = outer\n\ts.entities = make(map[string]*Decl)\n\treturn s\n}"} {"input": "package daemon\n\n\n\n\nimport (\n\t\"io\"\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\n\t\"github.com/cilium/cilium/api/v1/models\"\n)\n\n\n\n\n\n\n\n\n\ntype PatchConfigParams struct {\n\n\tHTTPRequest *http.Request\n\n\tConfiguration *models.Configuration\n}\n\n\n\nfunc (o *PatchConfigParams) BindRequest(r *http.Request, route *middleware.MatchedRoute) error {\n\tvar res []error\n\to.HTTPRequest = r\n\n\tif runtime.HasBody(r) {\n\t\tdefer r.Body.Close()\n\t\tvar body models.Configuration\n\t\tif err := route.Consumer.Consume(r.Body, &body); err != nil {\n\t\t\tif err == io.EOF {\n\t\t\t\tres = append(res, errors.Required(\"configuration\", \"body\"))\n\t\t\t} else {\n\t\t\t\tres = append(res, errors.NewParseError(\"configuration\", \"body\", \"\", err))\n\t\t\t}\n\n\t\t} else {\n\t\t\tif err := body.Validate(route.Formats); err != nil {\n\t\t\t\tres = append(res, err)\n\t\t\t}\n\n\t\t\tif len(res) == 0 {\n\t\t\t\to.Configuration = &body\n\t\t\t}\n\t\t}\n\n\t} else {\n\t\tres = append(res, errors.Required(\"configuration\", \"body\"))\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}\n\nfunc NewPatchConfigParams() PatchConfigParams ", "output": "{\n\tvar ()\n\treturn PatchConfigParams{}\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 }\n\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) Ordering() orderingInfo ", "output": "{ return orderingInfo{} }"} {"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\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) Close() error ", "output": "{\n\treturn c.conn.Close()\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\nfunc (r *AWSIoTAnalyticsPipeline_DeviceShadowEnrich) Metadata() map[string]interface{} {\n\treturn r._metadata\n}\n\n\n\n\n\n\n\nfunc (r *AWSIoTAnalyticsPipeline_DeviceShadowEnrich) SetDeletionPolicy(policy policies.DeletionPolicy) {\n\tr._deletionPolicy = policy\n}\n\nfunc (r *AWSIoTAnalyticsPipeline_DeviceShadowEnrich) SetMetadata(metadata map[string]interface{}) ", "output": "{\n\tr._metadata = metadata\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\nfunc NewFakeBlobstoreFactory() *FakeBlobstoreFactory {\n\treturn &FakeBlobstoreFactory{}\n}\n\n\n\nfunc (f *FakeBlobstoreFactory) Create(blobstoreURL string) (biblobstore.Blobstore, error) ", "output": "{\n\tf.CreateBlobstoreURL = blobstoreURL\n\treturn f.CreateBlobstore, f.CreateErr\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\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\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 ThresholdLogger(\n\tctx context.Context,\n\twarnDuration time.Duration,\n\tprintf func(context.Context, string, ...interface{}),\n\trecord TimingFn,\n) TimingFn ", "output": "{\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}"} {"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\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\n\n\nfunc (ctx *Context) Error() error ", "output": "{\n\tctx.mu.RLock()\n\tdefer ctx.mu.RUnlock()\n\n\treturn ctx.err\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\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) Authorize(provider goth.Provider, params goth.Params) (string, error) ", "output": "{\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}"} {"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\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_tooBig(t *testing.T) ", "output": "{\n\tevent := logEvent{msg: RandomString(maxEventSize + 1)}\n\tassert.Equal(t, errMessageTooBig, event.validate())\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\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\n\n\nfunc (response UpdateManagedListResponse) HTTPResponse() *http.Response ", "output": "{\n\treturn response.RawResponse\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\n\n\n\nfunc (r *Reader) Read(reader io.Reader, processorConfiguration *processor.Configuration) error {\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}\n\nfunc NewReader() (*Reader, error) ", "output": "{\n\treturn &Reader{}, nil\n}"} {"input": "package bits_test\n\nimport (\n\t\"github.com/twmb/bits\"\n\t\"testing\"\n)\n\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}\nfunc BenchmarkSetU64(b *testing.B) {\n\tfor i := 0; i < b.N; i++ {\n\t\tbits.SetU64(uint64(i))\n\t}\n}\n\nfunc TestSet(t *testing.T) ", "output": "{\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}"} {"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\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 (g *grpcEvent) ContentType() string ", "output": "{\n\treturn g.contentType\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\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) Unpack(b io.Reader) ", "output": "{\n\tpc.MessageID = decodeUint16(b)\n}"} {"input": "package sqlreflect\n\nimport (\n\t\"testing\"\n)\n\n\n\nfunc TestTableConstraint_ColumnUsage(t *testing.T) ", "output": "{\n\ttable := loadTestTable(t, \"person\")\n\tcon, err := table.Constraint(\"person_pkey\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tusage, err := con.ColumnUsage()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tif usage[0].ColumnName != \"id\" {\n\t\tt.Errorf(\"Expected column name id, got %q\", usage[0].ColumnName)\n\t}\n\tif usage[0].OrdinalPosition != 1 {\n\t\tt.Errorf(\"Expected column ordinal pos to be 1, got %d\", usage[0].OrdinalPosition)\n\t}\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\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) Initform(arg Instance) (v Instance, ok bool) ", "output": "{\n\treturn nil, false\n}"} {"input": "package json\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\n\t\"k8s.io/client-go/pkg/api/unversioned\"\n)\n\n\n\ntype MetaFactory interface {\n\tInterpret(data []byte) (*unversioned.GroupVersionKind, error)\n}\n\n\n\n\nvar DefaultMetaFactory = SimpleMetaFactory{}\n\n\n\n\n\ntype SimpleMetaFactory struct {\n}\n\n\n\n\n\nfunc (SimpleMetaFactory) Interpret(data []byte) (*unversioned.GroupVersionKind, error) ", "output": "{\n\tfindKind := struct {\n\t\tAPIVersion string `json:\"apiVersion,omitempty\"`\n\t\tKind string `json:\"kind,omitempty\"`\n\t}{}\n\tif err := json.Unmarshal(data, &findKind); err != nil {\n\t\treturn nil, fmt.Errorf(\"couldn't get version/kind; json parse error: %v\", err)\n\t}\n\tgv, err := unversioned.ParseGroupVersion(findKind.APIVersion)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &unversioned.GroupVersionKind{Group: gv.Group, Version: gv.Version, Kind: findKind.Kind}, 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\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\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) start(roots *x509.CertPool) ", "output": "{\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}"} {"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\nfunc TestCancelRequest(t *testing.T) {\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}\n\n\n\nfunc testServer() *httptest.Server ", "output": "{\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}"} {"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\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 *osStream) Chan() <-chan Record ", "output": "{\n\treturn o.stream\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\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 setConfigDefaults(config *rest.Config) error ", "output": "{\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}"} {"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\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\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 Run(application runner.Application, param runner.ApplicationParameter) ", "output": "{\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}"} {"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\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) AddAction(action IAction) ", "output": "{\n\tC.g_action_map_add_action(v.native(), action.toGAction())\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\n\n\nfunc metadataServer(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\tMetadataBase = u\n\n\tdefer server.Close()\n\ttest()\n}\n\nfunc apiServer(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\tGodoBase = u\n\n\tdefer server.Close()\n\ttest()\n}"} {"input": "package ujicha\n\nimport (\n\t\"net\"\n\t\"net/http\"\n\t\"errors\"\n\t\"encoding/json\"\n\t\"bytes\"\n)\n\ntype serviceInfo struct {\n\tName string `json:\"name\"`\n\tAddress string `json:\"address\"`\n}\n\ntype bffInfo struct {\n\tName string `json:\"name\"`\n\tAddress string `json:\"address\"`\n\tDisplayName string `json:\"display_name\"`\n}\n\nfunc getLocalIP() (string, error) {\n\taddresses, err := net.InterfaceAddrs()\n\n\tif err != nil {\n\t\treturn \"\", errors.New(\"Failed to get local ip address.\")\n\t}\n\n\tfor _, address := range addresses {\n\t\tif ipnet, ok := address.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {\n\t\t\treturn ipnet.IP.String(), nil\n\t\t}\n\t}\n\n\treturn \"\", errors.New(\"Failed to get local ip address.\")\n}\n\nfunc RegisterService(serviceName string) error {\n\tlocalIP, err := getLocalIP()\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tservice := serviceInfo {\n\t\tName: serviceName,\n\t\tAddress: localIP,\n\t}\n\n\tb, err := json.Marshal(service)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\taddr := \"http://ujicha:8081/v1/service\"\n\tres, err := http.Post(addr, \"application/json\", bytes.NewBuffer(b))\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdefer res.Body.Close()\n\n\tswitch res.StatusCode {\n\tcase 409:\n\t\treturn nil\n\tcase 201:\n\t\treturn nil\n\tdefault:\n\t\treturn errors.New(\"Failed to register service\")\n\t}\n}\n\n\n\nfunc RegisterBff(bffName string, displayName string) error ", "output": "{\n\tlocalIP, err := getLocalIP()\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tbff := bffInfo {\n\t\tName: bffName,\n\t\tAddress: localIP,\n\t\tDisplayName: displayName,\n\t}\n\n\tb, err := json.Marshal(bff)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\taddr := \"http://ujicha:8081/v1/bff\"\n\tres, err := http.Post(addr, \"application/json\", bytes.NewBuffer(b))\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdefer res.Body.Close()\n\n\tswitch res.StatusCode {\n\tcase 409:\n\t\treturn nil\n\tcase 201:\n\t\treturn nil\n\tdefault:\n\t\treturn errors.New(\"Failed to register bff\")\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\n\n\n\nfunc (defaultRepoPaths) ListRepoPaths(vfs rwvfs.WalkableFileSystem, after string, max int) ([][]string, error) {\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}\n\nfunc (defaultRepoPaths) PathToRepo(path []string) string ", "output": "{\n\treturn strings.Join(path[:len(path)-1], \"/\")\n}"} {"input": "package trigger\n\nvar (\n\tallowedMethods = []string{\"GET\", \"POST\"}\n)\n\ntype rule struct {\n\tEndpoint string `mapstructure:\"endpoint\"`\n\tMethod string `mapstructure:\"method\"`\n\tHeaders map[string]string `mapstructure:\"headers\"`\n\tBody string `mapstructure:\"body\"`\n\tContentType string `mapstructure:\"content-type\"`\n}\n\n\n\nfunc (r *rule) Defaults() ", "output": "{\n\tallowedMethod := false\n\tfor _, allowed := range allowedMethods {\n\t\tif allowed == r.Method {\n\t\t\tallowedMethod = true\n\t\t\tbreak\n\t\t}\n\t}\n\tif !allowedMethod {\n\t\tr.Method = \"POST\"\n\t}\n\tif r.ContentType == \"\" {\n\t\tr.ContentType = \"application/json\"\n\t}\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\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) ColMap() map[string]string ", "output": "{\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}"} {"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\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\n\n\nfunc Benchmark_Packet_LOCAL_INFILE_Request_ToPacket(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.ToPacket(context)\n\t}\n}"} {"input": "package grpcservice\n\nimport \"google.golang.org/grpc\"\n\n\nfunc GetInstanceFromServer(grpcserver *GRPCServer) *grpc.Server {\n\treturn grpcserver.server\n}\n\n\n\n\nfunc GetInstanceFromClient(grpcclient *GRPCClient) *grpc.ClientConn ", "output": "{\n\treturn grpcclient.connection\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\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 TargetGroups) Size() int ", "output": "{\n\treturn len(r.targets)\n}"} {"input": "package mux\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 TestUnregisterHandlers(t *testing.T) {\n\tfirst := 0\n\tsecond := 0\n\n\tc := NewPathRecorderMux()\n\ts := httptest.NewServer(c)\n\tdefer s.Close()\n\n\tc.UnlistedHandleFunc(\"/secret\", func(http.ResponseWriter, *http.Request) {})\n\tc.HandleFunc(\"/nonswagger\", func(http.ResponseWriter, *http.Request) {\n\t\tfirst = first + 1\n\t})\n\tassert.NotContains(t, c.ListedPaths(), \"/secret\")\n\tassert.Contains(t, c.ListedPaths(), \"/nonswagger\")\n\n\tresp, _ := http.Get(s.URL + \"/nonswagger\")\n\tassert.Equal(t, first, 1)\n\tassert.Equal(t, resp.StatusCode, http.StatusOK)\n\n\tc.Unregister(\"/nonswagger\")\n\tassert.NotContains(t, c.ListedPaths(), \"/nonswagger\")\n\n\tresp, _ = http.Get(s.URL + \"/nonswagger\")\n\tassert.Equal(t, first, 1)\n\tassert.Equal(t, resp.StatusCode, http.StatusNotFound)\n\n\tc.HandleFunc(\"/nonswagger\", func(http.ResponseWriter, *http.Request) {\n\t\tsecond = second + 1\n\t})\n\tassert.Contains(t, c.ListedPaths(), \"/nonswagger\")\n\tresp, _ = http.Get(s.URL + \"/nonswagger\")\n\tassert.Equal(t, first, 1)\n\tassert.Equal(t, second, 1)\n\tassert.Equal(t, resp.StatusCode, http.StatusOK)\n}\n\nfunc TestSecretHandlers(t *testing.T) ", "output": "{\n\tc := NewPathRecorderMux()\n\tc.UnlistedHandleFunc(\"/secret\", func(http.ResponseWriter, *http.Request) {})\n\tc.HandleFunc(\"/nonswagger\", func(http.ResponseWriter, *http.Request) {})\n\tassert.NotContains(t, c.ListedPaths(), \"/secret\")\n\tassert.Contains(t, c.ListedPaths(), \"/nonswagger\")\n}"} {"input": "package checks\n\nimport (\n\t\"testing\"\n\n\t\"github.com/abulimov/haproxy-lint/lib\"\n)\n\nfunc TestCheckUnusedBackends(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 := CheckUnusedBackends(sections)\n\n\tif len(problems) != 1 {\n\t\tt.Errorf(\"Expected %d problems, got %d\", 1, len(problems))\n\t}\n}\n\n\n\nfunc TestCheckUnknownBackends(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 := CheckUnknownBackends(sections)\n\n\tif len(problems) != 1 {\n\t\tt.Errorf(\"Expected %d problems, got %d\", 1, len(problems))\n\t}\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\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 (rs *RestartStatistics) FailureCount() int ", "output": "{\n\treturn len(rs.failureTimes)\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\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\nfunc TestGrabCommandLineArgs(t *testing.T) {\n\tgrabCommandLineArgs()\n}\n\nfunc TestPluginRegistration(t *testing.T) ", "output": "{\n\tregisterPlugins()\n\tassert.True(t, plugin.RegistryContains(\"Logging\"))\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\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\nfunc TestConcurrent(t *testing.T) {\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}\n\nfunc TestSingle(t *testing.T) ", "output": "{\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}"} {"input": "package boottest\n\nimport (\n\t\"strings\"\n\n\t\"github.com/snapcore/snapd/asserts\"\n\t\"github.com/snapcore/snapd/snap\"\n)\n\ntype mockDevice struct {\n\tbootSnap string\n\tmode string\n\tuc20 bool\n\n\tmodel *asserts.Model\n}\n\n\n\n\n\n\n\nfunc MockDevice(s string) snap.Device {\n\tbootsnap, mode, uc20 := snapAndMode(s)\n\tif uc20 && bootsnap == \"\" {\n\t\tpanic(\"MockDevice with no snap name and @mode is unsupported\")\n\t}\n\treturn &mockDevice{\n\t\tbootSnap: bootsnap,\n\t\tmode: mode,\n\t\tuc20: uc20,\n\t}\n}\n\n\n\n\n\n\nfunc snapAndMode(str string) (snap, mode string, uc20 bool) {\n\tparts := strings.SplitN(string(str), \"@\", 2)\n\tif len(parts) == 1 || parts[1] == \"\" {\n\t\treturn parts[0], \"run\", false\n\t}\n\treturn parts[0], parts[1], true\n}\n\nfunc (d *mockDevice) Kernel() string { return d.bootSnap }\nfunc (d *mockDevice) Classic() bool { return d.bootSnap == \"\" }\nfunc (d *mockDevice) RunMode() bool { return d.mode == \"run\" }\nfunc (d *mockDevice) HasModeenv() bool { return d.uc20 }\nfunc (d *mockDevice) Base() string {\n\tif d.model != nil {\n\t\treturn d.model.Base()\n\t}\n\treturn d.bootSnap\n}\nfunc (d *mockDevice) Model() *asserts.Model {\n\tif d.model == nil {\n\t\tpanic(\"Device.Model called but MockUC20Device not used\")\n\t}\n\treturn d.model\n}\n\nfunc MockUC20Device(mode string, model *asserts.Model) snap.Device ", "output": "{\n\tif mode == \"\" {\n\t\tmode = \"run\"\n\t}\n\tif model == nil {\n\t\tmodel = MakeMockUC20Model()\n\t}\n\treturn &mockDevice{\n\t\tbootSnap: model.Kernel(),\n\t\tmode: mode,\n\t\tuc20: true,\n\t\tmodel: model,\n\t}\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\n\n\nfunc (t *test_t) Result() bool {\n\treturn true\n}\n\nfunc (t *test_t) Test() test_i ", "output": "{\n\treturn t\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\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 TestRemovePackage(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\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}"} {"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\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\n\n\n\nvar _ (acl.ACL) = (*SimpleAcl)(nil)\n\n\nvar _ (acl.Factory) = (*Factory)(nil)\n\nfunc (factory *Factory) AllString() string ", "output": "{\n\treturn all\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\nfunc basicAuthenticate(req *restful.Request, resp *restful.Response, chain *restful.FilterChain) {\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}\n\n\n\nfunc secret(req *restful.Request, resp *restful.Response) ", "output": "{\n io.WriteString(resp, \"42\")\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) ListParameterWithContext(ctx context.Context, req *ListParameterRequest) ([]*Parameter, error) {\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}\n\nfunc (s *Service) ListParameter(req *ListParameterRequest) ([]*Parameter, error) ", "output": "{\n\treturn s.ListParameterWithContext(context.Background(), req)\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\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\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 NewPlainResult(statusCode int, body string) Result ", "output": "{\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}"} {"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\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) User() *storage.Collection ", "output": "{\n\treturn s.Collection(\"user\")\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\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 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\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\nfunc TestMetricValueDataType_IsMonotonic(t *testing.T) {\n\tvalueDataType := metricValueDataType{isMonotonic: true}\n\n\tassert.True(t, valueDataType.IsMonotonic())\n}\n\nfunc TestNewMetricDataType(t *testing.T) ", "output": "{\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}"} {"input": "package xcpretty\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/bitrise-io/go-utils/log\"\n\t\"github.com/bitrise-io/go-xcode/v2/xcpretty\"\n\t\"github.com/hashicorp/go-version\"\n)\n\n\ntype Installer interface {\n\tInstall() (*version.Version, error)\n}\n\ntype installer struct {\n\txcpretty xcpretty.Xcpretty\n}\n\n\n\n\n\nfunc (i installer) Install() (*version.Version, error) {\n\tfmt.Println()\n\tlog.Infof(\"Checking if output tool (xcpretty) is installed\")\n\n\tinstalled, err := i.xcpretty.IsInstalled()\n\tif err != nil {\n\t\treturn nil, err\n\t} else if !installed {\n\t\tlog.Warnf(`xcpretty is not installed`)\n\t\tfmt.Println()\n\t\tlog.Printf(\"Installing xcpretty\")\n\n\t\tcmdModelSlice, err := i.xcpretty.Install()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to install xcpretty: %s\", err)\n\t\t}\n\n\t\tfor _, cmd := range cmdModelSlice {\n\t\t\tif err := cmd.Run(); err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"failed to install xcpretty: %s\", err)\n\t\t\t}\n\t\t}\n\t}\n\n\txcprettyVersion, err := i.xcpretty.Version()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to determine xcpretty version: %s\", err)\n\t}\n\treturn xcprettyVersion, nil\n}\n\nfunc NewInstaller(xcpretty xcpretty.Xcpretty) Installer ", "output": "{\n\treturn &installer{\n\t\txcpretty: xcpretty,\n\t}\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\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) SetSafekeepingAccount(value string) ", "output": "{\n\tp.SafekeepingAccount = (*Max35Text)(&value)\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\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 PossibleStepTypeValues() []StepType ", "output": "{\n\treturn []StepType{StepTypeStepProperties, StepTypeWait}\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\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\n\n\nfunc readSecretFrom(fname string) (*[]byte, error) ", "output": "{\n\tbytes, err := ioutil.ReadFile(fname)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &bytes, nil\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\nfunc (this *Retry) shouldRetry(err error) bool {\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}\n\n\n\nfunc (this *Retry) CallWithRetries(name string, call func() error) error ", "output": "{\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}"} {"input": "package migrate\n\nimport (\n\t\"github.com/gophercloud/gophercloud\"\n)\n\n\n\n\nfunc Migrate(client *gophercloud.ServiceClient, id string) (r MigrateResult) ", "output": "{\n\t_, r.Err = client.Post(actionURL(client, id), map[string]interface{}{\"migrate\": nil}, nil, nil)\n\treturn\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\nfunc GetOpenProjectsOnPage(tickData JSONGetter, page int) (Projects, error) {\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}\n\n\n\nfunc GetProject(tickData JSONGetter, projectID int) (Project, error) ", "output": "{\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}"} {"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\nfunc (response ChangeDeploymentCompartmentResponse) String() string {\n\treturn common.PointerString(response)\n}\n\n\n\n\nfunc (response ChangeDeploymentCompartmentResponse) HTTPResponse() *http.Response ", "output": "{\n\treturn response.RawResponse\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\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 PutInt64LE(dest []byte, i int64) ", "output": "{\n\tbinary.LittleEndian.PutUint64(dest, uint64(i))\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\nfunc (s *LinkService) Get(hash string) (*shopy.Link, error) {\n\tlink := &shopy.Link{}\n\terr := s.DB.Get(link, \"SELECT * FROM links WHERE hash=?\", hash)\n\n\treturn link, err\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\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) Update(l *shopy.Link, fields ...string) error ", "output": "{\n\t_, err := s.DB.NamedExec(updateQuery(\"links\", \"hash\", fieldsToColumns(linkMap, fields...)), l)\n\treturn err\n}"} {"input": "package cmd\n\nimport (\n\t\"github.com/spf13/cobra\"\n)\n\n\nvar rotateCmd = &cobra.Command{\n\tUse: \"rotate\",\n\tShort: \"Rotates children of internal nodes\",\n\tLong: `Rotates children of internal nodes by different means.\n\nEither randomly with \"rand\" subcommand, either sorting by number of tips\nwith \"sort\" subcommand.\n\nIt does not change the topology, but just the order of neighbors \nof all node and thus the newick representation.\n\n ------C ------A\n x |z\t \t x |z\t \n A---------*ROOT => B---------*ROOT \n |t\t \t |t\t \t \n ------B \t ------C\n\nExample of usage:\n\ngotree rotate rand -i t.nw\ngotree rotate sort -i t.nw\n`,\n}\n\n\n\nfunc init() ", "output": "{\n\tRootCmd.AddCommand(rotateCmd)\n\trotateCmd.PersistentFlags().StringVarP(&intreefile, \"input\", \"i\", \"stdin\", \"Input tree\")\n\trotateCmd.PersistentFlags().StringVarP(&outtreefile, \"output\", \"o\", \"stdout\", \"Rotated tree output file\")\n}"} {"input": "package healthcheck\n\nimport (\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/resolver\"\n)\n\nconst (\n\tupsMaxFails = \"ingress.kubernetes.io/upstream-max-fails\"\n\tupsFailTimeout = \"ingress.kubernetes.io/upstream-fail-timeout\"\n)\n\n\n\ntype Upstream struct {\n\tMaxFails int `json:\"maxFails\"`\n\tFailTimeout int `json:\"failTimeout\"`\n}\n\ntype healthCheck struct {\n\tbackendResolver resolver.DefaultBackend\n}\n\n\nfunc NewParser(br resolver.DefaultBackend) parser.IngressAnnotation {\n\treturn healthCheck{br}\n}\n\n\n\n\n\nfunc (a healthCheck) Parse(ing *extensions.Ingress) (interface{}, error) ", "output": "{\n\tdefBackend := a.backendResolver.GetDefaultBackend()\n\tif ing.GetAnnotations() == nil {\n\t\treturn &Upstream{defBackend.UpstreamMaxFails, defBackend.UpstreamFailTimeout}, nil\n\t}\n\n\tmf, err := parser.GetIntAnnotation(upsMaxFails, ing)\n\tif err != nil {\n\t\tmf = defBackend.UpstreamMaxFails\n\t}\n\n\tft, err := parser.GetIntAnnotation(upsFailTimeout, ing)\n\tif err != nil {\n\t\tft = defBackend.UpstreamFailTimeout\n\t}\n\n\treturn &Upstream{mf, ft}, nil\n}"} {"input": "package pipe\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n)\n\nfunc TestReduceChan(t *testing.T) {\n\tin := make(chan int, 5)\n\n\tgo func() {\n\t\tin <- 5\n\t\tin <- 10\n\t\tin <- 20\n\t\tclose(in)\n\t}()\n\n\tout := ReduceChan(sum, 0, in).(int)\n\n\tif out != 35 {\n\t\tt.Fatal(\"ReduceChan(sum, 0, []int{5, 10, 20}) output \", out)\n\t}\n}\n\n\n\nfunc TestReduceChanTypeCoercion(t *testing.T) ", "output": "{\n\tappendToString := func(str string, item fmt.Stringer) string {\n\t\treturn fmt.Sprintf(\"%s%s\", str, item.String())\n\t}\n\n\tin := make(chan testStringer, 5)\n\n\tgo func() {\n\t\tin <- 1\n\t\tin <- 2\n\t\tin <- 3\n\t\tclose(in)\n\t}()\n\n\tout := ReduceChan(appendToString, \"a\", in).(string)\n\n\tif out != \"a123\" {\n\t\tt.Fatal(\"ReduceChan(appendToString, \\\"a\\\", chan testStringer) output \", out)\n\t}\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\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\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) TokenizerNamed(name string, cache *Cache) (analysis.Tokenizer, error) ", "output": "{\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}"} {"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\n\n\nfunc initData() {\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}\n\nfunc TestMain(m *testing.M) ", "output": "{\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}"} {"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\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 (s *set) add(element string) ", "output": "{\n\ts.els[element] = nil\n}"} {"input": "package main\n\nimport (\n\t\"github.com/bmizerany/assert\"\n\t\"testing\"\n)\n\n\n\nfunc TestTemplatesCompile(t *testing.T) ", "output": "{\n\ttemplates := getTemplates()\n\tassert.NotEqual(t, templates, 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\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) Top() byte ", "output": "{\n\tlength := len(*s)\n\tif 0 == length {\n\t\treturn 0\n\t}\n\treturn (*s)[length-1]\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\n\n\nfunc download(link, output string) error {\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}\n\nfunc BulkDownload(list []string, output string) error ", "output": "{\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}"} {"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\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\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 init() ", "output": "{\n\tcommands = make(map[string]RunFunc)\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\n\n\nfunc (cmd *getCommand) getDEPAccount(args []string) error {\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}\n\nfunc (out *depaccountTableOutput) BasicFooter() ", "output": "{\n\tout.w.Flush()\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n)\n\nfunc parseM3uPlaylist(data string) (songs []*SongRecord) {\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}\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\n\n\nfunc writePlsPlaylist(songs []*SongRecord) error ", "output": "{\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}"} {"input": "package decision\n\nimport (\n\t\"math\"\n\t\"testing\"\n\n\tkey \"github.com/ipfs/go-ipfs/blocks/key\"\n\t\"github.com/ipfs/go-ipfs/exchange/bitswap/wantlist\"\n\t\"github.com/ipfs/go-ipfs/util/testutil\"\n\t\"gx/ipfs/QmUBogf4nUefBjmYjn6jfsfPJRkmDGSeMhNj4usRKq69f4/go-libp2p/p2p/peer\"\n)\n\n\n\n\n\nfunc BenchmarkTaskQueuePush(b *testing.B) ", "output": "{\n\tq := newPRQ()\n\tpeers := []peer.ID{\n\t\ttestutil.RandPeerIDFatal(b),\n\t\ttestutil.RandPeerIDFatal(b),\n\t\ttestutil.RandPeerIDFatal(b),\n\t}\n\tb.ResetTimer()\n\tfor i := 0; i < b.N; i++ {\n\t\tq.Push(wantlist.Entry{Key: key.Key(i), Priority: math.MaxInt32}, peers[i%len(peers)])\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\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 (f *TForm) PlatformWindow() NSWindow ", "output": "{\n\tr, _, _ := NSWindow_FromForm.Call(f.instance)\n\treturn NSWindow(r)\n}"} {"input": "package configuration_test\n\nimport (\n\t. \"github.com/onsi/ginkgo\"\n\t. \"github.com/onsi/gomega\"\n\n\t\"testing\"\n)\n\n\n\nfunc TestConfig(t *testing.T) ", "output": "{\n\tRegisterFailHandler(Fail)\n\tRunSpecs(t, \"Config Suite\")\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\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\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 NewMockCommandRunner(ctrl *gomock.Controller) *MockCommandRunner ", "output": "{\n\tmock := &MockCommandRunner{ctrl: ctrl}\n\tmock.recorder = &MockCommandRunnerMockRecorder{mock}\n\treturn mock\n}"} {"input": "package entities\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\n\n\nfunc TestCreatesCorrectly(t *testing.T) ", "output": "{\n\tregistration := CreateNewRegistration(\"myevent\", \"mycallback\")\n\n\tassert.NotZero(t, registration.Id)\n\tassert.NotZero(t, registration.CreationDate)\n\tassert.Equal(t, \"myevent\", registration.EventName)\n\tassert.Equal(t, \"mycallback\", registration.CallbackUrl)\n}"} {"input": "package go_n1ql\n\ntype n1qlResult struct {\n\taffectedRows int64\n\tinsertId int64\n}\n\n\n\nfunc (res *n1qlResult) RowsAffected() (int64, error) {\n\treturn res.affectedRows, nil\n}\n\nfunc (res *n1qlResult) LastInsertId() (int64, error) ", "output": "{\n\treturn res.insertId, nil\n}"} {"input": "package rule\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/mgechev/revive/lint\"\n)\n\n\ntype ImportsBlacklistRule struct {\n\tblacklist map[string]bool\n}\n\n\nfunc (r *ImportsBlacklistRule) Apply(file *lint.File, arguments lint.Arguments) []lint.Failure {\n\tvar failures []lint.Failure\n\n\tif file.IsTest() {\n\t\treturn failures \n\t}\n\n\tif r.blacklist == nil {\n\t\tr.blacklist = make(map[string]bool, len(arguments))\n\n\t\tfor _, arg := range arguments {\n\t\t\targStr, ok := arg.(string)\n\t\t\tif !ok {\n\t\t\t\tpanic(fmt.Sprintf(\"Invalid argument to the imports-blacklist rule. Expecting a string, got %T\", arg))\n\t\t\t}\n\t\t\tif len(argStr) > 2 && argStr[0] != '\"' && argStr[len(argStr)-1] != '\"' {\n\t\t\t\targStr = fmt.Sprintf(`%q`, argStr)\n\t\t\t}\n\t\t\tr.blacklist[argStr] = true\n\t\t}\n\t}\n\n\tfor _, is := range file.AST.Imports {\n\t\tpath := is.Path\n\t\tif path != nil && r.blacklist[path.Value] {\n\t\t\tfailures = append(failures, lint.Failure{\n\t\t\t\tConfidence: 1,\n\t\t\t\tFailure: \"should not use the following blacklisted import: \" + path.Value,\n\t\t\t\tNode: is,\n\t\t\t\tCategory: \"imports\",\n\t\t\t})\n\t\t}\n\t}\n\n\treturn failures\n}\n\n\n\n\nfunc (r *ImportsBlacklistRule) Name() string ", "output": "{\n\treturn \"imports-blacklist\"\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\nfunc onTouchStart(x, y float32) { sendTouch(event.TouchStart, x, y) }\n\n\nfunc onTouchMove(x, y float32) { sendTouch(event.TouchMove, x, y) }\n\n\n\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 onTouchEnd(x, y float32) ", "output": "{ sendTouch(event.TouchEnd, x, y) }"} {"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\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) GetCollectionData(slug string) (Collection, error) ", "output": "{\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}"} {"input": "package web\n\n\n\nfunc SetKey(key string) {\n\tclient.setKey(key)\n}\n\nfunc SetNodeId(nodeId int) {\n\tclient.setNodeId(nodeId)\n}\n\nfunc SetBaseUrl(baseUrl string) ", "output": "{\n\tclient.setBaseUrl(baseUrl)\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\nfunc (c *TimeoutConn) Read(b []byte) (n int, err error) {\n\tc.setReadTimeout()\n\treturn c.Conn.Read(b)\n}\n\n\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) Write(b []byte) (n int, err error) ", "output": "{\n\tc.setWriteTimeout()\n\treturn c.Conn.Write(b)\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\nfunc WaitForTPRReady(restClient *rest.RESTClient, tprGroup, tprVersion, tprName string) error {\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}\n\n\n\n\n\nfunc PodRunningAndReady(pod v1.Pod) (bool, error) ", "output": "{\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}"} {"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\nfunc (e *apiError) Empty() bool {\n\treturn len(e.Errors) == 0\n}\n\n\n\n\n\n\nfunc relevantError(httpError error, ae apiError) error ", "output": "{\n\tif httpError != nil {\n\t\treturn httpError\n\t}\n\tif ae.Empty() {\n\t\treturn nil\n\t}\n\treturn ae\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\n\n\nfunc (n *NoopLeaseManager) SetLeaseVerifier(leaseVerifier LeaseVerifier) error {\n\treturn nil\n}\n\nfunc (n *NoopLeaseManager) UpdateOpenLeases(\n\tdescriptor LeaseDescriptor,\n\tstate LeaseState,\n) (UpdateLeasesResult, error) ", "output": "{\n\treturn UpdateLeasesResult{}, nil\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\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\n\n\nfunc TestParseTokenParams(t *testing.T) ", "output": "{\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}"} {"input": "package proxyprotocol\n\nimport (\n\t\"net\"\n)\n\ntype listener struct {\n\traw net.Listener\n}\n\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\nfunc (l *listener) Addr() net.Addr {\n\treturn l.raw.Addr()\n}\n\nfunc Listen(raw net.Listener) net.Listener ", "output": "{\n\treturn &listener{raw}\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\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) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error ", "output": "{\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}"} {"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\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\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 SignMessage(message, secret []byte) []byte ", "output": "{\n\tsignature := generateSignature(message, secret)\n\treturn append(signature, message...)\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\n\n\n\nfunc DeleteLabel(meta *metav1.ObjectMeta, key string) {\n\tdelete(meta.Labels, key)\n}\n\nfunc SetLabel(meta *metav1.ObjectMeta, key, value string) ", "output": "{\n\tif meta.Labels == nil {\n\t\tmeta.Labels = make(map[string]string, 1)\n\t}\n\n\tmeta.Labels[key] = value\n}"} {"input": "package minecraft\n\nimport (\n\t\"io\"\n\t\"github.com/LilyPad/GoLilyPad/packet\"\n)\n\ntype packetServerPluginMessageCodec17 struct {\n\n}\n\n\n\nfunc (this *packetServerPluginMessageCodec17) 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\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}\n\nfunc (this *packetServerPluginMessageCodec17) Decode(reader io.Reader) (decode packet.Packet, err error) ", "output": "{\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}"} {"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\nfunc NewPopulatedClient() clientset.Interface {\n\treturn fake.NewSimpleClientset(\n\t\tNewRuntimeClass(EmptyRuntimeClass, \"\"),\n\t\tNewRuntimeClass(SandboxRuntimeClass, SandboxRuntimeHandler),\n\t)\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\n\n\nfunc NewRuntimeClass(name, handler string) *nodev1.RuntimeClass ", "output": "{\n\treturn &nodev1.RuntimeClass{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: name,\n\t\t},\n\t\tHandler: handler,\n\t}\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\nfunc (h *HopField) DecodeFromBytes(raw []byte) error {\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}\n\n\n\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) SerializeTo(b []byte) error ", "output": "{\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}"} {"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\n\n\n\nfunc (defaultRepoPaths) PathToRepo(path []string) string {\n\treturn strings.Join(path[:len(path)-1], \"/\")\n}\n\n\nfunc (defaultRepoPaths) ListRepoPaths(vfs rwvfs.WalkableFileSystem, after string, max int) ([][]string, error) {\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}\n\nfunc (defaultRepoPaths) RepoToPath(repo string) []string ", "output": "{\n\tp := strings.Split(repo, \"/\")\n\tp = append(p, SrclibStoreDir)\n\treturn p\n}"} {"input": "package datamodel\n\nimport (\n\tpb \"datamodel/protobuf\"\n\t\"fmt\"\n\t\"utils\"\n)\n\n\ntype Info struct {\n\t*pb.Sketch\n\tlocked bool\n\tid string\n}\n\n\nfunc (info *Info) ID() string {\n\tif len(info.id) == 0 {\n\t\tinfo.id = fmt.Sprintf(\"%s.%s\", info.GetName(), info.GetType())\n\t}\n\treturn info.id\n}\n\n\nfunc (info *Info) Locked() bool {\n\treturn info.locked\n}\n\n\nfunc (info *Info) Lock() {\n\tinfo.locked = true\n}\n\n\nfunc (info *Info) Unlock() {\n\tinfo.locked = false\n}\n\n\n\n\n\nfunc NewEmptyProperties() *pb.SketchProperties {\n\treturn &pb.SketchProperties{\n\t\tErrorRate: utils.Float32p(0),\n\t\tMaxUniqueItems: utils.Int64p(0),\n\t\tSize: utils.Int64p(0),\n\t}\n}\n\n\nfunc NewEmptyState() *pb.SketchState {\n\treturn &pb.SketchState{\n\t\tFillRate: utils.Float32p(0),\n\t\tLastSnapshot: utils.Int64p(0),\n\t}\n}\n\n\nfunc NewEmptyInfo() *Info {\n\tsketch := &pb.Sketch{\n\t\tProperties: NewEmptyProperties(),\n\t\tState: NewEmptyState(),\n\t}\n\treturn &Info{Sketch: sketch, locked: false}\n}\n\nfunc (info *Info) Copy() *Info ", "output": "{\n\ttyp := info.GetType()\n\treturn &Info{\n\t\tSketch: &pb.Sketch{\n\t\t\tProperties: &pb.SketchProperties{\n\t\t\t\tErrorRate: utils.Float32p(info.Properties.GetErrorRate()),\n\t\t\t\tMaxUniqueItems: utils.Int64p(info.Properties.GetMaxUniqueItems()),\n\t\t\t\tSize: utils.Int64p(info.Properties.GetSize()),\n\t\t\t},\n\t\t\tState: &pb.SketchState{\n\t\t\t\tFillRate: utils.Float32p(info.State.GetFillRate()),\n\t\t\t\tLastSnapshot: utils.Int64p(info.State.GetLastSnapshot()),\n\t\t\t},\n\t\t\tName: utils.Stringp(info.GetName()),\n\t\t\tType: &typ,\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\nfunc NewTTLCache(ttl time.Duration) TTLCache {\n\treturn &ttlCache{\n\t\tttl: ttl,\n\t\tcache: make(map[string]*ttlCacheEntry),\n\t}\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\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 (t *ttlCache) Get(key string) (value interface{}, expired bool, ok bool) ", "output": "{\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}"} {"input": "\n\nfunc swapPairs(head *ListNode) *ListNode ", "output": "{\n pair := &ListNode{0, nil}\n dummy := pair\n dummy.Next = head\n for head != nil && head.Next != nil {\n tmp_next := head.Next\n head.Next = tmp_next.Next\n tmp_next.Next = head\n pair.Next = tmp_next\n head = head.Next\n pair = tmp_next.Next\n }\n return dummy.Next\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\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 b(s string) string ", "output": "{\n\tlog += \"b\"\n\treturn s\n}"} {"input": "package migration\n\nimport (\n\t\"github.com/jmoiron/sqlx\"\n)\n\ntype revision_db76e79e987 struct {\n}\n\nfunc (r *revision_db76e79e987) Version() string { return \"db76e79e987\" }\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\n\n\nfunc (r *revision_db76e79e987) Down(tx *sqlx.Tx) error ", "output": "{\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}"} {"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\n\n\ntype CentosHostInfo struct{}\n\nfunc (tpl *CentosHostInfo) Render(p urknall.Package) {\n\tp.AddTemplate(\"hostinfo\", &CentosHostInfoTemplate{})\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 init() ", "output": "{\n\tcentoshostinfo = &CentosHostInfo{}\n\ttemplates.Register(\"CentosHostInfo\", centoshostinfo)\n}"} {"input": "package rs\n\nimport (\n\t\"crypto/sha1\"\n\t\"encoding/base64\"\n\t\"io\"\n\t\"net/http\"\n\t\"testing\"\n)\n\n\n\nfunc TestGetPrivateUrl(t *testing.T) {\n\n\terr := upFile(\"token.go\", bucketName, key)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdefer client.Delete(nil, bucketName, key)\n\n\tbaseUrl := MakeBaseUrl(domain, key)\n\n\tpolicy := GetPolicy{}\n\tprivateUrl := policy.MakeRequest(baseUrl, nil)\n\n\tresp, err := http.Get(privateUrl)\n\tif err != nil {\n\t\tt.Fatal(\"http.Get failed:\", err)\n\t}\n\tdefer resp.Body.Close()\n\n\th := sha1.New()\n\tio.Copy(h, resp.Body)\n\tetagExpected := base64.URLEncoding.EncodeToString(h.Sum([]byte{'\\x16'}))\n\n\tetag := resp.Header.Get(\"Etag\")\n\tif etag[1:len(etag)-1] != etagExpected {\n\t\tt.Fatal(\"http.Get etag failed:\", etag, etagExpected)\n\t}\n\n}\n\nfunc init() ", "output": "{\n\tclient = New(nil)\n\tclient.Delete(nil, bucketName, key)\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\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_1) Execute(frame *rtda.Frame) ", "output": "{\n\t_astore(frame, 1)\n}"} {"input": "package s3gof3r\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"net/http\"\n\t\"os\"\n\t\"time\"\n)\n\n\n\ntype Keys struct {\n\tAccessKey string\n\tSecretKey string\n\tSecurityToken string\n}\n\ntype mdCreds struct {\n\tCode string\n\tLastUpdated string\n\tType string\n\tAccessKeyId string\n\tSecretAccessKey string\n\tToken string\n\tExpiration string\n}\n\n\n\nfunc InstanceKeys() (keys Keys, err error) {\n\n\trolePath := \"http://169.254.169.254/latest/meta-data/iam/security-credentials/\"\n\tvar creds mdCreds\n\n\tresp, err := ClientWithTimeout(2 * time.Second).Get(rolePath)\n\tif err != nil {\n\t\treturn\n\t}\n\tdefer checkClose(resp.Body, &err)\n\tif resp.StatusCode != 200 {\n\t\terr = newRespError(resp)\n\t\treturn\n\t}\n\trole, err := ioutil.ReadAll(resp.Body)\n\n\tif err != nil {\n\t\treturn\n\t}\n\n\tresp, err = http.Get(rolePath + string(role))\n\tif err != nil {\n\t\treturn\n\t}\n\tdefer checkClose(resp.Body, &err)\n\tif resp.StatusCode != 200 {\n\t\terr = newRespError(resp)\n\t\treturn\n\t}\n\tmetadata, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tif err = json.Unmarshal([]byte(metadata), &creds); err != nil {\n\t\treturn\n\t}\n\tkeys = Keys{AccessKey: creds.AccessKeyId,\n\t\tSecretKey: creds.SecretAccessKey,\n\t\tSecurityToken: creds.Token,\n\t}\n\n\treturn\n}\n\n\n\n\nfunc EnvKeys() (keys Keys, err error) ", "output": "{\n\tkeys = Keys{AccessKey: os.Getenv(\"AWS_ACCESS_KEY_ID\"),\n\t\tSecretKey: os.Getenv(\"AWS_SECRET_ACCESS_KEY\"),\n\t}\n\tif keys.AccessKey == \"\" || keys.SecretKey == \"\" {\n\t\terr = fmt.Errorf(\"keys not set in environment: AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY\")\n\t}\n\treturn\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\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\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 TestSliceStackPush(t *testing.T) ", "output": "{\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}"} {"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\nfunc (r *AWSAmazonMQBroker_MaintenanceWindow) SetMetadata(metadata map[string]interface{}) {\n\tr._metadata = metadata\n}\n\n\n\n\n\nfunc (r *AWSAmazonMQBroker_MaintenanceWindow) SetDeletionPolicy(policy policies.DeletionPolicy) ", "output": "{\n\tr._deletionPolicy = policy\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\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 chmodTarEntry(perm os.FileMode) os.FileMode ", "output": "{\n\tperm &= 0755\n\tperm |= 0111\n\n\treturn perm\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) { }\n\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) Init(conn *iris.Connection) error ", "output": "{ return nil }"} {"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\n\n\nfunc (_ XPathExec) MustExec(_ interface{}, _ ...FuncOpts) interface{} {\n\treturn nil\n}\n\nfunc (_ XPathExec) ExecNum(_ interface{}, _ ...FuncOpts) (float64, error) ", "output": "{\n\treturn 0, nil\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\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 PossibleNameAvailabilityReasonValues() []NameAvailabilityReason ", "output": "{\n\treturn []NameAvailabilityReason{NameAvailabilityReasonAlreadyExists, NameAvailabilityReasonInvalid, NameAvailabilityReasonNotSpecified}\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\nfunc (response DeleteUserResponse) String() string {\n\treturn common.PointerString(response)\n}\n\n\n\n\nfunc (response DeleteUserResponse) HTTPResponse() *http.Response ", "output": "{\n\treturn response.RawResponse\n}"} {"input": "package main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"github.com/cross-dev/script-server/Godeps/_workspace/src/github.com/onsi/ginkgo/config\"\n)\n\nfunc BuildVersionCommand() *Command {\n\treturn &Command{\n\t\tName: \"version\",\n\t\tFlagSet: flag.NewFlagSet(\"version\", flag.ExitOnError),\n\t\tUsageCommand: \"ginkgo version\",\n\t\tUsage: []string{\n\t\t\t\"Print Ginkgo's version\",\n\t\t},\n\t\tCommand: printVersion,\n\t}\n}\n\n\n\nfunc printVersion([]string, []string) ", "output": "{\n\tfmt.Printf(\"Ginkgo Version %s\\n\", config.VERSION)\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\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\n\n\nfunc (o *GetWorkflowsLibraryParams) 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 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\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}\n\n\nfunc (l *logReader) reset() ", "output": "{\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}"} {"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 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 atomicloadp(ptr unsafe.Pointer) unsafe.Pointer ", "output": "{\n\tnop()\n\treturn *(*unsafe.Pointer)(ptr)\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\n\n\n\nfunc GetType(name string) (Type, bool) {\n\tt, f := typesByName[name]\n\treturn t, f\n}\n\nfunc (t Type) String() string ", "output": "{\n\treturn typeNames[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\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\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) AddSeries() SurfaceChartSeries ", "output": "{\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}"} {"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\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 (d dockerClientMock) Events(ctx context.Context, options types.EventsOptions) (<-chan events.Message, <-chan error) ", "output": "{\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}"} {"input": "package authy\n\nimport (\n\t\"github.com/tg123/sshpiper/sshpiperd/challenger\"\n)\n\nfunc (authyClient) GetName() string {\n\treturn \"authy\"\n}\n\n\n\nfunc (a *authyClient) GetHandler() challenger.Handler {\n\treturn a.challenge\n}\n\nfunc init() {\n\tchallenger.Register(\"authy\", &authyClient{})\n}\n\nfunc (a *authyClient) GetOpts() interface{} ", "output": "{\n\treturn &a.Config\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\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\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 NewInstallationLog(service installationLogService, logger logger) InstallationLog ", "output": "{\n\treturn InstallationLog{\n\t\tservice: service,\n\t\tlogger: logger,\n\t}\n}"} {"input": "package swt\n\nimport \"github.com/timob/javabind\"\nimport \"unsafe\"\n\n\n\nimport \"C\"\n\nfunc go_callback_EventsMenuDetectListenerNative_MenuDetected(env unsafe.Pointer, obj uintptr, arg_0 uintptr) {\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}\n\nvar EventsMenuDetectListenerNativeMap = make(map[int]EventsMenuDetectListenerInterface)\n\ntype EventsMenuDetectListenerNative struct {\n\t*javabind.Callable\n\tEventsMenuDetectListenerInterface\n}\n\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 NewEventsMenuDetectListenerNative(implementation EventsMenuDetectListenerInterface) *EventsMenuDetectListenerNative ", "output": "{\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}"} {"input": "package math\n\n\n\n\n\n\n\n\n\nfunc Nextafter(x, y float64) (r float64) ", "output": "{\n\tswitch {\n\tcase x != x || y != y: \n\t\tr = NaN()\n\tcase x == y:\n\t\tr = x\n\tcase x == 0:\n\t\tr = Copysign(Float64frombits(1), y)\n\tcase (y > x) == (x > 0):\n\t\tr = Float64frombits(Float64bits(x) + 1)\n\tdefault:\n\t\tr = Float64frombits(Float64bits(x) - 1)\n\t}\n\treturn\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\n\n\n\n\n\nfunc NewStatmFromReader(reader io.Reader) (*Statm, error) {\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}\n\nfunc NewStatm(pid int) (*Statm, error) ", "output": "{\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}"} {"input": "package authorizationutil\n\nimport (\n\trbacv1 \"k8s.io/api/rbac/v1\"\n\t\"k8s.io/apiserver/pkg/authentication/serviceaccount\"\n)\n\nfunc BuildRBACSubjects(users, groups []string) []rbacv1.Subject {\n\tsubjects := []rbacv1.Subject{}\n\n\tfor _, user := range users {\n\t\tsaNamespace, saName, err := serviceaccount.SplitUsername(user)\n\t\tif err == nil {\n\t\t\tsubjects = append(subjects, rbacv1.Subject{Kind: rbacv1.ServiceAccountKind, Namespace: saNamespace, Name: saName})\n\t\t} else {\n\t\t\tsubjects = append(subjects, rbacv1.Subject{Kind: rbacv1.UserKind, APIGroup: rbacv1.GroupName, Name: user})\n\t\t}\n\t}\n\n\tfor _, group := range groups {\n\t\tsubjects = append(subjects, rbacv1.Subject{Kind: rbacv1.GroupKind, APIGroup: rbacv1.GroupName, Name: group})\n\t}\n\n\treturn subjects\n}\n\n\n\nfunc RBACSubjectsToUsersAndGroups(subjects []rbacv1.Subject, defaultNamespace string) (users []string, groups []string) ", "output": "{\n\tfor _, subject := range subjects {\n\n\t\tswitch {\n\t\tcase subject.APIGroup == rbacv1.GroupName && subject.Kind == rbacv1.GroupKind:\n\t\t\tgroups = append(groups, subject.Name)\n\t\tcase subject.APIGroup == rbacv1.GroupName && subject.Kind == rbacv1.UserKind:\n\t\t\tusers = append(users, subject.Name)\n\t\tcase subject.APIGroup == \"\" && subject.Kind == rbacv1.ServiceAccountKind:\n\t\t\tns := defaultNamespace\n\t\t\tif len(subject.Namespace) > 0 {\n\t\t\t\tns = subject.Namespace\n\t\t\t}\n\t\t\tif len(ns) > 0 {\n\t\t\t\tname := serviceaccount.MakeUsername(ns, subject.Name)\n\t\t\t\tusers = append(users, name)\n\t\t\t} else {\n\t\t\t}\n\t\tdefault:\n\t\t}\n\t}\n\n\treturn users, groups\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\nfunc NewCommand(name string) *CleanCommand {\n\treturn &CleanCommand{flags: flag.NewFlagSet(name, flag.ExitOnError)}\n}\n\n\n\n\nfunc (c *CleanCommand) Run(parser *dockerfile.Parser, args []string) error ", "output": "{\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}"} {"input": "package integration\n\nimport . \"gopkg.in/check.v1\"\n\n\n\nfunc (s *QemuSuite) TestLenientServiceParsing(c *C) ", "output": "{\n\ts.RunQemu(c, \"--cloud-config\", \"./tests/assets/test_19/cloud-config.yml\")\n\n\ts.CheckCall(c, `\nsleep 5\nsudo system-docker ps -a | grep test-parsing`)\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\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 DefaultDuration(value *time.Duration, defaultValue time.Duration) *time.Duration ", "output": "{\n\tif value == nil {\n\t\treturn &defaultValue\n\t}\n\treturn value\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\nfunc (c *Client) CreateWithdrawalCrypto(newWithdrawalCrypto *WithdrawalCrypto) (WithdrawalCrypto, error) {\n\tvar savedWithdrawal WithdrawalCrypto\n\turl := fmt.Sprintf(\"/withdrawals/crypto\")\n\t_, err := c.Request(\"POST\", url, newWithdrawalCrypto, &savedWithdrawal)\n\treturn savedWithdrawal, err\n}\n\n\n\nfunc (c *Client) CreateWithdrawalCoinbase(newWithdrawalCoinbase *WithdrawalCoinbase) (WithdrawalCoinbase, error) ", "output": "{\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}"} {"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\nfunc (d *Digest) Reset() {\n\td.md5.Reset()\n\td.crc32c.Reset()\n}\n\n\n\n\nfunc (d *Digest) Checksums() Checksums ", "output": "{\n\treturn Checksums{\n\t\tMD5: d.md5.Sum(nil),\n\t\tCRC32C: int32(d.crc32c.Sum32()),\n\t\tHasCRC32C: true,\n\t}\n}"} {"input": "package gzip\n\nimport (\n\t\"compress/gzip\"\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"net/http\"\n\t\"path/filepath\"\n\t\"strings\"\n\t\"sync\"\n\n\t\"github.com/gin-gonic/gin\"\n)\n\nconst (\n\tBestCompression = gzip.BestCompression\n\tBestSpeed = gzip.BestSpeed\n\tDefaultCompression = gzip.DefaultCompression\n\tNoCompression = gzip.NoCompression\n)\n\n\n\ntype gzipWriter struct {\n\tgin.ResponseWriter\n\twriter *gzip.Writer\n}\n\nfunc (g *gzipWriter) WriteString(s string) (int, error) {\n\treturn g.writer.Write([]byte(s))\n}\n\nfunc (g *gzipWriter) Write(data []byte) (int, error) {\n\treturn g.writer.Write(data)\n}\n\nfunc shouldCompress(req *http.Request) bool {\n\tif !strings.Contains(req.Header.Get(\"Accept-Encoding\"), \"gzip\") {\n\t\treturn false\n\t}\n\textension := filepath.Ext(req.URL.Path)\n\tif len(extension) < 4 { \n\t\treturn true\n\t}\n\n\tswitch extension {\n\tcase \".png\", \".gif\", \".jpeg\", \".jpg\":\n\t\treturn false\n\tdefault:\n\t\treturn true\n\t}\n}\n\nfunc Gzip(level int) gin.HandlerFunc ", "output": "{\n\tvar gzPool sync.Pool\n\tgzPool.New = func() interface{} {\n\t\tgz, err := gzip.NewWriterLevel(ioutil.Discard, level)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\treturn gz\n\t}\n\treturn func(c *gin.Context) {\n\t\tif !shouldCompress(c.Request) {\n\t\t\treturn\n\t\t}\n\n\t\tgz := gzPool.Get().(*gzip.Writer)\n\t\tdefer gzPool.Put(gz)\n\t\tgz.Reset(c.Writer)\n\n\t\tc.Header(\"Content-Encoding\", \"gzip\")\n\t\tc.Header(\"Vary\", \"Accept-Encoding\")\n\t\tc.Writer = &gzipWriter{c.Writer, gz}\n\t\tdefer func() {\n\t\t\tgz.Close()\n\t\t\tc.Header(\"Content-Length\", fmt.Sprint(c.Writer.Size()))\n\t\t}()\n\t\tc.Next()\n\t}\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\nfunc (daemon *Daemon) prepareMountPoints(container *container.Container) error {\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}\n\n\n\nfunc (daemon *Daemon) removeMountPoints(container *container.Container, rm bool) error ", "output": "{\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}"} {"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\nfunc (f *Field) WithLock(fn func(*Field)) {\n\tf.Lock()\n\tfn(f)\n\tf.Unlock()\n}\n\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) Close() ", "output": "{\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}"} {"input": "package merge\n\n\n\n\nfunc Merge(nums1, nums2 []int, m,n int) []int ", "output": "{\n\ti,j,tar := m-1, n-1, m+n-1\n\tfor j >= 0 {\n\t\tif i >= 0 && nums1[i] > nums2[j]{\n\t\t\t\tnums1[tar] = nums1[i]\n\t\t\t\ti -= 1\n\t\t}else {\n\t\t\tnums1[tar] = nums2[j]\n\t\t\tj -= 1\n\t\t}\n\t\ttar -= 1\n\t}\n\treturn nums1\n}"} {"input": "package executedconditionals\n\nfunc a(condition bool) string {\n\tif condition {\n\t\treturn \"A\"\n\t}\n\treturn \"A\"\n}\n\n\n\nfunc c() string {\n\treturn \"C\"\n}\n\nfunc wrapper(condition bool) {\n\ta(condition)\n\tb()\n\tc()\n}\n\nfunc b() string ", "output": "{\n\treturn \"B\"\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\nfunc (flag *OptionsFlag) Register(f *flag.FlagSet) {\n\tf.StringVar(&flag.path, \"options\", \"\", \"Options spec file path for VM deployment\")\n}\n\n\n\nfunc (flag *OptionsFlag) Process() error ", "output": "{\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}"} {"input": "package arch_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 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\n\n\n\n\nfunc NewMsgFilterAdd(data []byte) *MsgFilterAdd {\n\treturn &MsgFilterAdd{\n\t\tData: data,\n\t}\n}\n\nfunc (msg *MsgFilterAdd) MaxPayloadLength(pver uint32) uint32 ", "output": "{\n\treturn uint32(VarIntSerializeSize(MaxFilterAddDataSize)) +\n\t\tMaxFilterAddDataSize\n}"} {"input": "package main\n\nimport (\n\t\"net/http\"\n\t\"os\"\n\t\"path\"\n\t\"strings\"\n\n\t\"github.com/zenazn/goji/web\"\n)\n\n\n\nfunc staticHandler(c web.C, w http.ResponseWriter, r *http.Request) {\n\tpath := r.URL.Path\n\tif path[len(path)-1:] == \"/\" {\n\t\tnotFoundHandler(c, w, r)\n\t\treturn\n\t} else {\n\t\tif path == \"/favicon.ico\" {\n\t\t\tpath = \"/static/images/favicon.gif\"\n\t\t}\n\n\t\tfilePath := strings.TrimPrefix(path, \"/static/\")\n\t\tfile, err := staticBox.Open(filePath)\n\t\tif err != nil {\n\t\t\tnotFoundHandler(c, w, r)\n\t\t\treturn\n\t\t}\n\n\t\tw.Header().Set(\"Etag\", timeStartedStr)\n\t\tw.Header().Set(\"Cache-Control\", \"max-age=86400\")\n\t\thttp.ServeContent(w, r, filePath, timeStarted, file)\n\t\treturn\n\t}\n}\n\nfunc fileExistsAndNotExpired(filename string) bool {\n\tfilePath := path.Join(Config.filesDir, filename)\n\n\t_, err := os.Stat(filePath)\n\tif err != nil {\n\t\treturn false\n\t}\n\n\tif isFileExpired(filename) {\n\t\tos.Remove(path.Join(Config.filesDir, filename))\n\t\tos.Remove(path.Join(Config.metaDir, filename))\n\t\treturn false\n\t}\n\n\treturn true\n}\n\nfunc fileServeHandler(c web.C, w http.ResponseWriter, r *http.Request) ", "output": "{\n\tfileName := c.URLParams[\"name\"]\n\tfilePath := path.Join(Config.filesDir, fileName)\n\n\tif !fileExistsAndNotExpired(fileName) {\n\t\tnotFoundHandler(c, w, r)\n\t\treturn\n\t}\n\n\tif !Config.allowHotlink {\n\t\treferer := r.Header.Get(\"Referer\")\n\t\tif referer != \"\" && !strings.HasPrefix(referer, Config.siteURL) {\n\t\t\tw.WriteHeader(403)\n\t\t\treturn\n\t\t}\n\t}\n\n\tw.Header().Set(\"Content-Security-Policy\", Config.fileContentSecurityPolicy)\n\n\thttp.ServeFile(w, r, filePath)\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\n\n\nfunc deleteAll(dryMode bool) {\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}\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 Delete(c *cli.Context) ", "output": "{\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}"} {"input": "package mqtt\n\nimport (\n\t\"encoding/binary\"\n\t\"encoding/json\"\n\t\"io\"\n)\n\ntype ConnackMessage struct {\n\tFixedHeader\n\tReserved uint8\n\tReturnCode uint8\n}\n\nfunc (self *ConnackMessage) decode(reader io.Reader) error {\n\tbinary.Read(reader, binary.BigEndian, &self.Reserved)\n\tbinary.Read(reader, binary.BigEndian, &self.ReturnCode)\n\n\treturn nil\n}\n\n\n\nfunc (self *ConnackMessage) String() string {\n\tb, _ := json.Marshal(self)\n\treturn string(b)\n}\n\nfunc (self ConnackMessage) WriteTo(w io.Writer) (int64, error) ", "output": "{\n\tvar fsize = 2\n\tsize, err := self.FixedHeader.writeTo(fsize, w)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\tbinary.Write(w, binary.BigEndian, self.Reserved)\n\tbinary.Write(w, binary.BigEndian, self.ReturnCode)\n\n\treturn int64(fsize) + size, nil\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\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 NewGetFilesFileidentifierParamsWithTimeout(timeout time.Duration) *GetFilesFileidentifierParams ", "output": "{\n\tvar ()\n\treturn &GetFilesFileidentifierParams{\n\n\t\ttimeout: timeout,\n\t}\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 TestEG_LineJoinPropertiesConstructor(t *testing.T) {\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}\n\n\n\nfunc TestEG_LineJoinPropertiesMarshalUnmarshal(t *testing.T) ", "output": "{\n\tv := dml.NewEG_LineJoinProperties()\n\tbuf, _ := xml.Marshal(v)\n\tv2 := dml.NewEG_LineJoinProperties()\n\txml.Unmarshal(buf, v2)\n}"} {"input": "package core\n\nimport (\n\t\"bytes\"\n\t\"errors\"\n\t\"fmt\"\n\t\"hash\"\n\t\"os\"\n)\n\n\ntype testingContentMap map[string][]byte\n\n\n\ntype testingProvider struct {\n\tstorage string\n\tcontentMap testingContentMap\n\thasher hash.Hash\n}\n\n\n\n\nfunc (p *testingProvider) Provide(path string, digest []byte) (string, error) ", "output": "{\n\tcontent, ok := p.contentMap[path]\n\tif !ok {\n\t\treturn \"\", os.ErrNotExist\n\t}\n\n\tp.hasher.Reset()\n\tp.hasher.Write(content)\n\tif !bytes.Equal(p.hasher.Sum(nil), digest) {\n\t\treturn \"\", errors.New(\"requested entry digest does not match expected\")\n\t}\n\n\ttemporaryFile, err := os.CreateTemp(p.storage, \"mutagen_provide\")\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"unable to create temporary file: %w\", err)\n\t}\n\n\t_, err = temporaryFile.Write(content)\n\ttemporaryFile.Close()\n\tif err != nil {\n\t\tos.Remove(temporaryFile.Name())\n\t\treturn \"\", fmt.Errorf(\"unable to write file contents: %w\", err)\n\t}\n\n\treturn temporaryFile.Name(), 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\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\n\n\nfunc sumNumbers(str string) float64 {\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}\n\nfunc getline() (string, error) ", "output": "{\n\treturn bufio.NewReader(os.Stdin).ReadString('\\n')\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\n\nfunc (stub *AnonymousParamsStub) RegisterCallCount() int {\n\tstub.registerMutex.RLock()\n\tdefer stub.registerMutex.RUnlock()\n\treturn len(stub.registerArgsForCall)\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) Register(arg1 string, arg2 int) ", "output": "{\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}"} {"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\nfunc NewDescribeCmd(cxt *command.Context) *cobra.Command {\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}\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\n\n\nfunc (c *describeCmd) describe() error ", "output": "{\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}"} {"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\n\n\nvar (\n\tpost = []byte(\"POST\")\n\ttextPlain = []byte(\"text/plain\")\n)\n\n\n\n\nfunc (w *HTTPWriter) WriteLineProtocol(body []byte) (int64, error) {\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}\n\nfunc NewHTTPWriter(c HTTPWriterConfig) LineProtocolWriter ", "output": "{\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}"} {"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\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\nfunc usage() {\n\tlog.Fatalln(\"usage: tee [-ai] [file ...]\")\n}\n\nfunc init() ", "output": "{\n\tlog.SetFlags(0)\n\tlog.SetOutput(os.Stderr)\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\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\nfunc (e *SecurityGroupRule) String() string {\n\treturn fi.TaskAsString(e)\n}\n\nfunc (o *SecurityGroupRule) 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 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}"} {"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\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\n\n\ntype MockReadWriteCloser struct {\n\tMockReader\n\tMockWriter\n\tMockCloser\n}\n\nfunc (w *MockWriter) Close() error ", "output": "{\n\treturns := w.Called()\n\treturn returns.Error(0)\n}"} {"input": "package testbase\n\nimport (\n\t\"go/build\"\n\t\"path/filepath\"\n\t\"sort\"\n\t\"strings\"\n\n\tgc \"launchpad.net/gocheck\"\n)\n\n\n\n\n\n\nfunc FindJujuCoreImports(c *gc.C, packageName string) []string ", "output": "{\n\tvar imports []string\n\n\tfor _, root := range build.Default.SrcDirs() {\n\t\tfullpath := filepath.Join(root, packageName)\n\t\tpkg, err := build.ImportDir(fullpath, 0)\n\t\tif err == nil {\n\t\t\timports = pkg.Imports\n\t\t\tbreak\n\t\t}\n\t}\n\tif imports == nil {\n\t\tc.Fatalf(packageName + \" not found\")\n\t}\n\n\tvar result []string\n\tconst prefix = \"launchpad.net/juju-core/\"\n\tfor _, name := range imports {\n\t\tif strings.HasPrefix(name, prefix) {\n\t\t\tresult = append(result, name[len(prefix):])\n\t\t}\n\t}\n\tsort.Strings(result)\n\treturn result\n}"} {"input": "package iso20022\n\n\ntype RejectedElement1 struct {\n\n\tElementSequenceNumber *Number `xml:\"ElmtSeqNb\"`\n\n\tIndividualRejectionReason *Max140Text `xml:\"IndvRjctnRsn\"`\n}\n\n\n\nfunc (r *RejectedElement1) SetIndividualRejectionReason(value string) {\n\tr.IndividualRejectionReason = (*Max140Text)(&value)\n}\n\nfunc (r *RejectedElement1) SetElementSequenceNumber(value string) ", "output": "{\n\tr.ElementSequenceNumber = (*Number)(&value)\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\nfunc Register(key string, exp Experiment) {\n\tknownExperiments[key] = exp\n}\n\n\n\n\nfunc Apply(ctx context.Context, b *bbpb.Build, task *swarmingpb.TaskRequest) error ", "output": "{\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}"} {"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\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 Critical(title string, data M) ", "output": "{\n\tlogWithLevel(title, kayvee.Critical, data)\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\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 Run() int ", "output": "{\n\treturn theApp.Run()\n}"} {"input": "package check\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\n\n\nfunc TestString(t *testing.T) {\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}\n\nfunc TestCompare(t *testing.T) ", "output": "{\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}"} {"input": "package cloudflare_test\n\nimport (\n\t\"context\"\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"log\"\n\n\tcloudflare \"github.com/cloudflare/cloudflare-go\"\n)\n\n\n\nfunc ExampleAPI_AccessAuditLogs() ", "output": "{\n\tapi, err := cloudflare.New(\"deadbeef\", \"test@example.org\")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tfilterOpts := cloudflare.AccessAuditLogFilterOptions{}\n\tresults, _ := api.AccessAuditLogs(context.Background(), \"someaccountid\", filterOpts)\n\n\tfor _, record := range results {\n\t\tb, _ := json.Marshal(record)\n\t\tfmt.Println(string(b))\n\t}\n}"} {"input": "package main\n\nimport (\n\t\"log\"\n\t\"time\"\n)\n\n\n\n\nfunc StartScheduler() ", "output": "{\n\tfor path, handler := range Registry {\n\t\tif handler.PollInterval() > 0 {\n\t\t\tlog.Printf(\"Start ticker for %s\\n\", path)\n\t\t\tticker := time.NewTicker(handler.PollInterval())\n\t\t\thandler := handler\n\t\t\tgo func() {\n\t\t\t\tfor range ticker.C {\n\t\t\t\t\thandler.Execute()\n\t\t\t\t}\n\t\t\t}()\n\t\t}\n\t}\n}"} {"input": "package main\n\nimport (\n\t\"testing\"\n\n\t\"github.com/streadway/amqp\"\n)\n\n\n\nfunc TestMessageParsing(t *testing.T) ", "output": "{\n\theaders := make(amqp.Table, 0)\n\tvar ttl int32 = 13\n\theaders[\"ttl\"] = ttl\n\tbody := \"test message\"\n\tmessage := amqp.Delivery{\n\t\tRoutingKey: \"user.18\",\n\t\tBody: []byte(body),\n\t\tHeaders: headers,\n\t}\n\tparsed, _ := ParseMessage(message)\n\tif parsed.Message != body || parsed.UID != 18 || parsed.TTL != 13 {\n\t\tt.Fatalf(\"%v\", parsed)\n\t}\n\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\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) SetTitleVisibility(flag NSWindowTitleVisibility) ", "output": "{\n\tNSWindow_setTitleVisibility.Call(uintptr(n), uintptr(flag))\n}"} {"input": "package term\n\nimport (\n\t\"github.com/docker/docker/pkg/term\"\n\t\"k8s.io/kubernetes/pkg/client/unversioned/remotecommand\"\n)\n\n\n\n\nfunc SetSize(fd uintptr, size remotecommand.TerminalSize) error ", "output": "{\n\treturn term.SetWinsize(fd, &term.Winsize{Height: size.Height, Width: size.Width})\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\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 New(c rest.Interface) *CertificatesV1beta1Client ", "output": "{\n\treturn &CertificatesV1beta1Client{c}\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\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\nfunc Create(name string) *Module {\n\tm := new(Module)\n\tm.Name = name\n\treturn m\n}\n\nfunc (m *Module) Run() ", "output": "{\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}"} {"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\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\n\n\nfunc (e *SafeError) Bytes() []byte ", "output": "{\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}"} {"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\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\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 init() ", "output": "{\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}"} {"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\n\n\nfunc (cr TransactionalCypherRunner) CypherBatch(queries []*neoism.CypherQuery) error {\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}\n\nfunc (cr TransactionalCypherRunner) String() string ", "output": "{\n\treturn cr.DB.Url\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\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) IsLeftBitSet() bool ", "output": "{\n\treturn n.prefix >= _leftmost32Bit\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\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\nfunc (w Watcher) Walk(root string, walkFn filepath.WalkFunc) error {\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}\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) Get(path string) FileInfo ", "output": "{\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}"} {"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\n\n\n\nfunc (response ListFastConnectProviderVirtualCircuitBandwidthShapesResponse) HTTPResponse() *http.Response {\n\treturn response.RawResponse\n}\n\nfunc (response ListFastConnectProviderVirtualCircuitBandwidthShapesResponse) String() string ", "output": "{\n\treturn common.PointerString(response)\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\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) Setup(bot *bot.Kabukibot) ", "output": "{\n\tself.db = bot.Database()\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\nfunc UpdateIndex(b Backend) error {\n\treturn updateIndex(b)\n}\n\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 ComputeStatistics() (Statistics, error) ", "output": "{\n\treturn computeStatistics()\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\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\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 NewSamplesBuffer(size int) *SamplesBuffer ", "output": "{\n\treturn &SamplesBuffer{\n\t\tindex: -1,\n\t\tmaxSize: size,\n\t}\n}"} {"input": "package mysql\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 main\n\nimport (\n\t\"github.com/robertkrimen/otto\"\n)\n\n\n\nfunc evaluateScript(src string, payload []FinalInput) (string, error) ", "output": "{\n\tjavaScript := otto.New()\n\tvar evalFunc otto.Value\n\tjavaScript.Set(\"eval\", func(call otto.FunctionCall) otto.Value {\n\t\tevalFunc = call.Argument(0)\n\t\treturn otto.UndefinedValue()\n\t})\n\n\tjavaScript.Run(src)\n\targ, err := javaScript.ToValue(payload)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tret, err := evalFunc.Call(otto.NullValue(), arg)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn ret.ToString()\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\n\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) Search(x uint64) int ", "output": "{ return SearchUint64s(p, x) }"} {"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\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 *ISUB) 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 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\n\n\n\n\nfunc storagePoolResourcesGet(d *Daemon, r *http.Request) response.Response {\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}\n\nfunc api10ResourcesGet(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\tres, err := resources.GetResources()\n\tif err != nil {\n\t\treturn response.SmartError(err)\n\t}\n\n\treturn response.SyncResponse(true, res)\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\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\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) Len() int ", "output": "{\n\tq.lock.Lock()\n\tdefer q.lock.Unlock()\n\n\treturn q.count\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\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) Sub(delta uint32) uint32 ", "output": "{\n\treturn atomic.AddUint32(&i.v, ^(delta - 1))\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\nfunc (_ DeleteSecurityGroupCommand) Setup(config commands.Config, ui commands.UI) error {\n\treturn nil\n}\n\n\n\nfunc (_ DeleteSecurityGroupCommand) Execute(args []string) error ", "output": "{\n\tcmd.Main(os.Getenv(\"CF_TRACE\"), os.Args)\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\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\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(t *testing.T) ", "output": "{\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}"} {"input": "package findprocess\n\nimport (\n\t\"os\"\n\t\"syscall\"\n)\n\n\n\nfunc findProcess(pid int) (process *os.Process, err error) ", "output": "{\n\tprocess, err = os.FindProcess(pid)\n\tif err != nil {\n\t\treturn process, err\n\t}\n\terr = process.Signal(syscall.Signal(0))\n\tif err == nil {\n\t\treturn process, nil\n\t}\n\tif err.Error() == \"os: process already finished\" {\n\t\treturn process, ErrNotFound\n\t}\n\treturn process, err\n}"} {"input": "package samples\n\nimport (\n\t\"math\"\n)\n\ntype ArcNegativeSample struct {\n\tCairoSampleImpl\n}\n\n\n\nfunc (ans *ArcNegativeSample) Run() ", "output": "{\n\n\txc := 128.0\n\tyc := 128.0\n\tradius := 100.0\n\tangle1 := 45.0 * (math.Pi / 180.0)\n\tangle2 := 180.0 * (math.Pi / 180.0)\n\n\tctx := ans.CairoContext()\n\n\tctx.SetLineWidth(10.0)\n\tctx.ArcNegative(xc, yc, radius, angle1, angle2)\n\tctx.Stroke()\n\n\tctx.SetSourceRgba(1, 0.2, 0.2, 0.6)\n\tctx.SetLineWidth(6.0)\n\tctx.Arc(xc, yc, 10.0, 0, 2*math.Pi)\n\tctx.Fill()\n\n\tctx.Arc(xc, yc, radius, angle1, angle1)\n\tctx.LineTo(xc, yc)\n\tctx.Arc(xc, yc, radius, angle2, angle2)\n\tctx.LineTo(xc, yc)\n\tctx.Stroke()\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\n\n\nfunc pubsubHandler(ctx context.Context, sub *pubsub.Subscription) {\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}\n\nfunc pubsubUpdateHandler(id peer.ID, msg *UpdatePeer) ", "output": "{\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}"} {"input": "package trie\n\nimport (\n\t\"testing\"\n\n\t\"github.com/ethereumproject/go-ethereum/common\"\n\t\"github.com/ethereumproject/go-ethereum/ethdb\"\n)\n\n\n\n\nfunc TestNodeIteratorCoverage(t *testing.T) {\n\tdb, trie, _ := makeTestTrie()\n\n\thashes := make(map[common.Hash]struct{})\n\tfor it := NewNodeIterator(trie); it.Next(); {\n\t\tif it.Hash != (common.Hash{}) {\n\t\t\thashes[it.Hash] = struct{}{}\n\t\t}\n\t}\n\tfor hash, _ := range hashes {\n\t\tif _, err := db.Get(hash.Bytes()); err != nil {\n\t\t\tt.Errorf(\"failed to retrieve reported node %x: %v\", hash, err)\n\t\t}\n\t}\n\tfor _, key := range db.(*ethdb.MemDatabase).Keys() {\n\t\tif _, ok := hashes[common.BytesToHash(key)]; !ok {\n\t\t\tt.Errorf(\"state entry not reported %x\", key)\n\t\t}\n\t}\n}\n\nfunc TestIterator(t *testing.T) ", "output": "{\n\ttrie := newEmpty()\n\tvals := []struct{ k, v string }{\n\t\t{\"do\", \"verb\"},\n\t\t{\"ether\", \"wookiedoo\"},\n\t\t{\"horse\", \"stallion\"},\n\t\t{\"shaman\", \"horse\"},\n\t\t{\"doge\", \"coin\"},\n\t\t{\"dog\", \"puppy\"},\n\t\t{\"somethingveryoddindeedthis is\", \"myothernodedata\"},\n\t}\n\tv := make(map[string]bool)\n\tfor _, val := range vals {\n\t\tv[val.k] = false\n\t\ttrie.Update([]byte(val.k), []byte(val.v))\n\t}\n\ttrie.Commit()\n\n\tit := NewIterator(trie)\n\tfor it.Next() {\n\t\tv[string(it.Key)] = true\n\t}\n\n\tfor k, found := range v {\n\t\tif !found {\n\t\t\tt.Error(\"iterator didn't find\", k)\n\t\t}\n\t}\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\n\n\nfunc TestGetServiceState(t *testing.T) {\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}\n\nfunc TestSetServiceStateByDays(t *testing.T) ", "output": "{\n\terr := SetServiceStateByDays(\"testStateDays\", 0, 1)\n\tif err != nil {\n\t\tt.Error(err)\n\t\treturn\n\t}\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\n\n\n\nfunc (m VolumeGroupSourceFromVolumeGroupDetails) MarshalJSON() (buff []byte, e error) {\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}\n\nfunc (m VolumeGroupSourceFromVolumeGroupDetails) String() string ", "output": "{\n\treturn common.PointerString(m)\n}"} {"input": "package main\n\nimport \"fmt\"\n\n\nfunc ping(pings chan<- string, msg string) {\n\n \n pings <- msg\n}\n\n\n\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 pong(pings <-chan string, pongs chan<- string) ", "output": "{\n\n \n msg := <-pings\n\n \n pongs <- msg\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\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) SetReconciliationIdentification(value string) ", "output": "{\n\tc.ReconciliationIdentification = (*Max35Text)(&value)\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\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\n\n\nfunc (p *RetrivedCookieJar) SetURLAndCookies(all map[string][]*http.Cookie) error ", "output": "{\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}"} {"input": "package health\n\nimport (\n\t\"github.com/jinzhu/gorm\"\n)\n\n\ntype Service struct {\n\tdb *gorm.DB\n}\n\n\n\n\n\nfunc (s *Service) Close() {}\n\nfunc NewService(db *gorm.DB) *Service ", "output": "{\n\treturn &Service{db: db}\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\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) Check() bool ", "output": "{\n for i:=0; i s.intervals[i+1].Start {\n return false\n }\n }\n return true\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\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\nfunc TestMain(m *testing.M) {\n\tconfig.UseTestFile()\n\tos.Exit(m.Run())\n}\n\nfunc testRequest(t *testing.T, url string) ", "output": "{\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}"} {"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\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\n\n\nfunc (t *Test) SetInterval(interval int) ", "output": "{\n\tt.interval = interval\n}"} {"input": "package NEAT\n\ntype Neuron struct{\n incoming []Gene\n value float64\n}\n\n\n\nfunc NewNeuron() *Neuron", "output": "{\n return &Neuron{[]Gene{},0}\n}"} {"input": "package http\n\nimport (\n\t\"go-common/app/admin/main/workflow/model/param\"\n\t\"go-common/library/ecode\"\n\t\"go-common/library/log\"\n\tbm \"go-common/library/net/http/blademaster\"\n\t\"go-common/library/net/http/blademaster/binding\"\n)\n\nfunc listCallback(ctx *bm.Context) {\n\tctx.JSON(wkfSvc.ListCallback(ctx))\n}\n\n\n\nfunc addOrUpCallback(ctx *bm.Context) ", "output": "{\n\tcbp := ¶m.AddCallbackParam{}\n\tif err := ctx.BindWith(cbp, binding.JSON); err != nil {\n\t\treturn\n\t}\n\n\tif cbp.State > 0 {\n\t\tcbp.State = 1\n\t}\n\n\tcbID, err := wkfSvc.AddOrUpCallback(ctx, cbp)\n\tif err != nil {\n\t\tlog.Error(\"wkfSvc.AddUpCallback(%+v) error(%v)\", cbp, err)\n\t\tctx.JSON(nil, ecode.RequestErr)\n\t\treturn\n\t}\n\n\tctx.JSON(map[string]int32{\n\t\t\"callbackNo\": cbID,\n\t}, 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\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\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) MarshalJSON() ([]byte, error) ", "output": "{\n\treturn j, nil\n}"} {"input": "package exclude\n\nimport (\n\t\"context\"\n\t\"regexp\"\n\n\t\"github.com/go-graphite/carbonapi/expr/helper\"\n\t\"github.com/go-graphite/carbonapi/expr/interfaces\"\n\t\"github.com/go-graphite/carbonapi/expr/types\"\n\t\"github.com/go-graphite/carbonapi/pkg/parser\"\n)\n\ntype exclude struct {\n\tinterfaces.FunctionBase\n}\n\nfunc GetOrder() interfaces.Order {\n\treturn interfaces.Any\n}\n\nfunc New(configFile string) []interfaces.FunctionMetadata {\n\tres := make([]interfaces.FunctionMetadata, 0)\n\tf := &exclude{}\n\tfunctions := []string{\"exclude\"}\n\tfor _, n := range functions {\n\t\tres = append(res, interfaces.FunctionMetadata{Name: n, F: f})\n\t}\n\treturn res\n}\n\n\nfunc (f *exclude) Do(ctx context.Context, e parser.Expr, from, until int64, values map[parser.MetricRequest][]*types.MetricData) ([]*types.MetricData, error) {\n\targ, err := helper.GetSeriesArg(e.Args()[0], from, until, values)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tpat, err := e.GetStringArg(1)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tpatre, err := regexp.Compile(pat)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar results []*types.MetricData\n\n\tfor _, a := range arg {\n\t\tif !patre.MatchString(a.Name) {\n\t\t\tresults = append(results, a)\n\t\t}\n\t}\n\n\treturn results, nil\n}\n\n\n\n\nfunc (f *exclude) Description() map[string]types.FunctionDescription ", "output": "{\n\treturn map[string]types.FunctionDescription{\n\t\t\"exclude\": {\n\t\t\tDescription: \"Takes a metric or a wildcard seriesList, followed by a regular expression\\nin double quotes. Excludes metrics that match the regular expression.\\n\\nExample:\\n\\n.. code-block:: none\\n\\n &target=exclude(servers*.instance*.threads.busy,\\\"server02\\\")\",\n\t\t\tFunction: \"exclude(seriesList, pattern)\",\n\t\t\tGroup: \"Filter Series\",\n\t\t\tModule: \"graphite.render.functions\",\n\t\t\tName: \"exclude\",\n\t\t\tParams: []types.FunctionParam{\n\t\t\t\t{\n\t\t\t\t\tName: \"seriesList\",\n\t\t\t\t\tRequired: true,\n\t\t\t\t\tType: types.SeriesList,\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tName: \"pattern\",\n\t\t\t\t\tRequired: true,\n\t\t\t\t\tType: types.String,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n}"} {"input": "package test\n\nimport \"testing\"\n\n\n\nfunc TestTempFile(t *testing.T) ", "output": "{\n\tt.Parallel()\n\t_, f, e := TempFile(\".\", \"test\")\n\tif e != nil {\n\t\tt.Fatalf(\"failed to create temp file: %s\", e)\n\t}\n\tdefer f()\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\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) Start() ", "output": "{\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}"} {"input": "package system \n\nimport (\n\t\"io/ioutil\"\n\t\"os\"\n\t\"path/filepath\"\n)\n\n\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\nfunc TempFileSequential(dir, prefix string) (f *os.File, err error) {\n\treturn ioutil.TempFile(dir, prefix)\n}\n\nfunc MkdirAllWithACL(path string, perm os.FileMode, sddl string) error ", "output": "{\n\treturn os.MkdirAll(path, perm)\n}"} {"input": "package pkcs11\n\nimport (\n\t\"io/ioutil\"\n\t\"github.com/cloudflare/cfssl/crypto/pkcs11key\"\n\t\"github.com/cloudflare/cfssl/errors\"\n\t\"github.com/cloudflare/cfssl/helpers\"\n\t\"github.com/cloudflare/cfssl/log\"\n\t\"github.com/cloudflare/cfssl/ocsp\"\n\tocspConfig \"github.com/cloudflare/cfssl/ocsp/config\"\n)\n\n\nconst Enabled = true\n\n\n\n\nfunc NewPKCS11Signer(cfg ocspConfig.Config) (ocsp.Signer, error) ", "output": "{\n\tlog.Debugf(\"Loading PKCS #11 module %s\", cfg.PKCS11.Module)\n\tcertData, err := ioutil.ReadFile(cfg.CACertFile)\n\tif err != nil {\n\t\treturn nil, errors.New(errors.CertificateError, errors.ReadFailed)\n\t}\n\n\tcert, err := helpers.ParseCertificatePEM(certData)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tPKCS11 := cfg.PKCS11\n\tpriv, err := pkcs11key.New(\n\t\tPKCS11.Module,\n\t\tPKCS11.TokenLabel,\n\t\tPKCS11.PIN,\n\t\tPKCS11.PrivateKeyLabel)\n\tif err != nil {\n\t\treturn nil, errors.New(errors.PrivateKeyError, errors.ReadFailed)\n\t}\n\n\treturn ocsp.NewSigner(cert, cert, priv, cfg.Interval)\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\nfunc BenchmarkReduceToDiff1000(b *testing.B) {\n\tbenchmarkReduceToDiff(1000, 1000, b)\n}\n\n\n\nfunc BenchmarkReduceToDiff10000(b *testing.B) ", "output": "{\n\tbenchmarkReduceToDiff(10000, 10000, b)\n}"} {"input": "package migrations\n\nimport (\n\t\"xorm.io/xorm\"\n)\n\n\n\nfunc addLFSMirrorColumns(x *xorm.Engine) error ", "output": "{\n\ttype Mirror struct {\n\t\tLFS bool `xorm:\"lfs_enabled NOT NULL DEFAULT false\"`\n\t\tLFSEndpoint string `xorm:\"lfs_endpoint TEXT\"`\n\t}\n\n\treturn x.Sync2(new(Mirror))\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\nfunc isVDI(b []byte) bool {\n\n\ts := string(b[0:40])\n\treturn s == \"<<< Oracle VM VirtualBox Disk Image >>>\"+\"\\n\"\n}\n\n\n\nfunc parseVDI(file *os.File, pl parse.ParsedLayout) (*parse.ParsedLayout, error) ", "output": "{\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}"} {"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 < 11; 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 := 0, 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 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\nfunc (c *PrintCommand) AutocompleteFlags() complete.Flags {\n\treturn nil\n}\n\n\n\nfunc (c *PrintCommand) Run(args []string) int ", "output": "{\n\treturn cli.RunResultHelp\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\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 NewBulkIndex(_index, _type, _id string, source []byte) *Bulk ", "output": "{\n\treturn &Bulk{\n\t\tIndex: NewMeta(_index, _type, _id),\n\t\tSource: source,\n\t}\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\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\n\n\nfunc (r *AWSAmazonMQConfiguration_TagsEntry) SetDeletionPolicy(policy policies.DeletionPolicy) ", "output": "{\n\tr._deletionPolicy = policy\n}"} {"input": "package mysql\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 dnscfg\n\nimport (\n\t\"fmt\"\n\t\"net\"\n)\n\n\n\n\n\nfunc Get(dnsAddr *string, port *int) ([]string, error) ", "output": "{\n\taddrs := []string{}\n\n\tips, err := net.LookupIP(*dnsAddr)\n\tif err != nil {\n\t\treturn addrs, err\n\t}\n\n\tfor _, ip := range ips {\n\t\taddr := fmt.Sprintf(\"%s:%d\", ip, *port)\n\t\taddrs = append(addrs, addr)\n\t}\n\n\treturn addrs, nil\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\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) HTTPRequest(method, path string) (http.Request, error) ", "output": "{\n\treturn common.MakeDefaultHTTPRequestWithTaggedStruct(method, path, request)\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\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\nfunc (r *Users) Flush() {\n\tr.Lock()\n\tdefer r.Unlock()\n\n\tr.List = []*User{}\n}\n\nfunc (u *Users) Create(user *User) ", "output": "{\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}"} {"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\n\n\nfunc (c StringKeyValueMap) GetBool(key string) bool {\n\treturn String(c.GetString(key)).ToBool()\n}\n\nfunc (c StringKeyValueMap) GetInt(key string) int ", "output": "{\n\treturn String(c.GetString(key)).ToIntNoError()\n}"} {"input": "package mysql\n\nconst requiredSchemaVersion = 21\n\nfunc SchemaVersion() int {\n\treturn requiredSchemaVersion\n}\n\n\n\n\n\n\n\nfunc SQLCreateTables() []string ", "output": "{\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}"} {"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\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) RetryPolicy() *common.RetryPolicy ", "output": "{\n\treturn request.RequestMetadata.RetryPolicy\n}"} {"input": "package main\n\nimport \"testing\"\n\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\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 TestValidateURL(t *testing.T) ", "output": "{\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}"} {"input": "package psdock\n\nimport (\n\t\"os\"\n\t\"os/signal\"\n\t\"syscall\"\n)\n\n\n\n\n\nfunc ManageSignals(p *Process) ", "output": "{\n\ttermSignalChannel := make(chan os.Signal)\n\totherSignalChannel := make(chan os.Signal)\n\tsignal.Notify(termSignalChannel, syscall.SIGINT, syscall.SIGTERM, syscall.SIGQUIT, syscall.SIGHUP, syscall.SIGALRM, syscall.SIGPIPE)\n\n\tsignal.Notify(otherSignalChannel, otherSignals...)\n\tgo func() {\n\t\tfor {\n\t\t\ts := <-otherSignalChannel\n\t\t\tp.Cmd.Process.Signal(s)\n\t\t}\n\t}()\n\t_ = <-termSignalChannel\n\n\tp.eofChannel <- true\n\t_ = p.Terminate(5)\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\n\n\nfunc Base() Applier {\n\treturn applyFn(func(root string) error {\n\t\treturn nil\n\t})\n}\n\nfunc Lchtimes(name string, atime, mtime time.Time) Applier ", "output": "{\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}"} {"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\nfunc NewPruneCommand(dockerCli *command.DockerCli) *cobra.Command {\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}\n\nconst warning = `WARNING! This will remove all networks not used by at least one container.\nAre you sure you want to continue?`\n\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 runPrune(dockerCli *command.DockerCli, opts pruneOptions) (output string, err error) ", "output": "{\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}"} {"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\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) DeleteObject(name string) error ", "output": "{\n\treturn nil\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\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 TestHashCash(t *testing.T) ", "output": "{\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}"} {"input": "package kernel\n\nimport (\n\t\"os/exec\"\n\t\"strings\"\n\t\"testing\"\n)\n\n\n\nfunc TestCompilerIdentity(t *testing.T) ", "output": "{\n\tcompiler := \"gcc\"\n\tif _, err := exec.LookPath(compiler); err != nil {\n\t\tt.Skipf(\"compiler '%v' is not found: %v\", compiler, err)\n\t}\n\tid, err := CompilerIdentity(compiler)\n\tif err != nil {\n\t\tt.Fatalf(\"failed: %v\", err)\n\t}\n\tif len(id) == 0 {\n\t\tt.Fatalf(\"identity is empty\")\n\t}\n\tif strings.Index(id, \"\\n\") != -1 {\n\t\tt.Fatalf(\"identity contains a new line\")\n\t}\n\tt.Logf(\"id: '%v'\", id)\n}"} {"input": "package dht\n\nimport (\n\t\"io\"\n\n\tinet \"gx/ipfs/QmQx1dHDDYENugYgqA22BaBrRfuv1coSsuPiM7rYh1wwGH/go-libp2p-net\"\n\tmstream \"gx/ipfs/QmTnsezaB1wWNRHeHnYrm8K4d5i9wtyj3GsqjC3Rt5b5v5/go-multistream\"\n\tma \"gx/ipfs/QmUAQaWbKxGCUTuoQVvvicbQNZ9APF5pDGWyAZSe93AtKH/go-multiaddr\"\n)\n\n\ntype netNotifiee IpfsDHT\n\nfunc (nn *netNotifiee) DHT() *IpfsDHT {\n\treturn (*IpfsDHT)(nn)\n}\n\n\n\nfunc (nn *netNotifiee) Disconnected(n inet.Network, v inet.Conn) {\n\tdht := nn.DHT()\n\tselect {\n\tcase <-dht.Process().Closing():\n\t\treturn\n\tdefault:\n\t}\n\tdht.routingTable.Remove(v.RemotePeer())\n}\n\nfunc (nn *netNotifiee) OpenedStream(n inet.Network, v inet.Stream) {}\nfunc (nn *netNotifiee) ClosedStream(n inet.Network, v inet.Stream) {}\nfunc (nn *netNotifiee) Listen(n inet.Network, a ma.Multiaddr) {}\nfunc (nn *netNotifiee) ListenClose(n inet.Network, a ma.Multiaddr) {}\n\nfunc (nn *netNotifiee) Connected(n inet.Network, v inet.Conn) ", "output": "{\n\tdht := nn.DHT()\n\tselect {\n\tcase <-dht.Process().Closing():\n\t\treturn\n\tdefault:\n\t}\n\n\ts, err := dht.host.NewStream(dht.Context(), v.RemotePeer(), ProtocolDHT, ProtocolDHTOld)\n\tswitch err {\n\tcase nil:\n\t\ts.Close()\n\t\tdht.Update(dht.Context(), v.RemotePeer())\n\tcase mstream.ErrNotSupported:\n\tcase io.EOF:\n\t\tlog.Warningf(\"checking dht client type: %s\", err)\n\tdefault:\n\t\tlog.Errorf(\"checking dht client type: %s\", err)\n\t}\n}"} {"input": "package iso\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/mitchellh/multistep\"\n\tparallelscommon \"github.com/orivej/packer/builder/parallels/common\"\n\t\"github.com/orivej/packer/packer\"\n)\n\n\n\n\n\ntype stepCreateVM struct {\n\tvmName string\n}\n\nfunc (s *stepCreateVM) Run(state multistep.StateBag) multistep.StepAction {\n\n\tconfig := state.Get(\"config\").(*Config)\n\tdriver := state.Get(\"driver\").(parallelscommon.Driver)\n\tui := state.Get(\"ui\").(packer.Ui)\n\tname := config.VMName\n\n\tcommand := []string{\n\t\t\"create\", name,\n\t\t\"--distribution\", config.GuestOSType,\n\t\t\"--dst\", config.OutputDir,\n\t\t\"--vmtype\", \"vm\",\n\t\t\"--no-hdd\",\n\t}\n\n\tui.Say(\"Creating virtual machine...\")\n\tif err := driver.Prlctl(command...); err != nil {\n\t\terr := fmt.Errorf(\"Error creating VM: %s\", err)\n\t\tstate.Put(\"error\", err)\n\t\tui.Error(err.Error())\n\t\treturn multistep.ActionHalt\n\t}\n\n\tui.Say(\"Applying default settings...\")\n\tif err := driver.SetDefaultConfiguration(name); err != nil {\n\t\terr := fmt.Errorf(\"Error VM configuration: %s\", err)\n\t\tstate.Put(\"error\", err)\n\t\tui.Error(err.Error())\n\t\treturn multistep.ActionHalt\n\t}\n\n\tif s.vmName == \"\" {\n\t\ts.vmName = name\n\t}\n\n\tstate.Put(\"vmName\", s.vmName)\n\treturn multistep.ActionContinue\n}\n\n\n\nfunc (s *stepCreateVM) Cleanup(state multistep.StateBag) ", "output": "{\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 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\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\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) Request() *http.Request ", "output": "{\n\treturn c.r\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\nfunc TestMusicMCategorys(t *testing.T) {\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}\n\n\n\nfunc TestMusicMusic(t *testing.T) ", "output": "{\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}"} {"input": "package jms\n\nimport (\n\t\"github.com/oracle/oci-go-sdk/v46/common\"\n)\n\n\ntype Fleet struct {\n\n\tId *string `mandatory:\"true\" json:\"id\"`\n\n\tDisplayName *string `mandatory:\"true\" json:\"displayName\"`\n\n\tDescription *string `mandatory:\"true\" json:\"description\"`\n\n\tCompartmentId *string `mandatory:\"true\" json:\"compartmentId\"`\n\n\tApproximateJreCount *int `mandatory:\"true\" json:\"approximateJreCount\"`\n\n\tApproximateInstallationCount *int `mandatory:\"true\" json:\"approximateInstallationCount\"`\n\n\tApproximateApplicationCount *int `mandatory:\"true\" json:\"approximateApplicationCount\"`\n\n\tApproximateManagedInstanceCount *int `mandatory:\"true\" json:\"approximateManagedInstanceCount\"`\n\n\tTimeCreated *common.SDKTime `mandatory:\"true\" json:\"timeCreated\"`\n\n\tLifecycleState LifecycleStateEnum `mandatory:\"true\" json:\"lifecycleState\"`\n\n\tDefinedTags map[string]map[string]interface{} `mandatory:\"false\" json:\"definedTags\"`\n\n\tFreeformTags map[string]string `mandatory:\"false\" json:\"freeformTags\"`\n\n\tSystemTags map[string]map[string]interface{} `mandatory:\"false\" json:\"systemTags\"`\n}\n\n\n\nfunc (m Fleet) String() string ", "output": "{\n\treturn common.PointerString(m)\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\n\n\n\nfunc (t *Plugin) DescribeResources(spec resource.Spec) (string, error) {\n\treturn t.DoDescribeResources(spec)\n}\n\nfunc (t *Plugin) Destroy(spec resource.Spec, pretend bool) (string, error) ", "output": "{\n\treturn t.DoDestroy(spec, pretend)\n}"} {"input": "package main\n\nimport (\n\t\"bytes\"\n\t\"encoding/json\"\n\t\"errors\"\n\n\t\"github.com/Sirupsen/logrus\"\n\t\"github.com/minio/minio-xl/pkg/probe\"\n\n\t. \"gopkg.in/check.v1\"\n)\n\ntype LoggerSuite struct{}\n\nvar _ = Suite(&LoggerSuite{})\n\n\n\nfunc (s *LoggerSuite) TestLogger(c *C) ", "output": "{\n\tvar buffer bytes.Buffer\n\tvar fields logrus.Fields\n\tlog.Out = &buffer\n\tlog.Formatter = new(logrus.JSONFormatter)\n\n\terrorIf(probe.NewError(errors.New(\"Fake error\")), \"Failed with error.\", nil)\n\terr := json.Unmarshal(buffer.Bytes(), &fields)\n\tc.Assert(err, IsNil)\n\tc.Assert(fields[\"level\"], Equals, \"error\")\n\n\tmsg, ok := fields[\"Error\"]\n\tc.Assert(ok, Equals, true)\n\tc.Assert(msg.(map[string]interface{})[\"cause\"], Equals, \"Fake error\")\n}"} {"input": "package router\n\nimport (\n\t\"log\"\n\t\"net/http\"\n\t\"net/http/httptest\"\n\t\"net/url\"\n\t\"testing\"\n\n\t\"github.com/fission/fission\"\n)\n\nfunc createBackendService(testResponseString string) *url.URL {\n\tbackendServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tw.Write([]byte(testResponseString))\n\t}))\n\n\tbackendURL, err := url.Parse(backendServer.URL)\n\tif err != nil {\n\t\tpanic(\"error parsing url\")\n\t}\n\treturn backendURL\n}\n\n\n\n\nfunc TestFunctionProxying(t *testing.T) ", "output": "{\n\ttestResponseString := \"hi\"\n\tbackendURL := createBackendService(testResponseString)\n\tlog.Printf(\"Created backend svc at %v\", backendURL)\n\n\tfn := &fission.Metadata{Name: \"foo\", Uid: \"xxx\"}\n\tfmap := makeFunctionServiceMap(0)\n\tfmap.assign(fn, backendURL)\n\n\tfh := &functionHandler{fmap: fmap, Function: *fn}\n\tfunctionHandlerServer := httptest.NewServer(http.HandlerFunc(fh.handler))\n\tfhURL := functionHandlerServer.URL\n\n\ttestRequest(fhURL, testResponseString)\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\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) RetryPolicy() *common.RetryPolicy ", "output": "{\n\treturn request.RequestMetadata.RetryPolicy\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\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\n\n\nfunc Answer() interface{} ", "output": "{\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}"} {"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\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\nfunc (patcher *Dispatch) GetID() int {\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}\n\nfunc GetADispather(maxvalue int) Dispatcher ", "output": "{\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}"} {"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\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\nfunc (ol *OptionList) PermissibleString() string {\n\treturn fmt.Sprintf(`\"%s\"`, strings.Join(ol.allOptions, `\", \"`))\n}\n\nfunc (ol *OptionList) Set(s string) error ", "output": "{\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}"} {"input": "package controller_test\n\nimport \"testing\"\n\n\nfunc AssertEqual(t *testing.T, actualValue interface{}, expectedValue interface{}) {\n\tif actualValue != expectedValue {\n\t\tt.Errorf(\"\\n got: %v\\nwant: %v\", actualValue, expectedValue)\n\t}\n}\n\n\n\n\nfunc AssertNotNil(t *testing.T, actualValue interface{}) ", "output": "{\n\tif actualValue == nil {\n\t\tt.Errorf(\"\\n got: %v\\ndidn't want: %v\", actualValue, nil)\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\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\n\n\nfunc GetSession(dataSource string) *mgo.Session {\n\ts := sessionPool[dataSource]\n\treturn s.Clone()\n}\n\nfunc LoadSessions(dataSourceConfig map[string]*config.DataSourceConfiguration) ", "output": "{\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}"} {"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\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\n\n\nfunc dispatch(b byte) Message ", "output": "{\n\tm := msg(b)\n\tif _, has := msg2String[m]; !has {\n\t\treturn nil\n\t}\n\treturn m\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n)\n\nfunc main() {\n\tinput := [][]int{{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}\n\tfmt.Println(input)\n\tfmt.Println(transpose(input))\n}\n\n\n\nfunc transpose(A [][]int) [][]int ", "output": "{\n\tif A == nil {\n\t\treturn nil\n\t}\n\n\tx := len(A[0])\n\tT := [][]int{}\n\n\tfor i := 0; i < x; i++ {\n\t\tb := []int{}\n\t\tT = append(T, b)\n\t\tfor j := 0; j < len(A); j++ {\n\t\t\tT[i] = append(T[i], A[j][i])\n\t\t}\n\t}\n\n\treturn T\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"github.com/gin-gonic/gin\"\n\t\"github.com/tealeg/xlsx\"\n\t\"net/http\"\n)\n\ntype Competition struct {\n\tName string `json:\"name\"`\n\n\tScores []Score `json:\"scores\"`\n}\n\ntype Score struct {\n\tPlayer string `json:\"player\"`\n\tRounds []int `json:\"rounds\"`\n}\n\n\n\nfunc main() {\n\texcelFileName := \"./scores.xlsx\"\n\n\tgin.SetMode(gin.ReleaseMode)\n\tr := gin.Default()\n\tr.LoadHTMLGlob(\"./static/templates/*\")\n\n\tr.Static(\"/static\", \"./static\")\n\n\tr.GET(\"/\", func(c *gin.Context) {\n\t\tobj := gin.H{}\n\t\tc.HTML(http.StatusOK, \"index.tmpl\", obj)\n\t})\n\n\tr.GET(\"/scores\", func(c *gin.Context) {\n\t\tcomps := ParseXlsx(excelFileName)\n\t\tc.JSON(200, comps)\n\t})\n\n\tfmt.Println(\"Listening on localhost:8080\")\n\tr.Run(\":8080\")\n}\n\nfunc ParseXlsx(file string) []Competition ", "output": "{\n\txlFile, err := xlsx.OpenFile(file)\n\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n\n\tvar comps []Competition\n\n\tfor _, sheet := range xlFile.Sheets {\n\t\tvar comp Competition\n\t\tcomp.Name = sheet.Name\n\n\t\tfor i, row := range sheet.Rows {\n\t\t\tif i == 0 {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tvar score Score\n\n\t\t\tfor j, cell := range row.Cells {\n\t\t\t\tif j == 0 {\n\t\t\t\t\tscore.Player = cell.String()\n\t\t\t\t} else {\n\t\t\t\t\tr, _ := cell.Int()\n\t\t\t\t\tif j < 3 && len(cell.String()) > 0 {\n\t\t\t\t\t\tscore.Rounds = append(score.Rounds, r)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tcomp.Scores = append(comp.Scores, score)\n\t\t}\n\n\t\tcomps = append(comps, comp)\n\t}\n\n\treturn comps\n}"} {"input": "package eventgrid\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.3.1-beta\"\n}\n\nfunc UserAgent() string ", "output": "{\n\treturn \"Azure-SDK-For-Go/v10.3.1-beta arm-eventgrid/2017-06-15-preview\"\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\nfunc (o *CommissionSiteURL) Build() (*url.URL, error) {\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}\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\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) 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 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}"} {"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\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 *lengthStack) init() ", "output": "{\n\ts.stack = s.stack0[:0]\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\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\nfunc TestDropLeadingSorter(t *testing.T) {\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}\n\nfunc TestSpaces(t *testing.T) ", "output": "{\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}"} {"input": "package lib_gc_log\n\nimport (\n\t\"io\"\n\t\"log\"\n\t\"os\"\n)\n\nfunc init() {\n\tInit(os.Stdout, os.Stdout, os.Stdout, os.Stdout)\n}\n\nvar (\n\tTrace *log.Logger\n\tInfo *log.Logger\n\tWarning *log.Logger\n\tError *log.Logger\n)\n\nvar LogLevel LOG_LEVEL = TRACE\n\n\n\nfunc Init(\n\ttraceHandle io.Writer,\n\tinfoHandle io.Writer,\n\twarningHandle io.Writer,\n\terrorHandle io.Writer) ", "output": "{\n\n\tTrace = log.New(traceHandle,\n\t\t\"TRACE: \",\n\t\tlog.Ldate|log.Ltime|log.Lmicroseconds|log.Lshortfile)\n\n\tInfo = log.New(infoHandle,\n\t\t\"INFO: \",\n\t\tlog.Ldate|log.Ltime|log.Lmicroseconds|log.Lshortfile)\n\n\tWarning = log.New(warningHandle,\n\t\t\"WARNING: \",\n\t\tlog.Ldate|log.Ltime|log.Lmicroseconds|log.Lshortfile)\n\n\tError = log.New(errorHandle,\n\t\t\"ERROR: \",\n\t\tlog.Ldate|log.Ltime|log.Lmicroseconds|log.Lshortfile)\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\nfunc NewMustRunAs(options *extensions.RunAsUserStrategyOptions) (RunAsUserStrategy, error) {\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}\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\n\n\nfunc (s *mustRunAs) isValidUID(id int64) bool ", "output": "{\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}"} {"input": "package tbin\n\nimport (\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"testing\"\n)\n\n\n\nfunc TestTBinMarshallableDecode(test *testing.T) {\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}\n\nfunc (line *Polyline) UnmarshalTBin(dec *Decoder) error ", "output": "{\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}"} {"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\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 lrucache\n\nimport (\n\t\"strconv\"\n\t\"testing\"\n)\n\ntype bytes []byte\n\n\n\nfunc BenchmarkGet(b *testing.B) {\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}\n\nfunc (b bytes) Size() uint64 ", "output": "{\n\treturn uint64(cap(b))\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/metrics/pkg/apis/metrics\"\n\t\"k8s.io/metrics/pkg/apis/metrics/v1beta1\"\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: metrics.GroupName,\n\t\t\tVersionPreferenceOrder: []string{v1beta1.SchemeGroupVersion.Version},\n\t\t\tRootScopedKinds: sets.NewString(\"NodeMetrics\"),\n\t\t\tAddInternalObjectsToScheme: metrics.AddToScheme,\n\t\t},\n\t\tannounced.VersionToSchemeFunc{\n\t\t\tv1beta1.SchemeGroupVersion.Version: v1beta1.AddToScheme,\n\t\t},\n\t).Announce(groupFactoryRegistry).RegisterAndEnable(registry, scheme); err != nil {\n\t\tpanic(err)\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\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) Before(o Timestamp) bool ", "output": "{\n\treturn t < o\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\nfunc ToZkPool(p config.Pool) (ZkPool, map[string]config.Host) {\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}\n\n\n\nfunc (z ZkPool) Pool(hosts map[string]config.Host) config.Pool ", "output": "{\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}"} {"input": "package mocks\n\nimport (\n\t\"errors\"\n)\n\ntype BuildEngine struct {\n\tIsError bool\n\tBuildSiteCalled bool\n}\n\n\n\nfunc (be *BuildEngine) BuildSite(source string) error ", "output": "{\n\tbe.BuildSiteCalled = true\n\tif be.IsError {\n\t\treturn errors.New(\"Some error\")\n\t}\n\treturn nil\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\n\n\nfunc (m *MovingText) Tick(ev tl.Event) {\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}\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) Draw(s *tl.Screen) ", "output": "{\n\tm.text.Draw(s)\n}"} {"input": "\n\nfunc arrangeCoins(n int) int ", "output": "{\n var ret,index int\n index = 1\n for n >= 0 {\n n -= index\n index++\n ret++\n }\n return ret-1\n}"} {"input": "package get_cocoa\n\nimport (\n\t\"log\"\n\n\t\"github.com/gonum/plot\"\n\t\"github.com/gonum/plot/plotter\"\n\t\"github.com/gonum/plot/plotutil\"\n\t\"github.com/gonum/plot/vg\"\n)\n\ntype PlotStruct struct {\n\tX float64\n\tY float64\n}\n\n\n\nfunc Plot(series plotter.XYs) ", "output": "{\n\tp, err := plot.New()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tp.Title.Text = \"Time Series\"\n\tp.X.Label.Text = \"Day #\"\n\tp.Y.Label.Text = \"Price\"\n\n\terr = plotutil.AddLinePoints(p,\n\t\t\"Close\", series,\n\t)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tif err := p.Save(12*vg.Inch, 6*vg.Inch, \"price.png\"); err != nil {\n\t\tlog.Fatal(err)\n\t}\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\nfunc (s *GitService) GetBlob(owner string, repo string, sha string) (*Blob, *Response, error) {\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}\n\n\n\n\n\n\nfunc (s *GitService) CreateBlob(owner string, repo string, blob *Blob) (*Blob, *Response, error) ", "output": "{\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}"} {"input": "package cli\n\nimport (\n\t\"crypto/x509\"\n\t\"errors\"\n\n\t\"github.com/twstrike/coyim/config\"\n\t\"github.com/twstrike/coyim/digests\"\n\tourtls \"github.com/twstrike/coyim/tls\"\n)\n\nfunc (c *cliUI) verifier() ourtls.Verifier {\n\tconf := c.session.GetConfig()\n\treturn &ourtls.BasicVerifier{\n\t\tOnNoPeerCertificates: func() { c.session.SetWantToBeOnline(false) },\n\t\tOnPinDeny: func() { c.session.SetWantToBeOnline(false) },\n\t\tHasPinned: func(certs []*x509.Certificate) bool { return checkPinned(conf, certs) },\n\t\tVerifyFailure: func(certs []*x509.Certificate, err error) error {\n\t\t\treturn errors.New(\"tls: failed to verify TLS certificate: \" + err.Error())\n\t\t},\n\t\tVerifyHostnameFailure: func(certs []*x509.Certificate, origin string, err error) error {\n\t\t\treturn errors.New(\"tls: failed to match TLS certificate to name: \" + err.Error())\n\t\t},\n\t\tAddCert: func(cert *x509.Certificate) {\n\t\t\tconf.SaveCert(cert.Subject.CommonName, cert.Issuer.CommonName, digests.Sha3_256(cert.Raw))\n\t\t\tc.SaveConf()\n\t\t},\n\t\tAskPinning: func(certs []*x509.Certificate) error {\n\t\t\tc.session.SetWantToBeOnline(false)\n\t\t\treturn errors.New(\"tls: you manually denied the possibility of connecting using this certificate\")\n\t\t},\n\t\tHasCertificates: func() bool { return len(conf.Certificates) > 0 },\n\t\tNeedToCheckPins: conf.PinningPolicy != \"none\",\n\t\tPinningPolicy: conf.PinningPolicy,\n\t}\n}\n\n\n\nfunc checkPinned(c *config.Account, certs []*x509.Certificate) bool ", "output": "{\n\tif c != nil {\n\t\tfor _, pin := range c.Certificates {\n\t\t\tif pin.Matches(certs[0]) {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t}\n\n\treturn false\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\n\n\nfunc BenchmarkLoop(b *testing.B) {\n\tfor i := 0; i < b.N; i++ {\n\t\tbasename.Loop(path)\n\t}\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 TestLastIndex(t *testing.T) ", "output": "{\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}"} {"input": "\n\nfunc findClosestElements(arr []int, k int, x int) []int {\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}\n\nfunc abs(n int) int ", "output": "{\n if n < 0 {\n return -n\n } else {\n return n\n }\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\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\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) WriteMessage(msgType int, message []byte) (err error) ", "output": "{\n\tc.wmu.Lock()\n\terr = c.ws.WriteMessage(msgType, message)\n\tc.wmu.Unlock()\n\treturn\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\nfunc AnalyzerConstructor(config map[string]interface{}, cache *registry.Cache) (*analysis.Analyzer, error) {\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}\n\n\n\nfunc init() ", "output": "{\n\tregistry.RegisterAnalyzer(AnalyzerName, AnalyzerConstructor)\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\nfunc (r *DeleteAlertRequest) GetApiKey() string {\n\treturn r.ApiKey\n}\n\n\n\nfunc (r *DeleteAlertRequest) GenerateUrl() (string, url.Values, error) ", "output": "{\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}"} {"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\nfunc ExampleToPunycode() {\n\tname := \"インターネット.テスト\"\n\tfmt.Printf(\"%s -> %s\", name, idn.ToPunycode(name))\n}\n\n\n\nfunc ExampleFromPunycode() ", "output": "{\n\tname := \"xn--mgbaja8a1hpac.xn--mgbachtv\"\n\tfmt.Printf(\"%s -> %s\", name, idn.FromPunycode(name))\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\n\n\nfunc ReplaceLoggerDefaultFormatter() {\n\twriter := loggo.NewSimpleWriter(os.Stderr, &CustomFormatter{})\n\tloggo.ReplaceDefaultWriter(writer)\n}\n\nfunc (formatter *CustomFormatter) Format(level loggo.Level, module, filename string, line int, timestamp time.Time, message string) string ", "output": "{\n\treturn fmt.Sprintf(\"%s\", message)\n}"} {"input": "package main\n\nimport (\n\t\"fmt\"\n\t\"strconv\"\n\n\t\"github.com/hyperledger/fabric/core/chaincode/shim\"\n\tpb \"github.com/hyperledger/fabric/protos/peer\"\n)\n\n\ntype SimpleChaincode struct {\n}\n\n\nfunc (t *SimpleChaincode) Init(stub shim.ChaincodeStubInterface) pb.Response {\n\tvar A string \n\tvar Aval int \n\tvar err error\n\t_, args := stub.GetFunctionAndParameters()\n\tif len(args) != 2 {\n\t\treturn shim.Error(\"Incorrect number of arguments. Expecting 2\")\n\t}\n\n\tA = args[0]\n\tAval, err = strconv.Atoi(args[1])\n\tif err != nil {\n\t\treturn shim.Error(\"Expecting integer value for asset holding\")\n\t}\n\tfmt.Printf(\"Aval = %d\\n\", Aval)\n\n\terr = stub.PutState(A, []byte(strconv.Itoa(Aval)))\n\tif err != nil {\n\t\treturn shim.Error(err.Error())\n\t}\n\n\treturn shim.Success(nil)\n}\n\n\nfunc (t *SimpleChaincode) Invoke(stub shim.ChaincodeStubInterface) pb.Response {\n\tfunction, args := stub.GetFunctionAndParameters()\n\tif function == \"query\" {\n\t\treturn t.query(stub, args)\n\t}\n\n\treturn shim.Error(\"Invalid invoke function name. Expecting \\\"query\\\"\")\n}\n\n\n\nfunc main() {\n\terr := shim.Start(new(SimpleChaincode))\n\tif err != nil {\n\t\tfmt.Printf(\"Error starting chaincode: %s\", err)\n\t}\n}\n\nfunc (t *SimpleChaincode) query(stub shim.ChaincodeStubInterface, args []string) pb.Response ", "output": "{\n\tvar A string \n\tvar Aval int \n\tvar err error\n\n\tif len(args) != 2 {\n\t\treturn shim.Error(\"Incorrect number of arguments. Expecting 2\")\n\t}\n\n\tA = args[0]\n\tAval, err = strconv.Atoi(args[1])\n\tif err != nil {\n\t\treturn shim.Error(\"Expecting integer value for asset holding\")\n\t}\n\tfmt.Printf(\"Aval = %d\\n\", Aval)\n\n\terr = stub.PutState(A, []byte(strconv.Itoa(Aval)))\n\tif err != nil {\n\t\tjsonResp := \"{\\\"Error\\\":\\\"Cannot put state within chaincode query\\\"}\"\n\t\treturn shim.Error(jsonResp)\n\t}\n\n\treturn shim.Success(nil)\n}"} {"input": "package dos\n\nimport (\n\t\"os\"\n\t\"path/filepath\"\n\t\"strings\"\n)\n\n\nfunc GetHome() string {\n\thome := os.Getenv(\"HOME\")\n\tif home == \"\" {\n\t\thome = os.Getenv(\"USERPROFILE\")\n\t}\n\treturn home\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\n\n\nfunc ReplaceHomeToTildeSlash(wd string) string ", "output": "{\n\treturn filepath.ToSlash(ReplaceHomeToTilde(wd))\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\nfunc PubliclyAvailable(c *mv.Context) {\n\tc.Response.Write([]byte(\"This page is available for all users.\"))\n}\n\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 PrivatelyAvailable(c *mv.Context) ", "output": "{\n\tc.Response.Write([]byte(\"This page is only for authorized users.\"))\n}"} {"input": "package scheduler\n\nimport \"github.com/aosen/robot\"\n\ntype SimpleScheduler struct {\n\tqueue chan *robot.Request\n}\n\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\nfunc (this *SimpleScheduler) Count() int {\n\treturn len(this.queue)\n}\n\nfunc NewSimpleScheduler() *SimpleScheduler ", "output": "{\n\tch := make(chan *robot.Request, 1024)\n\treturn &SimpleScheduler{ch}\n}"} {"input": "package osext \n\nimport \"path/filepath\"\n\n\n\n\n\n\n\n\nfunc ExecutableFolder() (string, error) {\n\tp, err := Executable()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tfolder, _ := filepath.Split(p)\n\treturn folder, nil\n}\n\nfunc Executable() (string, error) ", "output": "{\n\tp, err := executable()\n\treturn filepath.Clean(p), err\n}"} {"input": "package main\n\nimport (\n\t\"reflect\"\n)\n\ntype Person struct {\n\tname string \"namestr\"\n\tage int\n}\n\n\n\nfunc show(i interface{}) {\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}\n\nfunc main() {\n\tp := new(Person)\n\tp.name = \"test\"\n\tp.age = 18\n\tShowTag(p)\n\tshow(p)\n}\n\nfunc ShowTag(i interface{}) ", "output": "{\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}"} {"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\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\nfunc HandleCollision(c1, c2 Collider) {\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}\n\nfunc CollidersCollide(a, b Collider) bool ", "output": "{\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}"} {"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) }\n\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) Swap(i, j int) ", "output": "{ prs[i], prs[j] = prs[j], prs[i] }"} {"input": "package ukvm\n\nimport (\n\t\"os\"\n\t\"path/filepath\"\n\n\t\"github.com/solo-io/unik/pkg/config\"\n\t\"github.com/solo-io/unik/pkg/state\"\n)\n\ntype UkvmProvider struct {\n\tconfig config.Ukvm\n\tstate state.State\n}\n\nfunc UkvmStateFile() string {\n\treturn filepath.Join(config.Internal.UnikHome, \"ukvm/state.json\")\n\n}\nfunc ukvmImagesDirectory() string {\n\treturn filepath.Join(config.Internal.UnikHome, \"ukvm/images/\")\n}\n\nfunc ukvmInstancesDirectory() string {\n\treturn filepath.Join(config.Internal.UnikHome, \"ukvm/instances/\")\n}\n\nfunc ukvmVolumesDirectory() string {\n\treturn filepath.Join(config.Internal.UnikHome, \"ukvm/volumes/\")\n}\n\n\n\nfunc (p *UkvmProvider) WithState(state state.State) *UkvmProvider {\n\tp.state = state\n\treturn p\n}\nfunc getImageDir(imageName string) string {\n\treturn filepath.Join(ukvmImagesDirectory(), imageName)\n}\nfunc getKernelPath(imageName string) string {\n\treturn filepath.Join(ukvmImagesDirectory(), imageName, \"program.bin\")\n}\nfunc getUkvmPath(imageName string) string {\n\treturn filepath.Join(ukvmImagesDirectory(), imageName, \"ukvm-bin\")\n}\n\nfunc getInstanceDir(instanceName string) string {\n\treturn filepath.Join(ukvmInstancesDirectory(), instanceName)\n}\n\nfunc getInstanceLogName(instanceName string) string {\n\treturn filepath.Join(ukvmInstancesDirectory(), instanceName, \"stdout\")\n}\n\nfunc getVolumePath(volumeName string) string {\n\treturn filepath.Join(ukvmVolumesDirectory(), volumeName, \"data.img\")\n}\n\nfunc NewUkvmProvider(config config.Ukvm) (*UkvmProvider, error) ", "output": "{\n\n\tos.MkdirAll(ukvmImagesDirectory(), 0777)\n\tos.MkdirAll(ukvmInstancesDirectory(), 0777)\n\tos.MkdirAll(ukvmVolumesDirectory(), 0777)\n\n\tp := &UkvmProvider{\n\t\tconfig: config,\n\t\tstate: state.NewBasicState(UkvmStateFile()),\n\t}\n\n\treturn p, nil\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\nfunc NewTTLCache(ttl time.Duration) TTLCache {\n\treturn &ttlCache{\n\t\tttl: ttl,\n\t\tcache: make(map[string]*ttlCacheEntry),\n\t}\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\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 (t *ttlCache) Set(key string, value interface{}) ", "output": "{\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}"} {"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\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\n\n\nfunc SecurityBulletinsFromJson(data io.Reader) SecurityBulletins ", "output": "{\n\tvar o SecurityBulletins\n\tjson.NewDecoder(data).Decode(&o)\n\treturn o\n}"} {"input": "package libFileSwarm\n\nimport (\n\t\"encoding/json\"\n\t\"libytc\"\n\t\"log\"\n)\n\ntype Encoder struct {\n}\n\n\n\nfunc (e Encoder) DecodeBlock(b []byte) libytc.Block {\n\tblock := new(Block)\n\tjson.Unmarshal(b, block)\n\treturn block\n}\n\nfunc (e Encoder) EncodeBlock(b libytc.Block) []byte ", "output": "{\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}"} {"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\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) Count(t int) int64 ", "output": "{\n\tcount, err := DbMap.SelectInt(\"SELECT count(*) FROM \"+this.TableName()+\" WHERE type = ?\", t)\n\tutils.HandleError(err)\n\n\treturn count\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\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\n\n\nfunc testGetMessages(t *testing.T, requestURL string) string ", "output": "{\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}"} {"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\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 Listxattr(path string, dest []byte) (sz int, err error) ", "output": "{\n\treturn syscall.Listxattr(path, dest)\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\nfunc NewReverseProxy(backends []string) *ReverseProxy {\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}\n\n\n\nfunc (rp *ReverseProxy) ServeHTTP(w http.ResponseWriter, r *http.Request) ", "output": "{\n\trp.handler.ServeHTTP(w, r)\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\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 WithNotFound(f http.Handler) ConfigOption ", "output": "{\n\treturn ConfigOptionFunc(func(c *Config) { c.NotFound = f })\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\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) swap(n int) ", "output": "{\n\tst.data[st.len()-n], st.data[st.len()-1] = st.data[st.len()-1], st.data[st.len()-n]\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\n\n\n\nfunc (a *GapBuf) Len() int {\n\treturn len(a.buffer) + a.gapStart - a.gapEnd\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 New(size int) *GapBuf ", "output": "{\n\ta := GapBuf{\n\t\tbuffer: make([]*line.Line, size),\n\t\tgapStart: 0,\n\t\tgapEnd: size,\n\t}\n\treturn &a\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\n\n\nfunc init() {\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}\n\nfunc (l *CertPolicyRequiresPersonalName) Execute(cert *x509.Certificate) *LintResult ", "output": "{\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}"} {"input": "package efs\n\nimport (\n\t\"testing\"\n\n\tapitests \"github.com/codedellemc/libstorage/api/tests\"\n\n\t\"github.com/codedellemc/libstorage/drivers/storage/efs\"\n\t_ \"github.com/codedellemc/libstorage/drivers/storage/efs/storage\"\n)\n\n\n\nfunc TestSuite(t *testing.T) ", "output": "{\n\tapitests.RunSuite(t, efs.Name)\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\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 (l *SANEDI) Initialize() error ", "output": "{\n\treturn nil\n}"} {"input": "package arm\n\nimport (\n\t\"testing\"\n\n\t\"golang.org/x/crypto/ssh\"\n)\n\n\n\nfunc TestPrivateKeyShouldParse(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\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}\n\nfunc TestAuthorizedKeyShouldParse(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\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}"} {"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\n\n\n\n\nfunc (t *SuiteSuite) VerifyMethodsWrongSignatureSkipped2() int {\n\tt.Fatalf(\"This should never run.\")\n\treturn 0\n}\n\nfunc (t *SuiteSuite) VerifyMethodsWrongSignatureSkipped1(x int) ", "output": "{\n\tt.Fatalf(\"This should never run.\")\n}"} {"input": "package main\n\ntype CCState int\n\nconst (\n CCStateIdle = CCState(iota)\n CCStateWaitRoute\n CCStateARComplete\n CCStateConnected\n CCStateDead\n CCStateDisconnecting\n)\n\n\n\nfunc (self CCState) String() string ", "output": "{\n switch self {\n case CCStateIdle:\n return \"Idle\"\n case CCStateWaitRoute:\n return \"WaitRoute\"\n case CCStateARComplete:\n return \"ARComplete\"\n case CCStateConnected:\n return \"Connected\"\n case CCStateDead:\n return \"Dead\"\n case CCStateDisconnecting:\n return \"Disconnecting\"\n }\n return \"Unknown\"\n}"} {"input": "package job\n\nimport (\n\tmetav1 \"k8s.io/apimachinery/pkg/apis/meta/v1\"\n\t\"k8s.io/kubernetes/pkg/api/v1\"\n\tbatch \"k8s.io/kubernetes/pkg/apis/batch/v1\"\n)\n\n\n\nfunc newControllerRef(j *batch.Job) *metav1.OwnerReference {\n\tblockOwnerDeletion := true\n\tisController := true\n\treturn &metav1.OwnerReference{\n\t\tAPIVersion: controllerKind.GroupVersion().String(),\n\t\tKind: controllerKind.Kind,\n\t\tName: j.Name,\n\t\tUID: j.UID,\n\t\tBlockOwnerDeletion: &blockOwnerDeletion,\n\t\tController: &isController,\n\t}\n}\n\nfunc IsJobFinished(j *batch.Job) bool ", "output": "{\n\tfor _, c := range j.Status.Conditions {\n\t\tif (c.Type == batch.JobComplete || c.Type == batch.JobFailed) && c.Status == v1.ConditionTrue {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}"} {"input": "package redisconn\n\nimport (\n\t\"bufio\"\n\t\"net\"\n\t\"time\"\n\n\t\"github.com/juju/errors\"\n\t\"github.com/ngaut/deadline\"\n)\n\nconst (\n\tDefaultBufSize = 4 * 1024\n)\n\n\ntype Conn struct {\n\taddr string\n\tnc net.Conn\n\tclosed bool\n\tr *bufio.Reader\n\tw *bufio.Writer\n\tnetTimeout int \n}\n\nfunc NewConnection(addr string, netTimeout int) (*Conn, error) {\n\treturn NewConnectionWithSize(addr, netTimeout, DefaultBufSize, DefaultBufSize)\n}\n\n\n\n\nfunc (c *Conn) Read(p []byte) (int, error) {\n\tpanic(\"not allowed\")\n}\n\nfunc (c *Conn) Flush() error {\n\treturn c.w.Flush()\n}\n\nfunc (c *Conn) Write(p []byte) (int, error) {\n\treturn c.w.Write(p)\n}\n\nfunc (c *Conn) BufioReader() *bufio.Reader {\n\treturn c.r\n}\n\nfunc (c *Conn) SetWriteDeadline(t time.Time) error {\n\treturn c.nc.SetWriteDeadline(t)\n}\n\nfunc (c *Conn) SetReadDeadline(t time.Time) error {\n\treturn c.nc.SetReadDeadline(t)\n}\n\nfunc (c *Conn) SetDeadline(t time.Time) error {\n\treturn c.nc.SetDeadline(t)\n}\n\nfunc (c *Conn) Close() {\n\tif c.closed {\n\t\treturn\n\t}\n\tc.closed = true\n\tc.nc.Close()\n}\n\nfunc NewConnectionWithSize(addr string, netTimeout int, readSize int, writeSize int) (*Conn, error) ", "output": "{\n\tconn, err := net.DialTimeout(\"tcp\", addr, time.Duration(netTimeout)*time.Second)\n\tif err != nil {\n\t\treturn nil, errors.Trace(err)\n\t}\n\n\treturn &Conn{\n\t\taddr: addr,\n\t\tnc: conn,\n\t\tclosed: false,\n\t\tr: bufio.NewReaderSize(conn, readSize),\n\t\tw: bufio.NewWriterSize(deadline.NewDeadlineWriter(conn, time.Duration(netTimeout)*time.Second), writeSize),\n\t\tnetTimeout: netTimeout,\n\t}, nil\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\nfunc (m ThreatFeedAction) String() string {\n\treturn common.PointerString(m)\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\n\n\nfunc GetThreatFeedActionActionEnumValues() []ThreatFeedActionActionEnum ", "output": "{\n\tvalues := make([]ThreatFeedActionActionEnum, 0)\n\tfor _, v := range mappingThreatFeedActionAction {\n\t\tvalues = append(values, v)\n\t}\n\treturn values\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\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<= interval {\n\t\tt.Error(\"The limiter blocked when it shouldn't have\")\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\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) Synopsis() string ", "output": "{\n\treturn \"Force the Vault node to give up active duty\"\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\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 (c *CounterStat) Increment(num int) ", "output": "{\n\tc.calculations <- num\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\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\n\n\nfunc main() {}\n\nfunc f7(a []int) ", "output": "{\n\tfor i := uint(len(a)) - 1; i < uint(len(a)); i-- { \n\t\ta[i] = 0\n\t}\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\nfunc NewTrafficMonitorConfigMap() TrafficMonitorConfigMap {\n\treturn TrafficMonitorConfigMap{monitorConfig: &tc.TrafficMonitorConfigMap{}, m: &sync.RWMutex{}}\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\n\n\nfunc (t *TrafficMonitorConfigMap) Set(c tc.TrafficMonitorConfigMap) ", "output": "{\n\tt.m.Lock()\n\t*t.monitorConfig = c\n\tt.m.Unlock()\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\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\nfunc MakeViewPostEndpoint(svc HttpService) endpoint.Endpoint {\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}\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 MakeLoginEndpoint(svc HttpService) endpoint.Endpoint ", "output": "{\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}"} {"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\n\n\n\nfunc checkPrivileges() bool {\n\n\tif user, err := user.Current(); err == nil && user.Gid == \"0\" {\n\t\treturn true\n\t}\n\treturn false\n}\n\nfunc executablePath(name string) (string, error) ", "output": "{\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}"} {"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\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 RespondWithError(w http.ResponseWriter, httpErrCode int, errMsg string) ", "output": "{\n\tresp := StandardErrorRespModel{\n\t\tErrorMessage: errMsg,\n\t}\n\tRespondWithErrorJSON(w, httpErrCode, resp)\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\n\n\nfunc TestNewProcessorFactory_WithOptions(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\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}\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(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\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}"} {"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\n\n\nfunc TestGenerate(t *testing.T) {\n i := 1\n for s := range Generate(text, 0) {\n t.Logf(\"Generate: %d) %v\", i, s)\n i++\n }\n}\n\nfunc TestGenerateRandom(t *testing.T) ", "output": "{\n i := 1\n for s := range GenerateRandom(text, 0, 10, true) {\n t.Logf(\"GenerateRandom: %d) %v\", i, s)\n i++\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\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 TestEventerOn(t *testing.T) ", "output": "{\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}"} {"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\n\n\nfunc init() {\n\tcobra.OnInitialize(initConfig)\n\n\n\tRootCmd.Flags().BoolP(\"toggle\", \"t\", false, \"Help message for toggle\")\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 Execute() ", "output": "{\n\tif err := RootCmd.Execute(); err != nil {\n\t\tfmt.Println(err)\n\t\tos.Exit(-1)\n\t}\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}\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 MustClone(src, dst interface{}) ", "output": "{\n\tif err := Clone(src, dst); err != nil {\n\t\tpanic(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\nfunc (response CreateExternalPublicationResponse) String() string {\n\treturn common.PointerString(response)\n}\n\n\n\n\nfunc (response CreateExternalPublicationResponse) HTTPResponse() *http.Response ", "output": "{\n\treturn response.RawResponse\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\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 (m *MockExecutor) EXPECT() *MockExecutorMockRecorder ", "output": "{\n\treturn m.recorder\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\n\n\n\n\nfunc (k *rsaPublicKey) PublicKey() (bccsp.Key, error) {\n\treturn k, nil\n}\n\nfunc (k *rsaPublicKey) Private() bool ", "output": "{\n\treturn false\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\n\n\n\ntype MkdirRequest struct {\n\tPath string `json:\"path\"`\n}\n\nfunc (mh *MkdirHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {\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}\n\nfunc NewMkdirHandler(s *State) *MkdirHandler ", "output": "{\n\treturn &MkdirHandler{State: s}\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\n\n\nfunc show(c *gin.Context) {\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}\n\nfunc GetRoutesForRouter(router *gin.RouterGroup) ", "output": "{\n\tapps := router.Group(\"/jobs/:job_id\", common.Auth(true))\n\t{\n\t\tapps.GET(\"\", show)\n\t}\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\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\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 NewBufferedSectionReader(ra io.ReaderAt, off, n int64) io.Reader ", "output": "{\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}"} {"input": "package util\n\nimport (\n\t\"reflect\"\n\n\tapi_v1 \"k8s.io/kubernetes/pkg/api/v1\"\n)\n\n\n\n\nfunc CopyObjectMeta(obj api_v1.ObjectMeta) api_v1.ObjectMeta {\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}\n\n\n\n\n\n\nfunc ObjectMetaEquivalent(a, b api_v1.ObjectMeta) bool ", "output": "{\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}"} {"input": "package caviar\n\nimport (\n \"errors\"\n \"strings\"\n \"path\"\n \"path/filepath\"\n \"net/http\"\n)\n\n\ntype Dir string\n\n\n\n\nfunc (d Dir) Open(name string) (http.File, error) ", "output": "{\n if filepath.Separator != '/' && strings.IndexRune(name, filepath.Separator) >= 0 ||\n strings.Contains(name, \"\\x00\") {\n return nil, debug(errors.New(\"http: invalid character in file path\"))\n }\n dir := string(d)\n if dir == \"\" {\n dir = \".\"\n }\n f, err := Open(filepath.Join(dir, filepath.FromSlash(path.Clean(\"/\"+name))))\n if err != nil {\n return nil, debug(err)\n }\n return f, 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\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 (db *DB) Insert(pseg *seg.PathSegment, segTypes []seg.Type) (int, error) ", "output": "{\n\treturn db.conn.Insert(pseg, segTypes)\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\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 MakeSyncNowEndpoint(s Service) endpoint.Endpoint ", "output": "{\n\treturn func(ctx context.Context, _ interface{}) (interface{}, error) {\n\t\ts.SyncNow(ctx)\n\t\treturn syncNowResponse{}, nil\n\t}\n}"} {"input": "package main\n\nimport (\n\n\t\"gopkg.in/mgo.v2/bson\"\n\n\t\"github.com/mindcastio/mindcastio/backend\"\n\t\"github.com/mindcastio/mindcastio/backend/datastore\"\n\t\"github.com/mindcastio/mindcastio/backend/environment\"\n\t\"github.com/mindcastio/mindcastio/backend/logger\"\n\t\"github.com/mindcastio/mindcastio/backend/metrics\"\n\t\"github.com/mindcastio/mindcastio/backend/util\"\n)\n\n\n\nfunc main() {\n\n\tenv := environment.GetEnvironment()\n\tlogger.Initialize()\n\tmetrics.Initialize(env)\n\tdefer metrics.Shutdown()\n\tdatastore.Initialize(env)\n\tdefer datastore.Shutdown()\n\n\tds := datastore.GetDataStore()\n\tdefer ds.Close()\n\n\tmain_index := ds.Collection(datastore.META_COL)\n\n\tresults := []backend.PodcastIndex{}\n\tmain_index.Find(nil).All(&results)\n\n\tfor i := range results {\n\t\tresults[i].UpdateRate = backend.DEFAULT_UPDATE_RATE\n\t\tresults[i].Next = util.IncT(util.Timestamp(), util.Random(backend.DEFAULT_UPDATE_RATE))\n\t\tresults[i].Updated = util.Timestamp()\n\n\t\tmain_index.Update(bson.M{\"uid\": results[i].Uid}, &results[i])\n\t}\n\n}\n\n\n\nfunc check(e error) ", "output": "{\n\tif e != nil {\n\t\tpanic(e)\n\t}\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\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 GetAlertManagerDaemonsetName(appName string) string ", "output": "{\n\treturn fmt.Sprintf(\"alertmanager-%s\", appName)\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\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) DependsOn() []string ", "output": "{\n\treturn r._dependsOn\n}"} {"input": "package cmd\n\nimport (\n\t\"github.com/cloudfoundry/bosh-init/director/template\"\n\tboshui \"github.com/cloudfoundry/bosh-init/ui\"\n)\n\ntype BuildManifestCmd struct {\n\tui boshui.UI\n}\n\n\n\nfunc (c BuildManifestCmd) Run(opts BuildManifestOpts) error {\n\tvariables := opts.VarFlags.AsVariables()\n\n\ttemplate := template.NewTemplate(opts.Args.Manifest.Bytes)\n\n\tevaluatedManifest, err := template.Evaluate(variables)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tc.ui.PrintBlock(string(evaluatedManifest))\n\treturn nil\n}\n\nfunc NewBuildManifestCmd(ui boshui.UI) BuildManifestCmd ", "output": "{\n\treturn BuildManifestCmd{\n\t\tui: ui,\n\t}\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\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) Less(i, j int) bool ", "output": "{\n\treturn rs[i].Value < rs[j].Value\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\nfunc (request DeleteLoadBalancerRequest) HTTPRequest(method, path string) (http.Request, error) {\n\treturn common.MakeDefaultHTTPRequestWithTaggedStruct(method, path, request)\n}\n\n\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) RetryPolicy() *common.RetryPolicy ", "output": "{\n\treturn request.RequestMetadata.RetryPolicy\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\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\nfunc (a acceptor) Accept() (network.Connection, error) {\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}\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 (t listener) Listen() (network.Acceptor, error) ", "output": "{\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}"} {"input": "package audioplayer\n\nimport (\n \"govkmedia/dialogboxes\"\n \"govkmedia/requestwrapper\"\n \"strconv\"\n \"time\"\n)\n\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\nfunc (e *Engine) Prev() {\n if e.currentPlaying==0 { return }\n e.currentPlaying--\n e.StartPlay()\n}\n\nfunc (e *Engine) StartPlay() ", "output": "{\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}"} {"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/2018-09-01\"\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\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\nfunc (j *Queue) JobQueuingDone() {\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}\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) AddAndStartWorkers(num int) *Queue ", "output": "{\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}"} {"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\nfunc New(endpoint string, userName string) BaseClient {\n\treturn NewWithoutDefaults(endpoint, userName)\n}\n\n\n\n\nfunc NewWithoutDefaults(endpoint string, userName string) BaseClient ", "output": "{\n\treturn BaseClient{\n\t\tClient: autorest.NewClientWithUserAgent(UserAgent()),\n\t\tEndpoint: endpoint,\n\t\tUserName: userName,\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\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\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 newIndexOfInitialisms() *indexOfInitialisms ", "output": "{\n\treturn &indexOfInitialisms{\n\t\tgetMutex: new(sync.Mutex),\n\t\tindex: make(map[string]bool, 50),\n\t}\n}"}