text
stringlengths
11
4.05M
package main import ( "github.com/atymkiv/sa/cmd/subscribers/service" "github.com/atymkiv/sa/pkg/utl/config" "github.com/atymkiv/sa/pkg/utl/nats" "sync" ) func main() { cfg, err := config.Load("./config/subscribers.yaml") checkErr(err) natsClient, err := nats.New(cfg.Nats) checkErr(err) service.Subscriber(natsClient, "shops") wg := sync.WaitGroup{} wg.Add(1) wg.Wait() } func checkErr(err error) { if err != nil { panic(err) } }
// Copyright 2019 Yunion // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package tasks import ( "context" "yunion.io/x/jsonutils" "yunion.io/x/pkg/errors" api "yunion.io/x/onecloud/pkg/apis/compute" "yunion.io/x/onecloud/pkg/cloudcommon/db" "yunion.io/x/onecloud/pkg/cloudcommon/db/taskman" "yunion.io/x/onecloud/pkg/cloudprovider" "yunion.io/x/onecloud/pkg/compute/models" "yunion.io/x/onecloud/pkg/util/logclient" ) type InterVpcNetworkAddVpcTask struct { taskman.STask } func init() { taskman.RegisterTask(InterVpcNetworkAddVpcTask{}) } func (self *InterVpcNetworkAddVpcTask) taskFailed(ctx context.Context, network *models.SInterVpcNetwork, err error) { network.SetStatus(self.UserCred, api.INTER_VPC_NETWORK_STATUS_ADDVPC_FAILED, err.Error()) db.OpsLog.LogEvent(network, db.ACT_NETWORK_ADD_VPC, err, self.UserCred) logclient.AddActionLogWithStartable(self, network, logclient.ACT_NETWORK_ADD_VPC, err, self.UserCred, false) self.SetStageFailed(ctx, jsonutils.NewString(err.Error())) } func (self *InterVpcNetworkAddVpcTask) taskComplete(ctx context.Context, network *models.SInterVpcNetwork) { network.SetStatus(self.GetUserCred(), api.INTER_VPC_NETWORK_STATUS_AVAILABLE, "") logclient.AddActionLogWithStartable(self, network, logclient.ACT_NETWORK_ADD_VPC, nil, self.UserCred, true) self.SetStageComplete(ctx, nil) } func (self *InterVpcNetworkAddVpcTask) OnInit(ctx context.Context, obj db.IStandaloneModel, body jsonutils.JSONObject) { interVpcNetwork := obj.(*models.SInterVpcNetwork) vpcId, err := self.Params.GetString("vpc_id") if err != nil { self.taskFailed(ctx, interVpcNetwork, errors.Wrap(err, `self.Params.GetString("vpc_id")`)) return } _vpc, err := models.VpcManager.FetchById(vpcId) if err != nil { self.taskFailed(ctx, interVpcNetwork, errors.Wrap(err, `models.VpcManager.FetchById(vpcId)`)) return } vpc := _vpc.(*models.SVpc) iVpc, err := vpc.GetIVpc() if err != nil { self.taskFailed(ctx, interVpcNetwork, errors.Wrap(err, ` vpc.GetIVpc()`)) return } iVpcNetwork, err := interVpcNetwork.GetICloudInterVpcNetwork() if err != nil { self.taskFailed(ctx, interVpcNetwork, errors.Wrap(err, "GetICloudInterVpcNetwork()")) return } joinVpcOPts := cloudprovider.SVpcJointInterVpcNetworkOption{ InterVpcNetworkId: iVpcNetwork.GetId(), NetworkAuthorityOwnerId: iVpcNetwork.GetAuthorityOwnerId(), } err = iVpc.ProposeJoinICloudInterVpcNetwork(&joinVpcOPts) if err != nil { self.taskFailed(ctx, interVpcNetwork, errors.Wrapf(err, "iVpc.ProposeJoinICloudInterVpcNetwork(%s)", jsonutils.Marshal(joinVpcOPts).String())) return } addVpcOpts := cloudprovider.SInterVpcNetworkAttachVpcOption{ VpcId: iVpc.GetId(), VpcRegionId: iVpc.GetRegion().GetId(), VpcAuthorityOwnerId: iVpc.GetAuthorityOwnerId(), } err = iVpcNetwork.AttachVpc(&addVpcOpts) if err != nil { self.taskFailed(ctx, interVpcNetwork, errors.Wrapf(err, " iVpcNetwork.AddVpc(%s)", jsonutils.Marshal(addVpcOpts).String())) return } self.SetStage("OnSyncInterVpcNetworkComplete", nil) models.StartResourceSyncStatusTask(ctx, self.GetUserCred(), interVpcNetwork, "InterVpcNetworkSyncstatusTask", self.GetTaskId()) } func (self *InterVpcNetworkAddVpcTask) OnSyncInterVpcNetworkComplete(ctx context.Context, network *models.SInterVpcNetwork, data jsonutils.JSONObject) { self.SetStageComplete(ctx, nil) } func (self *InterVpcNetworkAddVpcTask) OnSyncInterVpcNetworkCompleteFailed(ctx context.Context, network *models.SInterVpcNetwork, data jsonutils.JSONObject) { self.SetStageFailed(ctx, data) }
package rule import ( "sync" "go.uber.org/atomic" ) // A node containing information about a domain component. type node struct { // The domain component's value. Value string // Whether or not this domain component is blocked. Blocked *atomic.Bool // The complete domain which this domain component is a part of. // Nil if this is not the most-specific domain component in the domain. FQDN *atomic.String // All children (subdomains) of this node. Children sync.Map } // Stores a domain into the passed domain component tree. func block(n *node, fqdn string, path []string) { cur := n for _, dc := range path { v, ok := cur.Children.Load(dc) if ok { cur = v.(*node) // This node is already blocked and a complete rule already exists // for this path. #A if cur.Blocked.Load() { return } } else { newNode := node{ Value: dc, Blocked: atomic.NewBool(false), FQDN: &atomic.String{}, } cur.Children.Store(dc, &newNode) cur = &newNode } } cur.Blocked.Store(true) cur.FQDN.Store(fqdn) } // Returns the least-specific blocked domains in the domain component tree. func read(n *node, result *[]string) { cur := n if cur.Blocked.Load() { *result = append(*result, cur.FQDN.Load()) return // This should have no effect if #A works. } (cur.Children).Range(func(key, value interface{}) bool { read(value.(*node), result) return true }) }
// Copyright 2020 The Cockroach Authors. // // Use of this software is governed by the Business Source License // included in the file licenses/BSL.txt. // // As of the Change Date specified in that file, in accordance with // the Business Source License, use of this software will be governed // by the Apache License, Version 2.0, included in the file // licenses/APL.txt. package rowflow import ( "context" "sync" "github.com/cockroachdb/cockroach/pkg/sql/execinfra" "github.com/cockroachdb/cockroach/pkg/sql/execinfrapb" "github.com/cockroachdb/cockroach/pkg/sql/types" ) // MakeTestRouter creates a router to be used by tests. func MakeTestRouter( ctx context.Context, flowCtx *execinfra.FlowCtx, spec *execinfrapb.OutputRouterSpec, streams []execinfra.RowReceiver, types []*types.T, wg *sync.WaitGroup, ) (execinfra.RowReceiver, error) { r, err := makeRouter(spec, streams) if err != nil { return nil, err } r.init(ctx, flowCtx, types) r.Start(ctx, wg, nil /* ctxCancel */) return r, nil }
package main import ( "crypto/tls" "io" "log" "time" ) //时间数据做了一点改动,因为毫秒总会有误差 var stimes = [25]int{122, 163, 204, 205, 245, 246, 247, 248, 249, 250, 251, 252, 285, 286, 287, 288, 289, 290, 291, 325, 326, 327, 328, 759, 844, } //var stimes = [25] int {122, 163, 204, 205, 245, 246, 247, 248, 249, 250, 251, 252, // 278, 279, 280, 281, 282, 283, 284, 315, 316, 317, 318, 746, 844, // } //注意有重发的情况,只需要发一半 var packageCount = [25]int{4, 2, 4, 4, 8, 4, 2, 4, 8, 2, 2, 6, 4, 6, 4, 4, 8, 6, 6, 2, 4, 4, 2, 6, 2, } var packageLength = [25]int{26586, 52548, 49896, 55416, 44592, 11256, 11148, 22296, 38466, 8388, 5628, 16884, 16776, 36204, 38856, 22296, 55632, 41724, 44484, 8388, 22296, 56822, 11358, 8376, 108, } //var slice = make([]string, 5) var slice = make([]string, 0) func init() { //330 //a := "中新网6月15日电 综合报道,美国一名现年70岁的新冠患者在医院度过62天后终于治愈,可当他出院后,却发现自己账单总额超过了110万美元。由于拥有医疗保险,他应该不必由于拥有医疗保险,他应该不必应该不必由于拥有医疗保险,他应该不必他的a" a := "中新网6月15日电 综合报道,美国一名现年70岁的新冠患" //var count int = 0 for i := 0; i < len(packageCount); i++ { var m = packageCount[i] / 2 var plength = packageLength[i] / packageCount[i] for k := 0; k < m; k++ { var c = plength / len(a) str := "" for j := 0; j < c; j++ { str = str + a } slice = append(slice, str) //count ++ } } } func main() { //注意这里要使用证书中包含的主机名称 tlsConfig := &tls.Config{InsecureSkipVerify: true} conn, err := tls.Dial("tcp", "zyy.centos:443", tlsConfig) if err != nil { log.Fatalln(err.Error()) } //defer conn.Close() //log.Println("Client Connect To ", conn.RemoteAddr()) //status := conn.ConnectionState() //fmt.Printf("%#v\n", status) var count int = 0 var j int = 0 //第一个 1 毫秒需要睡 for i := 0; i < len(stimes); i++ { if i == 0 { //time.Sleep(time.Millisecond * time.Duration(stimes[i] - 12)) time.Sleep(time.Millisecond * time.Duration(stimes[i]-16)) } else { time.Sleep(time.Millisecond * time.Duration(stimes[i]-stimes[i-1])) } for ; j < len(packageCount); j++ { var pkCount int = packageCount[j] / 2 for { str := slice[count] _, err = io.WriteString(conn, str) pkCount-- count++ if pkCount <= 0 || count >= len(slice) { break } } if pkCount <= 0 { j++ break } } } }
// Copyright 2018 Keybase Inc. All rights reserved. // Use of this source code is governed by a BSD // license that can be found in the LICENSE file. package main import ( "context" "io/ioutil" "os" "path/filepath" "testing" "github.com/keybase/kbfs/libpages/config" "github.com/stretchr/testify/require" "golang.org/x/crypto/bcrypt" ) type fakePrompterForTest struct { nextResponse string lastPrompt string } func (p *fakePrompterForTest) Prompt(prompt string) (string, error) { p.lastPrompt = prompt return p.nextResponse, nil } func (p *fakePrompterForTest) PromptPassword(prompt string) (string, error) { p.lastPrompt = prompt return p.nextResponse, nil } func TestEditor(t *testing.T) { configDir, err := ioutil.TempDir(".", "kbpagesconfig-editor-test-") require.NoError(t, err) defer os.RemoveAll(configDir) kbpConfigPath := filepath.Join(configDir, config.DefaultConfigFilename) prompter := &fakePrompterForTest{} editor, err := newKBPConfigEditorWithPrompterAndCost( configDir, prompter, bcrypt.MinCost) require.NoError(t, err) // The config file shouldn't exist yet. _, err = os.Stat(kbpConfigPath) require.Error(t, err) require.True(t, os.IsNotExist(err)) // Call confirmAndWrite which should create the config file. prompter.nextResponse = "y" err = editor.confirmAndWrite() require.NoError(t, err) _, err = os.Stat(kbpConfigPath) require.NoError(t, err) ctx := context.Background() // add user editor, err = newKBPConfigEditorWithPrompterAndCost( configDir, prompter, bcrypt.MinCost) require.NoError(t, err) // It's an empty config now so authentication should fail. ok := editor.kbpConfig.Authenticate(ctx, "alice", "12345") require.False(t, ok) // Try adding a user "alice" with password "12345" and "bob" with password // "54321". prompter.nextResponse = "12345" err = editor.addUser("alice") require.NoError(t, err) prompter.nextResponse = "54321" err = editor.addUser("bob") require.NoError(t, err) prompter.nextResponse = "y" err = editor.confirmAndWrite() require.NoError(t, err) // Re-read the config file and make sure the user is added properly. editor, err = newKBPConfigEditorWithPrompterAndCost( configDir, prompter, bcrypt.MinCost) require.NoError(t, err) ok = editor.kbpConfig.Authenticate(ctx, "alice", "12345") require.True(t, ok) ok = editor.kbpConfig.Authenticate(ctx, "bob", "54321") require.True(t, ok) // remove "bob" editor, err = newKBPConfigEditorWithPrompterAndCost( configDir, prompter, bcrypt.MinCost) require.NoError(t, err) editor.removeUser("bob") require.NoError(t, err) prompter.nextResponse = "y" err = editor.confirmAndWrite() require.NoError(t, err) // Re-read the config file and make sure "bob" is gone and "alice" is still // there. editor, err = newKBPConfigEditorWithPrompterAndCost( configDir, prompter, bcrypt.MinCost) require.NoError(t, err) ok = editor.kbpConfig.Authenticate(ctx, "bob", "54321") require.False(t, ok) ok = editor.kbpConfig.Authenticate(ctx, "alice", "12345") require.True(t, ok) // set anonymous permissions editor, err = newKBPConfigEditorWithPrompterAndCost( configDir, prompter, bcrypt.MinCost) require.NoError(t, err) // We don't have any permission set, so we should get the default read,list // for root. read, list, _, _, _, err := editor.kbpConfig.GetPermissions("/", nil) require.NoError(t, err) require.True(t, read) require.True(t, list) err = editor.setAnonymousPermission("read", "/") require.NoError(t, err) prompter.nextResponse = "y" err = editor.confirmAndWrite() require.NoError(t, err) // Re-read the config file and make sure the user is gone. editor, err = newKBPConfigEditorWithPrompterAndCost( configDir, prompter, bcrypt.MinCost) require.NoError(t, err) read, list, _, _, _, err = editor.kbpConfig.GetPermissions("/", nil) require.NoError(t, err) require.True(t, read) require.False(t, list) alice := "alice" // grant alice additional permissions editor, err = newKBPConfigEditorWithPrompterAndCost( configDir, prompter, bcrypt.MinCost) require.NoError(t, err) read, list, _, _, _, err = editor.kbpConfig.GetPermissions( "/", &alice) require.NoError(t, err) require.True(t, read) require.False(t, list) err = editor.setAdditionalPermission("alice", "list", "/") require.NoError(t, err) prompter.nextResponse = "y" err = editor.confirmAndWrite() require.NoError(t, err) // Re-read the config file and make sure the user is gone. editor, err = newKBPConfigEditorWithPrompterAndCost( configDir, prompter, bcrypt.MinCost) require.NoError(t, err) read, list, _, _, _, err = editor.kbpConfig.GetPermissions( "/", &alice) require.NoError(t, err) require.True(t, read) require.True(t, list) }
package ginlogruslogstash import ( "bytes" "fmt" "log" "math" "net" "net/http" "time" logrustash "github.com/bshuster-repo/logrus-logstash-hook" "github.com/gin-gonic/gin" "github.com/sirupsen/logrus" ) var timeFormat = "02/Jan/2006:15:04:05" type bodyLogWriter struct { gin.ResponseWriter body *bytes.Buffer } func (w bodyLogWriter) Write(b []byte) (int, error) { w.body.Write(b) return w.ResponseWriter.Write(b) } // Logger is the logrus logger handler func Logger(logger *logrus.Logger, connectionString, appName string) gin.HandlerFunc { conn, err := net.Dial("udp", connectionString) if err != nil { log.Println(err) } hook := logrustash.New(conn, logrustash.DefaultFormatter(logrus.Fields{"type": appName})) logger.Hooks.Add(hook) return func(c *gin.Context) { // other handler can change c.Path so: path := c.Request.URL.Path start := time.Now() blw := &bodyLogWriter{body: bytes.NewBufferString(""), ResponseWriter: c.Writer} c.Writer = blw c.Next() stop := time.Since(start) latency := int(math.Ceil(float64(stop.Nanoseconds()) / 1000000.0)) statusCode := c.Writer.Status() bodyResp := blw.body.String() clientIP := c.ClientIP() dataLength := c.Writer.Size() if dataLength < 0 { dataLength = 0 } entry := logger.WithFields(logrus.Fields{ "statusCode": statusCode, "latency": latency, // time to process "clientIP": clientIP, "method": c.Request.Method, "path": path, "dataLength": dataLength, "resp": bodyResp, }) // logger.SetFormatter(&logrus.JSONFormatter{ // FieldMap: logrus.FieldMap{ // logrus.FieldKeyTime: "@timestamp", // logrus.FieldKeyMsg: "message", // }, // }) // if len(c.Errors) > 0 { entry.Error(c.Errors.ByType(gin.ErrorTypePrivate).String()) } else { message := fmt.Sprintf("%s - [%s] \"%s %s\" %d (%dms)", clientIP, time.Now().Format(timeFormat), c.Request.Method, path, statusCode, latency) if statusCode >= http.StatusInternalServerError { entry.Error(message) } else if statusCode >= http.StatusBadRequest { entry.Warn(message) } else { entry.Info(message) } } } }
package orm import ( "fmt" "github.com/muidea/magicOrm/builder" "github.com/muidea/magicOrm/model" "github.com/muidea/magicOrm/util" ) type resultItems []interface{} func (s *impl) querySingle(vModel model.Model, filter model.Filter, deepLevel int) (ret model.Model, err error) { var queryValue resultItems func() { builder := builder.NewBuilder(vModel, s.modelProvider) sqlStr, sqlErr := builder.BuildQuery(filter) if sqlErr != nil { err = sqlErr return } err = s.executor.Query(sqlStr) if err != nil { return } defer s.executor.Finish() if !s.executor.Next() { return } items, itemErr := s.getInitializeValue(vModel, builder) if itemErr != nil { err = itemErr return } err = s.executor.GetField(items...) if err != nil { return } queryValue = items }() if err != nil || len(queryValue) == 0 { return } modelVal, modelErr := s.assignSingleModel(vModel, queryValue, deepLevel) if modelErr != nil { err = modelErr return } ret = modelVal return } func (s *impl) assignSingleModel(modelVal model.Model, queryVal resultItems, deepLevel int) (ret model.Model, err error) { offset := 0 for _, field := range modelVal.GetFields() { fType := field.GetType() fValue := field.GetValue() if !fType.IsBasic() { if !fValue.IsNil() { itemVal, itemErr := s.queryRelation(modelVal, field, deepLevel+1) if itemErr != nil { err = itemErr return } err = field.SetValue(itemVal) if err != nil { return } } //offset++ continue } if !fValue.IsNil() { fVal, fErr := s.modelProvider.DecodeValue(s.stripSlashes(fType, queryVal[offset]), fType) if fErr != nil { err = fErr return } err = field.SetValue(fVal) if err != nil { return } } offset++ } ret = modelVal return } func (s *impl) queryRelationSingle(id int, vModel model.Model, deepLevel int) (ret model.Model, err error) { relationModel := vModel.Copy() relationVal, relationErr := s.modelProvider.GetEntityValue(id) if relationErr != nil { err = fmt.Errorf("GetEntityValue failed, err:%s", relationErr) return } pkField := relationModel.GetPrimaryField() pkField.SetValue(relationVal) relationFilter, relationErr := s.getFieldFilter(pkField) if relationErr != nil { err = fmt.Errorf("GetEntityValue failed, err:%s", relationErr) return } queryVal, queryErr := s.querySingle(relationModel, relationFilter, deepLevel) if queryErr != nil { err = queryErr return } ret = queryVal return } func (s *impl) queryRelationSlice(ids []int, vModel model.Model, deepLevel int) (ret []model.Model, err error) { sliceVal := []model.Model{} for _, item := range ids { relationModel := vModel.Copy() relationVal, relationErr := s.modelProvider.GetEntityValue(item) if relationErr != nil { err = fmt.Errorf("GetEntityValue failed, err:%s", relationErr) return } pkField := relationModel.GetPrimaryField() pkField.SetValue(relationVal) relationFilter, relationErr := s.getFieldFilter(pkField) if relationErr != nil { err = fmt.Errorf("GetEntityValue failed, err:%s", relationErr) return } queryVal, queryErr := s.querySingle(relationModel, relationFilter, deepLevel) if queryErr != nil { err = queryErr return } if queryVal != nil { sliceVal = append(sliceVal, queryVal) } } ret = sliceVal return } func (s *impl) queryRelation(modelInfo model.Model, fieldInfo model.Field, deepLevel int) (ret model.Value, err error) { fieldType := fieldInfo.GetType() if deepLevel > 3 { ret, err = fieldType.Interface() return } fieldModel, fieldErr := s.modelProvider.GetTypeModel(fieldType) if fieldErr != nil { err = fieldErr return } builder := builder.NewBuilder(modelInfo, s.modelProvider) relationSQL, relationErr := builder.BuildQueryRelation(fieldInfo.GetName(), fieldModel) if relationErr != nil { err = relationErr return } var values []int func() { err = s.executor.Query(relationSQL) if err != nil { return } defer s.executor.Finish() for s.executor.Next() { v := 0 err = s.executor.GetField(&v) if err != nil { return } values = append(values, v) } }() if err != nil || len(values) == 0 { ret, err = fieldType.Interface() return } fieldValue, _ := fieldType.Interface() if util.IsStructType(fieldType.GetValue()) { queryVal, queryErr := s.queryRelationSingle(values[0], fieldModel, deepLevel+1) if queryErr != nil { err = queryErr return } if queryVal != nil { modelVal, modelErr := s.modelProvider.GetEntityValue(queryVal.Interface(true)) if modelErr != nil { err = modelErr return } fieldValue.Set(modelVal.Get()) } ret = fieldValue return } if util.IsSliceType(fieldType.GetValue()) { queryVal, queryErr := s.queryRelationSlice(values, fieldModel, deepLevel+1) if queryErr != nil { err = queryErr return } for _, v := range queryVal { modelVal, modelErr := s.modelProvider.GetEntityValue(v.Interface(true)) if modelErr != nil { err = modelErr return } fieldValue, fieldErr = s.modelProvider.AppendSliceValue(fieldValue, modelVal) if fieldErr != nil { err = fieldErr return } } } ret = fieldValue return } // Query query func (s *impl) Query(entityModel model.Model) (ret model.Model, err error) { entityFilter, entityErr := s.getModelFilter(entityModel) if entityErr != nil { err = entityErr return } queryVal, queryErr := s.querySingle(entityModel, entityFilter, 0) if queryErr != nil { err = queryErr return } if queryVal != nil { ret = queryVal return } err = fmt.Errorf("not exist model,name:%s,pkgPath:%s", entityModel.GetName(), entityModel.GetPkgPath()) return }
package routing import ( "github.com/gin-gonic/gin" "github.com/kamalraimi/recruiter-api/controllers" "github.com/kamalraimi/recruiter-api/middlewares" ) func Routes(route *gin.Engine) { //route.Use(middlewares.CORSMiddleware()) // CORS route.POST("/recruiter-api/login", middlewares.GinJwtMiddlewareHandler().LoginHandler) route.GET("/recruiter-api/menu/:id", controllers.GetMenusByUser) roleRoutes := route.Group("/recruiter-api/roles") { roleRoutes.GET("/", middlewares.GinJwtMiddlewareHandler().MiddlewareFunc(), controllers.GetRoles) roleRoutes.GET("/:id", middlewares.GinJwtMiddlewareHandler().MiddlewareFunc(), controllers.GetRole) roleRoutes.POST("/", middlewares.GinJwtMiddlewareHandler().MiddlewareFunc(), controllers.PostRole) roleRoutes.PUT("/:id", middlewares.GinJwtMiddlewareHandler().MiddlewareFunc(), controllers.PutRole) roleRoutes.DELETE("/:id", middlewares.GinJwtMiddlewareHandler().MiddlewareFunc(), controllers.DeleteRole) } userRoutes := route.Group("/recruiter-api/users") { //userRoutes.GET("/", middlewares.AuthMiddleware(), controllers.GetUsers) userRoutes.GET("/", middlewares.GinJwtMiddlewareHandler().MiddlewareFunc(), controllers.GetUsers) userRoutes.GET("/:id", middlewares.GinJwtMiddlewareHandler().MiddlewareFunc(), controllers.GetUser) userRoutes.POST("/", middlewares.GinJwtMiddlewareHandler().MiddlewareFunc(), controllers.PostUser) userRoutes.PUT("/:id", middlewares.GinJwtMiddlewareHandler().MiddlewareFunc(), controllers.PutUser) userRoutes.DELETE("/:id", middlewares.GinJwtMiddlewareHandler().MiddlewareFunc(), controllers.DeleteUser) } menuRoutes := route.Group("/recruiter-api/menus") { menuRoutes.GET("/", middlewares.GinJwtMiddlewareHandler().MiddlewareFunc(), controllers.GetMenus) menuRoutes.GET("/:id", middlewares.GinJwtMiddlewareHandler().MiddlewareFunc(), controllers.GetMenu) menuRoutes.POST("/", middlewares.GinJwtMiddlewareHandler().MiddlewareFunc(), controllers.PostMenu) menuRoutes.PUT("/:id", middlewares.GinJwtMiddlewareHandler().MiddlewareFunc(), controllers.PutMenu) menuRoutes.DELETE("/:id", middlewares.GinJwtMiddlewareHandler().MiddlewareFunc(), controllers.DeleteMenu) } customerRoutes := route.Group("/recruiter-api/customers") { customerRoutes.GET("/", middlewares.GinJwtMiddlewareHandler().MiddlewareFunc(), controllers.GetCustomers) customerRoutes.GET("/:id", middlewares.GinJwtMiddlewareHandler().MiddlewareFunc(), controllers.GetCustomer) customerRoutes.POST("/", middlewares.GinJwtMiddlewareHandler().MiddlewareFunc(), controllers.PostCustomer) customerRoutes.PUT("/:id", middlewares.GinJwtMiddlewareHandler().MiddlewareFunc(), controllers.PutCustomer) customerRoutes.DELETE("/:id", middlewares.GinJwtMiddlewareHandler().MiddlewareFunc(), controllers.DeleteCustomer) } collaboraterRoutes := route.Group("/recruiter-api/collaboraters") { collaboraterRoutes.GET("/", middlewares.GinJwtMiddlewareHandler().MiddlewareFunc(), controllers.GetCollaboraters) collaboraterRoutes.GET("/:id", middlewares.GinJwtMiddlewareHandler().MiddlewareFunc(), controllers.GetCollaborater) collaboraterRoutes.POST("/", middlewares.GinJwtMiddlewareHandler().MiddlewareFunc(), controllers.PostCollaborater) collaboraterRoutes.PUT("/:id", middlewares.GinJwtMiddlewareHandler().MiddlewareFunc(), controllers.PutCollaborater) collaboraterRoutes.DELETE("/:id", middlewares.GinJwtMiddlewareHandler().MiddlewareFunc(), controllers.DeleteCollaborater) } positionRoutes := route.Group("/recruiter-api/positions") { positionRoutes.GET("/", middlewares.GinJwtMiddlewareHandler().MiddlewareFunc(), controllers.GetPositions) positionRoutes.GET("/:id", middlewares.GinJwtMiddlewareHandler().MiddlewareFunc(), controllers.GetPosition) positionRoutes.POST("/", middlewares.GinJwtMiddlewareHandler().MiddlewareFunc(), controllers.PostPosition) positionRoutes.PUT("/:id", middlewares.GinJwtMiddlewareHandler().MiddlewareFunc(), controllers.PutPosition) positionRoutes.DELETE("/:id", middlewares.GinJwtMiddlewareHandler().MiddlewareFunc(), controllers.DeletePosition) } applicationRoutes := route.Group("/recruiter-api/applications") { applicationRoutes.GET("/", middlewares.GinJwtMiddlewareHandler().MiddlewareFunc(), controllers.GetApplications) applicationRoutes.GET("/:id", middlewares.GinJwtMiddlewareHandler().MiddlewareFunc(), controllers.GetApplication) applicationRoutes.POST("/", middlewares.GinJwtMiddlewareHandler().MiddlewareFunc(), controllers.PostApplication) applicationRoutes.PUT("/:id", middlewares.GinJwtMiddlewareHandler().MiddlewareFunc(), controllers.PutApplication) applicationRoutes.DELETE("/:id", middlewares.GinJwtMiddlewareHandler().MiddlewareFunc(), controllers.DeleteApplication) } relocationRoutes := route.Group("/recruiter-api/relocations") { relocationRoutes.GET("/", middlewares.GinJwtMiddlewareHandler().MiddlewareFunc(), controllers.GetRelocations) relocationRoutes.GET("/:id", middlewares.GinJwtMiddlewareHandler().MiddlewareFunc(), controllers.GetRelocation) relocationRoutes.POST("/", middlewares.GinJwtMiddlewareHandler().MiddlewareFunc(), controllers.PostRelocation) relocationRoutes.PUT("/:id", middlewares.GinJwtMiddlewareHandler().MiddlewareFunc(), controllers.PutRelocation) relocationRoutes.DELETE("/:id", middlewares.GinJwtMiddlewareHandler().MiddlewareFunc(), controllers.DeleteRelocation) } immigrationRoutes := route.Group("/recruiter-api/immigrations") { immigrationRoutes.GET("/", middlewares.GinJwtMiddlewareHandler().MiddlewareFunc(), controllers.GetImmigrations) immigrationRoutes.GET("/:id", middlewares.GinJwtMiddlewareHandler().MiddlewareFunc(), controllers.GetImmigration) immigrationRoutes.POST("/", middlewares.GinJwtMiddlewareHandler().MiddlewareFunc(), controllers.PostImmigration) immigrationRoutes.PUT("/:id", middlewares.GinJwtMiddlewareHandler().MiddlewareFunc(), controllers.PutImmigration) immigrationRoutes.DELETE("/:id", middlewares.GinJwtMiddlewareHandler().MiddlewareFunc(), controllers.DeleteImmigration) } }
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. // package main import ( "github.com/mattermost/mattermost-cloud/model" "github.com/pkg/errors" "github.com/spf13/cobra" ) func newCmdSubscription() *cobra.Command { cmd := &cobra.Command{ Use: "subscription", Short: "Manipulate subscriptions managed by the provisioning server.", } setClusterFlags(cmd) cmd.AddCommand(newCmdSubscriptionCreate()) cmd.AddCommand(newCmdSubscriptionList()) cmd.AddCommand(newCmdSubscriptionGet()) cmd.AddCommand(newCmdSubscriptionDelete()) return cmd } func newCmdSubscriptionCreate() *cobra.Command { var flags subscriptionCreateFlags cmd := &cobra.Command{ Use: "create", Short: "Creates subscription.", RunE: func(cmd *cobra.Command, args []string) error { cmd.SilenceUsage = true client := model.NewClient(flags.serverAddress) var headers model.Headers for key, value := range flags.headers { valueInner := value headers = append(headers, model.WebhookHeader{ Key: key, Value: &valueInner, }) } for key, value := range flags.headersFromEnv { valueInner := value headers = append(headers, model.WebhookHeader{ Key: key, ValueFromEnv: &valueInner, }) } if err := headers.Validate(); err != nil { return errors.Wrap(err, "failed to validate webhook headers") } request := &model.CreateSubscriptionRequest{ Name: flags.name, URL: flags.url, OwnerID: flags.owner, EventType: model.EventType(flags.eventType), FailureThreshold: flags.failureThreshold, Headers: headers, } if flags.dryRun { return runDryRun(request) } backup, err := client.CreateSubscription(request) if err != nil { return errors.Wrap(err, "failed to create subscription") } return printJSON(backup) }, PreRun: func(cmd *cobra.Command, args []string) { flags.clusterFlags.addFlags(cmd) }, } flags.addFlags(cmd) return cmd } func newCmdSubscriptionList() *cobra.Command { var flags subscriptionListFlags cmd := &cobra.Command{ Use: "list", Short: "List subscriptions.", RunE: func(cmd *cobra.Command, args []string) error { cmd.SilenceUsage = true client := model.NewClient(flags.serverAddress) paging := getPaging(flags.pagingFlags) request := &model.ListSubscriptionsRequest{ Paging: paging, Owner: flags.owner, EventType: model.EventType(flags.eventType), } subscriptions, err := client.ListSubscriptions(request) if err != nil { return errors.Wrap(err, "failed to get backup") } if enabled, customCols := getTableOutputOption(flags.tableOptions); enabled { var keys []string var vals [][]string if len(customCols) > 0 { data := make([]interface{}, 0, len(subscriptions)) for _, elem := range subscriptions { data = append(data, elem) } keys, vals, err = prepareTableData(customCols, data) if err != nil { return errors.Wrap(err, "failed to prepare table output") } } else { keys, vals = defaultSubscriptionsTableData(subscriptions) } printTable(keys, vals) return nil } return printJSON(subscriptions) }, PreRun: func(cmd *cobra.Command, args []string) { flags.clusterFlags.addFlags(cmd) }, } flags.addFlags(cmd) return cmd } func defaultSubscriptionsTableData(subscriptions []*model.Subscription) ([]string, [][]string) { keys := []string{"ID", "EVENT TYPE", "OWNER", "LAST DELIVERY ATTEMPT", "LAST DELIVERY STATUS"} vals := make([][]string, 0, len(subscriptions)) for _, sub := range subscriptions { vals = append(vals, []string{ sub.ID, string(sub.EventType), sub.OwnerID, model.TimeFromMillis(sub.LastDeliveryAttemptAt).Format("2006-01-02 15:04:05 -0700 MST"), string(sub.LastDeliveryStatus), }) } return keys, vals } func newCmdSubscriptionGet() *cobra.Command { var flags subscriptionGetFlags cmd := &cobra.Command{ Use: "get", Short: "Get subscription.", RunE: func(cmd *cobra.Command, args []string) error { cmd.SilenceUsage = true client := model.NewClient(flags.serverAddress) subscription, err := client.GetSubscription(flags.subID) if err != nil { return errors.Wrap(err, "failed to get subscription") } return printJSON(subscription) }, PreRun: func(cmd *cobra.Command, args []string) { flags.clusterFlags.addFlags(cmd) }, } flags.addFlags(cmd) return cmd } func newCmdSubscriptionDelete() *cobra.Command { var flags subscriptionDeleteFlags cmd := &cobra.Command{ Use: "delete", Short: "Delete subscription.", RunE: func(command *cobra.Command, args []string) error { command.SilenceUsage = true client := model.NewClient(flags.serverAddress) if err := client.DeleteSubscription(flags.subID); err != nil { return errors.Wrap(err, "failed to delete subscription") } return nil }, PreRun: func(cmd *cobra.Command, args []string) { flags.clusterFlags.addFlags(cmd) }, } flags.addFlags(cmd) return cmd }
package main import ( "assignments-tichx/servers/gateway/models/users" "assignments-tichx/servers/gateway/sessions" "assignments-tichx/servers/handlers" "database/sql" "fmt" "log" "net/http" "net/http/httputil" "net/url" "os" "strings" "time" "github.com/go-redis/redis" ) //main is the main entry point for the server func main() { const headerCORS = "Access-Control-Allow-Origin" const corsAnyOrigin = "*" addr := os.Getenv("ADDR") if len(addr) == 0 { addr = ":443" } MESSAGESADDR := strings.Split(os.Getenv("MESSAGESADDR"), ",") PHOTOSADDR := strings.Split(os.Getenv("PHOTOSADDR"), ",") tlsKeyPath := os.Getenv("TLSKEY") tlsCertPath := os.Getenv("TLSCERT") SessionKey := os.Getenv("SESSIONKEY") if len(SessionKey) == 0 { fmt.Fprintf(os.Stderr, "Error: Session key is missing.") os.Exit(1) } RedisAddr := os.Getenv("REDISADDR") if len(RedisAddr) == 0 { fmt.Fprintf(os.Stderr, "Error: Redis address is missing") os.Exit(1) } DSN := os.Getenv("DSN") if len(DSN) == 0 { fmt.Fprintf(os.Stderr, "Error: DSN is missing") os.Exit(1) } if len(tlsKeyPath) == 0 || len(tlsCertPath) == 0 { fmt.Fprintf(os.Stderr, "Error: both certificates path are missing, please declare as env vars.") os.Exit(1) } redis := redis.NewClient(&redis.Options{ Addr: RedisAddr, }) pong, err := redis.Ping().Result() if err != nil { fmt.Fprintf(os.Stderr, "Redis Connection: %v, %v", pong, err) os.Exit(1) } redisStore := sessions.NewRedisStore(redis, time.Hour) db, err := sql.Open("mysql", DSN) if err != nil { os.Stderr.WriteString("Unable to open database: " + err.Error()) os.Exit(1) } userStore := users.NewMySQLStore(db) context := &handlers.HandlerContext{ Key: SessionKey, SessionStore: redisStore, UserStore: userStore, } summaryAddr := os.Getenv("SUMMARYADDR") summaryProxy := httputil.NewSingleHostReverseProxy(&url.URL{Scheme: "http", Host: summaryAddr}) s3Addr := os.Getenv("S3ADDR") if len(s3Addr) == 0 { s3Addr = "micro-s3:8080" } s3Proxy := httputil.NewSingleHostReverseProxy(&url.URL{Scheme: "http", Host: s3Addr}) messageCount := 0 messageDirector := func(r *http.Request) { auth := r.Header.Get("Authorization") if len(auth) == 0 { auth = r.URL.Query().Get("auth") } authUserSessID := sessions.SessionID(strings.TrimPrefix(auth, "Bearer ")) sessState := &handlers.SessionState{} err := context.SessionStore.Get(authUserSessID, sessState) if err == nil { r.Header.Set("X-User", fmt.Sprintf("{\"userID\":%d}", sessState.User.ID)) } else { r.Header.Del("X-User") } r.Host = MESSAGESADDR[messageCount] r.URL.Host = MESSAGESADDR[messageCount] r.URL.Scheme = "http" if len(MESSAGESADDR) > messageCount+1 { messageCount++ } } photoCount := 0 photoDirector := func(r *http.Request) { auth := r.Header.Get("Authorization") if len(auth) == 0 { auth = r.URL.Query().Get("auth") } authUserSessID := sessions.SessionID(strings.TrimPrefix(auth, "Bearer ")) sessState := &handlers.SessionState{} err := context.SessionStore.Get(authUserSessID, sessState) if err == nil { r.Header.Set("X-User", fmt.Sprintf("{\"userID\":%d}", sessState.User.ID)) } else { r.Header.Del("X-User") } r.Host = PHOTOSADDR[photoCount] r.URL.Host = PHOTOSADDR[photoCount] r.URL.Scheme = "http" if len(PHOTOSADDR) > photoCount+1 { photoCount++ } } messageProxy := &httputil.ReverseProxy{Director: messageDirector} photoProxy := &httputil.ReverseProxy{Director: photoDirector} mux := http.NewServeMux() mux.Handle("/v1/summary", summaryProxy) mux.Handle("/v1/photos/", photoProxy) mux.Handle("/v1/photos", photoProxy) mux.Handle("/v1/upload/", s3Proxy) mux.Handle("/v1/delete/", s3Proxy) mux.Handle("/v1/channels", messageProxy) mux.Handle("/v1/channels/", messageProxy) mux.Handle("/v1/tags", photoProxy) mux.Handle("/v1/tags/", photoProxy) mux.Handle("/v1/messages/", messageProxy) mux.HandleFunc("/v1/users", context.UsersHandler) mux.HandleFunc("/v1/users/", context.SpecificUserHandler) mux.HandleFunc("/v1/sessions", context.SessionsHandler) mux.HandleFunc("/v1/sessions/", context.SpecificSessionHandler) cors := &handlers.CORS{ Handle: mux, } log.Printf("Listening in on Port %s.", addr) log.Fatal(http.ListenAndServeTLS(addr, tlsCertPath, tlsKeyPath, cors)) }
package gostringutil import "testing" func assertReverse(t *testing.T, input, got, expected string) { if got != expected { t.Errorf("Reverse(%q) == %q, expected %q", input, got, expected) } } func TestSimpleReverse(t *testing.T) { input := "Hello Go!" expected := "!oG olleH" got := Reverse(input) assertReverse(t, input, got, expected) } func TestWithChineseCharacters(t *testing.T) { input := "Hello 世界" expected := "界世 olleH" got := Reverse(input) assertReverse(t, input, got, expected) } func TestWithASingleCharacter(t *testing.T) { input := "å" expected := "å" got := Reverse(input) assertReverse(t, input, got, expected) } func TestWithEmptyString(t *testing.T) { input := "" got := Reverse(input) assertReverse(t, input, got, input) } func TestReverseWithAllCases(t *testing.T) { cases := []struct { input, expected string } { {"Hello Go!", "!oG olleH"}, {"Hello 世界", "界世 olleH"}, {"å", "å"}, {"", ""}, } for _, c := range cases { got := Reverse(c.input) assertReverse(t, c.input, got, c.expected) } }
package main import ( "bufio" "fmt" "net" "os" "strings" ) func checkErr(err error) { if err != nil { panic(err) } } func main() { conn, err := net.Dial("tcp", "127.0.0.1:8088") checkErr(err) defer conn.Close() go msgSend(conn) //发送消息 buf := make([]byte, 1024) for { length, err := conn.Read(buf) //接收服务器信息 if err != nil { fmt.Println("you disconnected server") os.Exit(0) } if length > 0 { fmt.Printf("%s\n", buf[:length]) } } } //发送消息 func msgSend(conn net.Conn) { for { reader := bufio.NewReader(os.Stdin) data, _, _ := reader.ReadLine() //从标准输入读取信息 //data like : 127.0.0.1:15716#你好 input := string(data) if strings.ToLower(input) == "quit" { conn.Close() break } _, err := conn.Write(data) //发送给服务器 if err != nil { conn.Close() fmt.Printf("connection error: %s", err.Error()) break } } }
package controller import ( "bytes" "fmt" "reflect" "testing" "time" "k8s.io/api/core/v1" apierrors "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" core "k8s.io/client-go/testing" platform "kolihub.io/koli/pkg/apis/core/v1alpha1" "kolihub.io/koli/pkg/util" ) func newSecret(name, ns, token string, lastUpdate time.Time) *v1.Secret { return &v1.Secret{ ObjectMeta: metav1.ObjectMeta{ Namespace: ns, Name: name, Labels: map[string]string{platform.LabelSecretController: "true"}, Annotations: map[string]string{ platform.AnnotationSecretLastUpdated: lastUpdate.Format(time.RFC3339), }, }, Data: map[string][]byte{ "token.jwt": bytes.NewBufferString(token).Bytes(), }, Type: v1.SecretTypeOpaque, } } func newNamespace(name string) *v1.Namespace { return &v1.Namespace{ ObjectMeta: metav1.ObjectMeta{ Name: name, }, } } func TestSyncSecrets(t *testing.T) { var ( customer, org, jwtSecret = "coyote", "acme", "asecret" ns = fmt.Sprintf("dev-%s-%s", customer, org) expectedObj = newSecret(platform.SystemSecretName, ns, "", time.Now().UTC()) ) tokenStr, _ := util.GenerateNewJwtToken(jwtSecret, customer, org, platform.SystemTokenType, time.Now().UTC().Add(time.Hour*1)) expectedObj.Data["token.jwt"] = bytes.NewBufferString(tokenStr).Bytes() f := newFixture(t, []runtime.Object{newNamespace(ns)}, nil, nil) c, _ := f.newSecretController("asecret") f.client.AddReactor("patch", "secrets", func(action core.Action) (bool, runtime.Object, error) { return true, nil, apierrors.NewNotFound(action.GetResource().GroupResource(), action.GetResource().Resource) }) if err := c.syncHandler(ns); err != nil { t.Fatalf("got unexpected error: %v", err) } if len(f.client.Actions()) != 2 { t.Fatalf("unexpected length of action(s), found %d action(s)", len(f.client.Actions())) } for _, action := range f.client.Actions() { switch a := action.(type) { case core.PatchActionImpl: // no-op, simulated a not found resource case core.CreateActionImpl: s := a.GetObject().(*v1.Secret) if !reflect.DeepEqual(s, expectedObj) { t.Errorf("GOT: %#v, EXPECTED: %#v", s, expectedObj) } default: t.Errorf("unexpected type of action: %T, OBJ: %v", a, action) } } } func TestSyncSecretsWithValidLastUpdatedTime(t *testing.T) { var ( customer, org = "coyote", "acme" ns = fmt.Sprintf("dev-%s-%s", customer, org) expectedObj = newSecret(platform.SystemSecretName, ns, "", time.Now().UTC()) ) f := newFixture(t, []runtime.Object{newNamespace(ns)}, nil, []runtime.Object{expectedObj}) c, _ := f.newSecretController("") if err := c.syncHandler(ns); err != nil { t.Fatalf("got unexpected error: %v", err) } if len(f.client.Actions()) != 0 { t.Fatalf("unexpected length of action(s), got %d action(s), expected 0", len(f.client.Actions())) } } func TestSyncSecretsWithExpiredLastUpdatedTime(t *testing.T) { var ( customer, org = "coyote", "acme" ns = fmt.Sprintf("dev-%s-%s", customer, org) expectedObj = newSecret(platform.SystemSecretName, ns, "", time.Now().UTC().Add(time.Minute-time.Minute*25)) ) f := newFixture(t, []runtime.Object{newNamespace(ns)}, nil, []runtime.Object{expectedObj}) c, _ := f.newSecretController("") if err := c.syncHandler(ns); err != nil { t.Fatalf("got unexpected error: %v", err) } if len(f.client.Actions()) != 1 { t.Fatalf("unexpected length of action(s), got %d action(s), expected 1", len(f.client.Actions())) } } func TestSyncSecretsWithErrorOnPatch(t *testing.T) { var ( customer, org = "coyote", "acme" ns = fmt.Sprintf("dev-%s-%s", customer, org) expectedObj = newSecret(platform.SystemSecretName, ns, "", time.Now().UTC().Add(time.Minute-time.Minute*25)) expError = fmt.Errorf("failed updating secret [bad request happened]") ) f := newFixture(t, []runtime.Object{newNamespace(ns)}, nil, []runtime.Object{expectedObj}) c, _ := f.newSecretController("") f.client.AddReactor("patch", "secrets", func(action core.Action) (bool, runtime.Object, error) { return true, nil, apierrors.NewBadRequest("bad request happened") }) err := c.syncHandler(ns) if !reflect.DeepEqual(err, expError) { t.Errorf("GOT: %#v, EXPECTED: %#v", err, expError) } } func TestSyncSecretsWithErrorOnCreate(t *testing.T) { var ( customer, org = "coyote", "acme" ns = fmt.Sprintf("dev-%s-%s", customer, org) expectedObj = newSecret(platform.SystemSecretName, ns, "", time.Now().UTC().Add(time.Minute-time.Minute*25)) expError = fmt.Errorf("failed creating secret [bad request happened]") ) f := newFixture(t, []runtime.Object{newNamespace(ns)}, nil, []runtime.Object{expectedObj}) c, _ := f.newSecretController("") f.client.AddReactor("patch", "secrets", func(action core.Action) (bool, runtime.Object, error) { return true, nil, apierrors.NewNotFound(action.GetResource().GroupResource(), action.GetResource().Resource) }) f.client.PrependReactor("create", "secrets", func(action core.Action) (bool, runtime.Object, error) { return true, nil, apierrors.NewBadRequest("bad request happened") }) err := c.syncHandler(ns) if !reflect.DeepEqual(err, expError) { t.Errorf("GOT: %#v, EXPECTED: %#v", err, expError) } }
package simple_test //START, OMIT import ( "testing" //OMIT "github.com/stretchr/testify/assert" // HL ) func TestGetData(t *testing.T) { data := GetData() assert.Len(t, data, 1) // HL assert.Contains(t, data, 10) // HL } //STOP, OMIT //STARTCONTAINS10, OMIT func TestGetData_Contains10(t *testing.T) { data := GetData() var found bool for _, d := range data { // HL if d == 10 { found = true } } if !found { // HL t.Fail() } } //STOPCONTAINS10, OMIT // STARTMAP, OMIT func TestGetMap_FindTwoValues(t *testing.T) { m := GetMap() vA, ok := m["a"] // HL if !ok { t.Fail() } if vA != "valueOfA" { // HL t.Fail() } vB, ok := m["b"] // HL if !ok { t.Fail() } if vB != "valueOfB" { // HL t.Fail() } } // STOPMAP, OMIT // STARTMAP2, OMIT func TestGetMap_FindValue(t *testing.T) { m := GetMap() assert.Contains(t, m, "a") assert.Equal(t, "valueOfA", m["a"]) assert.Contains(t, m, "b") assert.Equal(t, "valueOfB", m["b"]) } // STOPMAP2, OMIT func GetData() []int { return []int{} } func GetMap() map[string]string { return make(map[string]string) }
// Copyright (C) 2016-Present Pivotal Software, Inc. All rights reserved. // This program and the accompanying materials are made available under the terms of the under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. package loggerfactory import ( "context" "fmt" "io" "log" "github.com/pborman/uuid" "github.com/pivotal-cf/on-demand-service-broker/brokercontext" ) const Flags = log.Ldate | log.Ltime | log.Lmicroseconds | log.LUTC type LoggerFactory struct { out io.Writer name string flag int } func New(out io.Writer, name string, flag int) *LoggerFactory { return &LoggerFactory{out: out, name: name, flag: flag} } func (l *LoggerFactory) NewWithContext(ctx context.Context) *log.Logger { if brokercontext.GetReqID(ctx) == "" { return l.New() } prefix := fmt.Sprintf("[%s] [%s] ", l.name, brokercontext.GetReqID(ctx)) return log.New(l.out, prefix, l.flag) } func (l *LoggerFactory) NewWithRequestID() *log.Logger { prefix := fmt.Sprintf("[%s] [%s] ", l.name, uuid.New()) return log.New(l.out, prefix, l.flag) } func (l *LoggerFactory) New() *log.Logger { prefix := fmt.Sprintf("[%s] ", l.name) return log.New(l.out, prefix, l.flag) }
// Copyright 2021 The Cockroach Authors. // // Use of this software is governed by the Business Source License // included in the file licenses/BSL.txt. // // As of the Change Date specified in that file, in accordance with // the Business Source License, use of this software will be governed // by the Apache License, Version 2.0, included in the file // licenses/APL.txt. package tracing import "github.com/opentracing/opentracing-go" // otSpan is a span for an external opentracing compatible tracer such as // lightstep, zipkin, jaeger, etc. type otSpan struct { // shadowTr is the shadowTracer this span was created from. We need // to hold on to it separately because shadowSpan.Tracer() returns // the wrapper tracer and we lose the ability to find out // what tracer it is. This is important when deriving children from // this span, as we want to avoid mixing different tracers, which // would otherwise be the result of cluster settings changed. shadowTr *shadowTracer shadowSpan opentracing.Span }
// Copyright (c) 2016-2019 Uber Technologies, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package netutil import ( "errors" "fmt" "net" "time" ) // _supportedInterfaces is an ordered list of ip interfaces from which // host ip is determined. var _supportedInterfaces = []string{"eth0", "ib0"} func min(a, b time.Duration) time.Duration { if a < b { return a } return b } // WithRetry executes f maxRetries times until it returns non-nil error, sleeping // for the given delay between retries with exponential backoff until maxDelay is // reached. func WithRetry(maxRetries uint, delay time.Duration, maxDelay time.Duration, f func() error) error { var retries uint for { err := f() if err == nil { return nil } if retries > maxRetries { return err } time.Sleep(min(delay*(1<<retries), maxDelay)) retries++ } } // GetIP looks up the ip of host. func GetIP(host string) (net.IP, error) { ips, err := net.LookupIP(host) if err != nil { return nil, fmt.Errorf("net: %s", err) } for _, ip := range ips { if ip == nil || ip.IsLoopback() { continue } return ip, nil } return nil, errors.New("no ips found") } // GetLocalIP returns the ip address of the local machine. func GetLocalIP() (string, error) { ifaces, err := net.Interfaces() if err != nil { return "", fmt.Errorf("interfaces: %s", err) } ips := map[string]string{} for _, i := range ifaces { addrs, err := i.Addrs() if err != nil { return "", fmt.Errorf("addrs: %s", err) } for _, addr := range addrs { var ip net.IP switch v := addr.(type) { case *net.IPNet: ip = v.IP case *net.IPAddr: ip = v.IP } if ip == nil || ip.IsLoopback() { continue } ip = ip.To4() if ip == nil { continue } ips[i.Name] = ip.String() break } } for _, i := range _supportedInterfaces { if ip, ok := ips[i]; ok { return ip, nil } } return "", errors.New("no ip found") }
// Copyright 2022 The ChromiumOS Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // This file implements implements interfaces and generic structs for power measurement package power import ( "time" "chromiumos/tast/remote/firmware/suspend" ) // Results is an interface for power measurement results type Results interface { GetMean(key string) (float32, bool) } // Interface is an interface that provides power measurements type Interface interface { Measure(targetState suspend.State, duration time.Duration) (Results, error) } // ResultsGeneric provides a simple wrapper around maps of measurements type ResultsGeneric struct { means map[string]float32 } // NewResultsGeneric creates a new ResultsGeneric func NewResultsGeneric() ResultsGeneric { return ResultsGeneric{ means: make(map[string]float32), } } // AddMeans copies means from an existing map func (m *ResultsGeneric) AddMeans(means map[string]float32) { for key, value := range means { m.means[key] = value } } // GetMean returns the mean for a measurement by a key func (m *ResultsGeneric) GetMean(key string) (float32, bool) { value, present := m.means[key] return value, present }
// The package implements a minimal set of Azure Event Hubs functionality. // // We could use https://github.com/Azure/azure-event-hubs-go but it's too huge // and also it has a number of dependencies that aren't desired in the project. package eventhub import ( "context" "crypto/rand" "crypto/tls" "encoding/hex" "errors" "fmt" "strings" "time" "github.com/Azure/go-amqp" ) // Credentials is an evenhub connection string representation. type Credentials struct { Endpoint string SharedAccessKeyName string SharedAccessKey string EntityPath string } // ParseConnectionString parses the given connection string into Credentials structure. func ParseConnectionString(cs string) (*Credentials, error) { var c Credentials for _, s := range strings.Split(cs, ";") { kv := strings.SplitN(s, "=", 2) if len(kv) != 2 { return nil, errors.New("malformed connection string") } switch kv[0] { case "Endpoint": if !strings.HasPrefix(kv[1], "sb://") { return nil, errors.New("only sb:// schema supported") } c.Endpoint = strings.TrimRight(kv[1][5:], "/") case "SharedAccessKeyName": c.SharedAccessKeyName = kv[1] case "SharedAccessKey": c.SharedAccessKey = kv[1] case "EntityPath": c.EntityPath = kv[1] } } return &c, nil } // Option is a client configuration option. type Option func(c *Client) // WithTLSConfig sets connection TLS configuration. func WithTLSConfig(tc *tls.Config) Option { return WithConnOption(amqp.ConnTLSConfig(tc)) } // WithSASLPlain configures connection username and password. func WithSASLPlain(username, password string) Option { return WithConnOption(amqp.ConnSASLPlain(username, password)) } // WithConnOption sets a low-level connection option. func WithConnOption(opt amqp.ConnOption) Option { return func(c *Client) { c.opts = append(c.opts, opt) } } // Dial connects to the named EventHub and returns a client instance. func Dial(host, name string, opts ...Option) (*Client, error) { c := &Client{name: name} for _, opt := range opts { opt(c) } var err error c.conn, err = amqp.Dial("amqps://"+host, c.opts...) if err != nil { return nil, err } return c, nil } // DialConnectionString dials an EventHub instance using the given connection string. func DialConnectionString(cs string, opts ...Option) (*Client, error) { creds, err := ParseConnectionString(cs) if err != nil { return nil, err } return Dial(creds.Endpoint, creds.EntityPath, append([]Option{ WithSASLPlain(creds.SharedAccessKeyName, creds.SharedAccessKey), }, opts...)...) } // Client is an EventHub client. type Client struct { name string conn *amqp.Client opts []amqp.ConnOption } // SubscribeOption is a Subscribe option. type SubscribeOption func(r *sub) // WithSubscribeConsumerGroup overrides default consumer group, default is `$Default`. func WithSubscribeConsumerGroup(name string) SubscribeOption { return func(s *sub) { s.group = name } } // WithSubscribeSince requests events that occurred after the given time. func WithSubscribeSince(t time.Time) SubscribeOption { return WithSubscribeLinkOption(amqp.LinkSelectorFilter( fmt.Sprintf("amqp.annotation.x-opt-enqueuedtimeutc > '%d'", t.UnixNano()/int64(time.Millisecond)), )) } // WithSubscribeLinkOption is a low-level subscription configuration option. func WithSubscribeLinkOption(opt amqp.LinkOption) SubscribeOption { return func(s *sub) { s.opts = append(s.opts, opt) } } type sub struct { group string opts []amqp.LinkOption } // Event is an Event Hub event, simply wraps an AMQP message. type Event struct { *amqp.Message } // Subscribe subscribes to all hub's partitions and registers the given // handler and blocks until it encounters an error or the context is cancelled. // // It's client's responsibility to accept/reject/release events. func (c *Client) Subscribe( ctx context.Context, fn func(event *Event) error, opts ...SubscribeOption, ) error { var s sub for _, opt := range opts { opt(&s) } if s.group == "" { s.group = "$Default" } // initialize new session for each subscribe session sess, err := c.conn.NewSession() if err != nil { return err } defer sess.Close(context.Background()) ids, err := c.getPartitionIDs(ctx, sess) if err != nil { return err } // stop all goroutines at return ctx, cancel := context.WithCancel(ctx) defer cancel() msgc := make(chan *amqp.Message) errc := make(chan error) for _, id := range ids { addr := fmt.Sprintf("/%s/ConsumerGroups/%s/Partitions/%s", c.name, s.group, id) recv, err := sess.NewReceiver( append([]amqp.LinkOption{amqp.LinkSourceAddress(addr)}, s.opts...)..., ) if err != nil { return err } go func(recv *amqp.Receiver) { defer recv.Close(context.Background()) for { msg, err := recv.Receive(ctx) if err != nil { select { case errc <- err: case <-ctx.Done(): } return } select { case msgc <- msg: case <-ctx.Done(): } } }(recv) } for { select { case msg := <-msgc: if err := fn(&Event{msg}); err != nil { return err } case err := <-errc: return err case <-ctx.Done(): return ctx.Err() } } } // getPartitionIDs returns partition ids of the hub. func (c *Client) getPartitionIDs(ctx context.Context, sess *amqp.Session) ([]string, error) { replyTo := genID() recv, err := sess.NewReceiver( amqp.LinkSourceAddress("$management"), amqp.LinkTargetAddress(replyTo), ) if err != nil { return nil, err } defer recv.Close(context.Background()) send, err := sess.NewSender( amqp.LinkTargetAddress("$management"), amqp.LinkSourceAddress(replyTo), ) if err != nil { return nil, err } defer send.Close(context.Background()) mid := genID() if err := send.Send(ctx, &amqp.Message{ Properties: &amqp.MessageProperties{ MessageID: mid, ReplyTo: replyTo, }, ApplicationProperties: map[string]interface{}{ "operation": "READ", "name": c.name, "type": "com.microsoft:eventhub", }, }); err != nil { return nil, err } msg, err := recv.Receive(ctx) if err != nil { return nil, err } if err = CheckMessageResponse(msg); err != nil { return nil, err } if msg.Properties.CorrelationID != mid { return nil, errors.New("message-id mismatch") } if err := msg.Accept(); err != nil { return nil, err } val, ok := msg.Value.(map[string]interface{}) if !ok { return nil, errors.New("unable to typecast value") } ids, ok := val["partition_ids"].([]string) if !ok { return nil, errors.New("unable to typecast partition_ids") } return ids, nil } // Close closes underlying AMQP connection. func (c *Client) Close() error { return c.conn.Close() } // CheckMessageResponse checks for 200 response code otherwise returns an error. func CheckMessageResponse(msg *amqp.Message) error { rc, ok := msg.ApplicationProperties["status-code"].(int32) if !ok { return errors.New("unable to typecast status-code") } if rc == 200 { return nil } rd, _ := msg.ApplicationProperties["status-description"].(string) return fmt.Errorf("code = %d, description = %q", rc, rd) } func genID() string { b := make([]byte, 16) if _, err := rand.Read(b); err != nil { panic(err) } return hex.EncodeToString(b) }
package main import ( "flag" "fmt" "github.com/KarmaPenny/pdfparser/pdf" "os" ) // print help info func usage() { fmt.Fprintln(os.Stderr, "PDF Parser - decodes a pdf file") fmt.Fprintf(os.Stderr, "https://github.com/KarmaPenny/pdfparser\n\n") fmt.Fprintf(os.Stderr, "usage: pdfparser [options] file\n\n") fmt.Fprintln(os.Stderr, "options:") flag.PrintDefaults() } func main() { // cmd args pdf.Verbose = flag.Bool("v", false, "display verbose messages") flag.Usage = usage flag.Parse() if flag.NArg() == 0 { usage() os.Exit(1) } // open the pdf parser, err := pdf.Open(flag.Arg(0)) if err != nil { fmt.Fprintln(os.Stderr, err) os.Exit(1) } defer parser.Close() // check if pdf is encrypted if parser.IsEncrypted() { fmt.Fprintln(os.Stderr, "Encrypted") os.Exit(1) } // print all objects in xref for number := range parser.Xref { // read object object, err := parser.ReadObject(number) if err != nil { fmt.Fprintln(os.Stderr, err) continue } // print object object.Fprint(os.Stdout) } }
package releaser import ( "fmt" "github.com/aevea/release-notary/internal/github" "github.com/aevea/release-notary/internal/gitlab" "github.com/aevea/release-notary/internal/release" ) // Service describes the basic usage needed from a service such as Github type Service interface { LatestRelease() (*release.Release, error) Publish(*release.Release) error } // Releaser holds all functionality related to releasing. type Releaser struct { service Service } // Options are used to initialize releaser type Options struct { Provider Provider Token string Owner string Repo string // used for setting gitlab api url APIURL string // used by gitlab TagName string // used by Gitlab ProjectID int } // CreateReleaser initializes an instance of Releaser func CreateReleaser(options Options) (*Releaser, error) { if options.Provider == "github" { githubService := github.CreateGithubService(options.Token, options.Owner, options.Repo) return &Releaser{service: githubService}, nil } if options.Provider == "gitlab" { gitlabService, err := gitlab.CreateGitlabService(options.ProjectID, options.APIURL, options.TagName, options.Token) return &Releaser{service: gitlabService}, err } return nil, fmt.Errorf("provider %v not found", options.Provider) }
package arrays import "testing" func TestArrayIntOne(t *testing.T) { var v []int if err := Unmarshal([]byte("{1}"), &v); err != nil { t.Fatalf("Unexpected error, %v", err) } if expected := 1; len(v) != expected { t.Errorf("Expected array to have length %d, got %d", expected, len(v)) } if expected := 1; v[0] != expected { t.Errorf("Expected array[0] to be %d, got %d", expected, v[0]) } } func TestArrayIntTwo(t *testing.T) { var v []int if err := Unmarshal([]byte("{-1,2}"), &v); err != nil { t.Fatalf("Unexpected error, %v", err) } if expected := 2; len(v) != expected { t.Errorf("Expected array to have length %d, got %d", expected, len(v)) } if expected := -1; v[0] != expected { t.Errorf("Expected array[0] to be %d, got %d", expected, v[0]) } if expected := 2; v[1] != expected { t.Errorf("Expected array[1] to be %d, got %d", expected, v[1]) } } func TestArrayIntTwoWhitespace(t *testing.T) { var v []int if err := Unmarshal([]byte("{1, 2}"), &v); err != nil { t.Fatalf("Unexpected error, %v", err) } if expected := 2; len(v) != expected { t.Errorf("Expected array to have length %d, got %d", expected, len(v)) } if expected := 1; v[0] != expected { t.Errorf("Expected array[0] to be %d, got %d", expected, v[0]) } if expected := 2; v[1] != expected { t.Errorf("Expected array[1] to be %d, got %d", expected, v[1]) } } func TestArrayIntMultidimension(t *testing.T) { var v [][]int if err := Unmarshal([]byte("{{1}, {2}}"), &v); err != nil { t.Fatalf("Unexpected error, %v", err) } if expected := 2; len(v) != expected { t.Errorf("Expected array to have length %d, got %d", expected, len(v)) } if expected := 1; len(v[0]) != expected { t.Errorf("Expected array[0] to have length %d, got %d", expected, len(v[0])) } if expected := 1; v[0][0] != expected { t.Errorf("Expected array[0][0] to be %d, got %d", expected, v[0][0]) } if expected := 1; len(v[1]) != expected { t.Errorf("Expected array[1] to have length %d, got %d", expected, len(v[0])) } if expected := 2; v[1][0] != expected { t.Errorf("Expected array[1][0] to be %d, got %d", expected, v[1][0]) } } func TestArrayStringOne(t *testing.T) { var v []string if err := Unmarshal([]byte("{\"hello\"}"), &v); err != nil { t.Fatalf("Unexpected error, %v", err) } if expected := 1; len(v) != expected { t.Errorf("Expected array to have length %d, got %d", expected, len(v)) } if expected := "hello"; v[0] != expected { t.Errorf("Expected array[0] to be '%s', got '%s'", expected, v[0]) } } func TestArrayUnquotedString(t *testing.T) { var v []string if err := Unmarshal([]byte("{hello}"), &v); err != nil { t.Fatalf("Unexpected error, %v", err) } if expected := 1; len(v) != expected { t.Errorf("Expected array to have length %d, got %d", expected, len(v)) } if expected := "hello"; v[0] != expected { t.Errorf("Expected array[0] to be '%s', got '%s'", expected, v[0]) } } func TestArrayMixedQuotingStrings(t *testing.T) { var v []string if err := Unmarshal([]byte("{hello,\"there world\"}"), &v); err != nil { t.Fatalf("Unexpected error, %v", err) } if expected := 2; len(v) != expected { t.Errorf("Expected array to have length %d, got %d", expected, len(v)) } if expected := "hello"; v[0] != expected { t.Errorf("Expected array[0] to be '%s', got '%s'", expected, v[0]) } if expected := "there world"; v[1] != expected { t.Errorf("Expected array[1] to be '%s', got '%s'", expected, v[1]) } } func TestArrayNumbersAsStrings(t *testing.T) { var v []string if err := Unmarshal([]byte("{123}"), &v); err != nil { t.Fatalf("Unexpected error, %v", err) } if expected := 1; len(v) != expected { t.Errorf("Expected array to have length %d, got %d", expected, len(v)) } if expected := "123"; v[0] != expected { t.Errorf("Expected array[0] to be '%s', got '%s'", expected, v[0]) } } func TestArrayNullsAsStrings(t *testing.T) { var v []string if err := Unmarshal([]byte("{\"NULL\", NotANull, NULL}"), &v); err != nil { t.Fatalf("Unexpected error, %v", err) } if expected := 3; len(v) != expected { t.Errorf("Expected array to have length %d, got %d", expected, len(v)) } if expected := "NULL"; v[0] != expected { t.Errorf("Expected array[0] to be '%s', got '%s'", expected, v[0]) } if expected := "NotANull"; v[1] != expected { t.Errorf("Expected array[1] to be '%s', got '%s'", expected, v[1]) } if expected := ""; v[2] != expected { t.Errorf("Expected array[2] to be '%s', got '%s'", expected, v[2]) } } func TestArrayStringTwo(t *testing.T) { var v []string if err := Unmarshal([]byte("{\"hello\",\"world\"}"), &v); err != nil { t.Fatalf("Unexpected error, %v", err) } if expected := 2; len(v) != expected { t.Errorf("Expected array to have length %d, got %d", expected, len(v)) } if expected := "hello"; v[0] != expected { t.Errorf("Expected array[0] to be '%s', got '%s'", expected, v[0]) } if expected := "world"; v[1] != expected { t.Errorf("Expected array[1] to be '%s', got '%s'", expected, v[1]) } } func TestArrayStringTwoWhitespace(t *testing.T) { var v []string if err := Unmarshal([]byte("{\"hello\", \"world\"}"), &v); err != nil { t.Fatalf("Unexpected error, %v", err) } if expected := 2; len(v) != expected { t.Errorf("Expected array to have length %d, got %d", expected, len(v)) } if expected := "hello"; v[0] != expected { t.Errorf("Expected array[0] to be '%s', got '%s'", expected, v[0]) } if expected := "world"; v[1] != expected { t.Errorf("Expected array[1] to be '%s', got '%s'", expected, v[1]) } } func TestArrayStringMultidimension(t *testing.T) { var v [][]string if err := Unmarshal([]byte("{{\"hello\"}, {\"world\"}}"), &v); err != nil { t.Fatalf("Unexpected error, %v", err) } if expected := 2; len(v) != expected { t.Errorf("Expected array to have length %d, got %d", expected, len(v)) } if expected := 1; len(v[0]) != expected { t.Errorf("Expected array[0] to have length %d, got %d", expected, len(v[0])) } if expected := "hello"; v[0][0] != expected { t.Errorf("Expected array[0][0] to be '%s', got '%s'", expected, v[0][0]) } if expected := 1; len(v[1]) != expected { t.Errorf("Expected array[1] to have length %d, got %d", expected, len(v[0])) } if expected := "world"; v[1][0] != expected { t.Errorf("Expected array[1][0] to be '%s', got '%s'", expected, v[1][0]) } } func TestArrayFloat(t *testing.T) { var v []float64 if err := Unmarshal([]byte("{-1.2, 0.2, 4.54356}"), &v); err != nil { t.Fatalf("Unexpected error, %v", err) } if expected := 3; len(v) != expected { t.Errorf("Expected array to have length %d, got %d", expected, len(v)) } if expected := -1.2; v[0] != expected { t.Errorf("Expected array[0] to be %f, got %f", expected, v[0]) } if expected := 0.2; v[1] != expected { t.Errorf("Expected array[1] to be %f, got %f", expected, v[1]) } if expected := 4.54356; v[2] != expected { t.Errorf("Expected array[2] to be %f, got %f", expected, v[2]) } } func TestArrayBool(t *testing.T) { var v []bool if err := Unmarshal([]byte("{t, f}"), &v); err != nil { t.Fatalf("Unexpected error, %v", err) } if expected := 2; len(v) != expected { t.Errorf("Expected array to have length %d, got %d", expected, len(v)) } if expected := true; v[0] != expected { t.Errorf("Expected array[0] to be %t, got %t", expected, v[0]) } if expected := false; v[1] != expected { t.Errorf("Expected array[1] to be %t, got %t", expected, v[1]) } } func TestArrayBoolWithNulls(t *testing.T) { var v []bool if err := Unmarshal([]byte("{t, NULL}"), &v); err != nil { t.Fatalf("Unexpected error, %v", err) } if expected := 2; len(v) != expected { t.Errorf("Expected array to have length %d, got %d", expected, len(v)) } if expected := true; v[0] != expected { t.Errorf("Expected array[0] to be %t, got %t", expected, v[0]) } if expected := false; v[1] != expected { t.Errorf("Expected array[1] to be %t, got %t", expected, v[1]) } } func TestArrayBoolAsStrings(t *testing.T) { var v []string if err := Unmarshal([]byte("{t, f}"), &v); err != nil { t.Fatalf("Unexpected error, %v", err) } if expected := 2; len(v) != expected { t.Errorf("Expected array to have length %d, got %d", expected, len(v)) } if expected := "t"; v[0] != expected { t.Errorf("Expected array[0] to be %t, got %t", expected, v[0]) } if expected := "f"; v[1] != expected { t.Errorf("Expected array[1] to be %t, got %t", expected, v[1]) } } func TestArrayBoolWithNullsIntoInterfaceArray(t *testing.T) { var v []interface{} if err := Unmarshal([]byte("{t, NULL}"), &v); err != nil { t.Fatalf("Unexpected error, %v", err) } if expected := 2; len(v) != expected { t.Errorf("Expected array to have length %d, got %d", expected, len(v)) } if expected := true; v[0] != expected { t.Errorf("Expected array[0] to be %t, got %t", expected, v[0]) } if v[1] != nil { t.Errorf("Expected array[1] to be nil, got %t", v[1]) } } func TestArrayEscapedSlash(t *testing.T) { var v []string if err := Unmarshal([]byte("{\"hello\\\\world\"}"), &v); err != nil { t.Fatalf("Unexpected error, %v", err) } if expected := 1; len(v) != expected { t.Errorf("Expected array to have length %d, got %d", expected, len(v)) } if expected := "hello\\world"; v[0] != expected { t.Errorf("Expected array[0] to be '%s', got '%s'", expected, v[0]) } } func TestArrayEscapedOpenArray(t *testing.T) { var v []string if err := Unmarshal([]byte("{\"hello\\{world\"}"), &v); err != nil { t.Fatalf("Unexpected error, %v", err) } if expected := 1; len(v) != expected { t.Errorf("Expected array to have length %d, got %d", expected, len(v)) } if expected := "hello{world"; v[0] != expected { t.Errorf("Expected array[0] to be '%s', got '%s'", expected, v[0]) } } func TestArrayEscapedCloseArray(t *testing.T) { var v []string if err := Unmarshal([]byte("{\"hello\\}world\"}"), &v); err != nil { t.Fatalf("Unexpected error, %v", err) } if expected := 1; len(v) != expected { t.Errorf("Expected array to have length %d, got %d", expected, len(v)) } if expected := "hello}world"; v[0] != expected { t.Errorf("Expected array[0] to be '%s', got '%s'", expected, v[0]) } } type testObj struct { id int } func TestArrayDecodeIntoObject(t *testing.T) { v := testObj{} if err := Unmarshal([]byte("{\"hello\\}world\"}"), &v); err == nil { t.Fatal("Expected error, didn't get one") } v2 := &testObj{} if err := Unmarshal([]byte("{\"hello\\}world\"}"), &v2); err == nil { t.Fatal("Expected error, didn't get one") } } func TestArrayDecodeIntoPreallocatedSlice(t *testing.T) { v := make([]int, 0, 10) if err := Unmarshal([]byte("{1}"), &v); err != nil { t.Fatalf("Unexpected error, %v", err) } if expected := 1; len(v) != expected { t.Errorf("Expected array to have length %d, got %d", expected, len(v)) } if expected := 1; v[0] != expected { t.Errorf("Expected array[0] to be %d, got %d", expected, v[0]) } } func TestArrayDecodeIntoArray(t *testing.T) { v := [10]int{} if err := Unmarshal([]byte("{1}"), &v); err != nil { t.Fatalf("Unexpected error, %v", err) } if expected := 10; len(v) != expected { t.Errorf("Expected array to have length %d, got %d", expected, len(v)) } if expected := 1; v[0] != expected { t.Errorf("Expected array[0] to be %d, got %d", expected, v[0]) } }
package ravendb import ( "net/http" "reflect" "strconv" ) var ( _ IOperation = &GetCompareExchangeValuesOperation{} ) type GetCompareExchangeValuesOperation struct { Command *GetCompareExchangeValuesCommand _clazz reflect.Type _keys []string _startWith string _start int // -1 for unset _pageSize int } func NewGetCompareExchangeValuesOperationWithKeys(clazz reflect.Type, keys []string) (*GetCompareExchangeValuesOperation, error) { if len(keys) == 0 { return nil, newIllegalArgumentError("Keys cannot be null or empty array") } return &GetCompareExchangeValuesOperation{ _keys: keys, _clazz: clazz, _start: -1, _pageSize: 0, _startWith: "", }, nil } func NewGetCompareExchangeValuesOperation(clazz reflect.Type, startWith string, start int, pageSize int) (*GetCompareExchangeValuesOperation, error) { return &GetCompareExchangeValuesOperation{ _clazz: clazz, _start: start, _pageSize: pageSize, _startWith: startWith, }, nil } var _ RavenCommand = &GetCompareExchangeValuesCommand{} func (o *GetCompareExchangeValuesOperation) GetCommand(store *DocumentStore, conventions *DocumentConventions, cache *httpCache) (RavenCommand, error) { var err error o.Command, err = NewGetCompareExchangeValuesCommand(o, conventions) return o.Command, err } type GetCompareExchangeValuesCommand struct { RavenCommandBase _operation *GetCompareExchangeValuesOperation _conventions *DocumentConventions Result map[string]*CompareExchangeValue } func NewGetCompareExchangeValuesCommand(operation *GetCompareExchangeValuesOperation, conventions *DocumentConventions) (*GetCompareExchangeValuesCommand, error) { cmd := &GetCompareExchangeValuesCommand{ RavenCommandBase: NewRavenCommandBase(), _operation: operation, _conventions: conventions, } cmd.IsReadRequest = true return cmd, nil } func (c *GetCompareExchangeValuesCommand) CreateRequest(node *ServerNode) (*http.Request, error) { url := node.URL + "/databases/" + node.Database + "/cmpxchg?" if c._operation._keys != nil { for _, key := range c._operation._keys { url += "&key=" + urlUtilsEscapeDataString(key) } } else { if !stringIsEmpty(c._operation._startWith) { url += "&startsWith=" + urlUtilsEscapeDataString(c._operation._startWith) } if c._operation._start >= 0 { url += "&start=" + strconv.Itoa(c._operation._start) } if c._operation._pageSize > 0 { url += "&pageSize=" + strconv.Itoa(c._operation._pageSize) } } return newHttpGet(url) } func (c *GetCompareExchangeValuesCommand) SetResponse(response []byte, fromCache bool) error { res, err := compareExchangeValueResultParserGetValues(c._operation._clazz, response, c._conventions) if err != nil { return err } c.Result = res return nil }
package repository import ( "model" "github.com/jmoiron/sqlx" "github.com/hashicorp/go-multierror" ) type ICategoryRepository interface { FindAllCategories() (*[]model.Category, error) FindCategoryById(id int) (*model.Category, error) CreateCategory(category model.Category) (int, error) UpdateCategory(category model.Category) error DeleteCategory(id int) error } type CategoryRepository struct { db *sqlx.DB } func NewCategoryRepository(db *sqlx.DB) *CategoryRepository { return &CategoryRepository{db: db} } func (cr *CategoryRepository) FindAllCategories() (*[]model.Category, error) { query := `SELECT id as ID, name as Name, parent_id as ParentId FROM category` categories := []model.Category{} err := cr.db.Select(&categories, query) if err != nil { return nil, err } else { return &categories, nil } } func (cr *CategoryRepository) FindCategoryById(id int) (*model.Category, error) { query := `SELECT id as ID, name as Name, parent_id as ParentId FROM category WHERE id=$1` categories := []model.Category{} err := cr.db.Select(&categories, query, id) if err != nil { return nil, err } else if len(categories) == 0 { return &model.Category{}, nil } else { return &categories[0], nil } } func (cr *CategoryRepository) CreateCategory(category model.Category) (int, error) { var id int query := `INSERT INTO category (name, parent_id) VALUES ($1, $2) RETURNING id` tx, err := cr.db.Beginx() if err != nil { return -1, err } err = tx.QueryRow(query, category.Name, category.ParentId).Scan(&id) if err != nil { multierror.Append(err, tx.Rollback()) return -1, err } err = tx.Commit() if err != nil { return -1, err } return int(id), err } func (cr *CategoryRepository) UpdateCategory(category model.Category) error { query := `UPDATE category SET name=$1, parent_id=$2 WHERE id=$3` tx, err := cr.db.Beginx() if err != nil { return err } _, err = tx.Exec(query, category.Name, category.ParentId, category.ID) if err != nil { multierror.Append(err, tx.Rollback()) return err } tx.Commit() return nil } func (cr *CategoryRepository) DeleteCategory(id int) error { query := `DELETE FROM category WHERE id=$1` tx, err := cr.db.Beginx() if err != nil { return err } _, err = tx.Exec(query, id) if err != nil { multierror.Append(err, tx.Rollback()) return err } tx.Commit() return nil }
package pokergame //冒泡排序法对整数排序 func BubbleSortIntMin2Max(ints []int){ length := len(ints) for i :=0;i<length;i++{ for j := i;j < length;j++{ if ints[i] > ints[j]{ ints[i],ints[j] = ints[j],ints[i] } } } }
/* Copyright 2017 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package main import ( "errors" "flag" "fmt" "github.com/golang/glog" "github.com/kubernetes-incubator/external-storage/lib/controller" crdv1 "github.com/rootfs/snapshot/pkg/apis/crd/v1" crdclient "github.com/rootfs/snapshot/pkg/client" "github.com/rootfs/snapshot/pkg/cloudprovider" "github.com/rootfs/snapshot/pkg/cloudprovider/providers/aws" "github.com/rootfs/snapshot/pkg/cloudprovider/providers/gce" "github.com/rootfs/snapshot/pkg/cloudprovider/providers/openstack" "github.com/rootfs/snapshot/pkg/volume" "github.com/rootfs/snapshot/pkg/volume/aws_ebs" "github.com/rootfs/snapshot/pkg/volume/cinder" "github.com/rootfs/snapshot/pkg/volume/gce_pd" "github.com/rootfs/snapshot/pkg/volume/hostpath" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/util/uuid" "k8s.io/apimachinery/pkg/util/wait" "k8s.io/client-go/kubernetes" "k8s.io/client-go/pkg/api/v1" _ "k8s.io/client-go/plugin/pkg/client/auth/gcp" "k8s.io/client-go/rest" "k8s.io/client-go/tools/clientcmd" ) const ( provisionerName = "volumesnapshot.external-storage.k8s.io/snapshot-promoter" provisionerIDAnn = "snapshotProvisionerIdentity" ) type snapshotProvisioner struct { // Kubernetes Client. client kubernetes.Interface // CRD client crdclient *rest.RESTClient // Identity of this snapshotProvisioner, generated. Used to identify "this" // provisioner's PVs. identity string } func newSnapshotProvisioner(client kubernetes.Interface, crdclient *rest.RESTClient, id string) controller.Provisioner { return &snapshotProvisioner{ client: client, crdclient: crdclient, identity: id, } } var _ controller.Provisioner = &snapshotProvisioner{} func (p *snapshotProvisioner) getPVFromVolumeSnapshotDataSpec(snapshotDataSpec *crdv1.VolumeSnapshotDataSpec) (*v1.PersistentVolume, error) { if snapshotDataSpec.PersistentVolumeRef == nil { return nil, fmt.Errorf("VolumeSnapshotDataSpec is not bound to any PV") } pvName := snapshotDataSpec.PersistentVolumeRef.Name if pvName == "" { return nil, fmt.Errorf("The PV name is not specified in snapshotdata %#v", *snapshotDataSpec) } pv, err := p.client.CoreV1().PersistentVolumes().Get(pvName, metav1.GetOptions{}) if err != nil { return nil, fmt.Errorf("Failed to retrieve PV %s from the API server: %q", pvName, err) } return pv, nil } func (p *snapshotProvisioner) snapshotRestore(snapshotName string, snapshotData crdv1.VolumeSnapshotData, options controller.VolumeOptions) (*v1.PersistentVolumeSource, map[string]string, error) { // validate the PV supports snapshot and restore spec := &snapshotData.Spec pv, err := p.getPVFromVolumeSnapshotDataSpec(spec) if err != nil { return nil, nil, err } volumeType := crdv1.GetSupportedVolumeFromPVSpec(&pv.Spec) if len(volumeType) == 0 { return nil, nil, fmt.Errorf("unsupported volume type found in PV %#v", *spec) } plugin, ok := volumePlugins[volumeType] if !ok { return nil, nil, fmt.Errorf("%s is not supported volume for %#v", volumeType, *spec) } // restore snapshot pvSrc, labels, err := plugin.SnapshotRestore(&snapshotData, options.PVC, options.PVName, options.Parameters) if err != nil && pv == nil { glog.Warningf("failed to snapshot %#v, err: %v", *spec, err) } else { glog.Infof("snapshot %#v to snap %#v", *spec, *pvSrc) return pvSrc, labels, nil } return nil, nil, nil } // Provision creates a storage asset and returns a PV object representing it. func (p *snapshotProvisioner) Provision(options controller.VolumeOptions) (*v1.PersistentVolume, error) { if options.PVC.Spec.Selector != nil { return nil, fmt.Errorf("claim Selector is not supported") } snapshotName, ok := options.PVC.Annotations[crdclient.SnapshotPVCAnnotation] if !ok { return nil, fmt.Errorf("snapshot annotation not found on PV") } var snapshot crdv1.VolumeSnapshot err := p.crdclient.Get(). Resource(crdv1.VolumeSnapshotResourcePlural). Namespace(options.PVC.Namespace). Name(snapshotName). Do().Into(&snapshot) if err != nil { return nil, fmt.Errorf("failed to retrieve VolumeSnapshot %s: %v", snapshotName, err) } // FIXME: should also check if any VolumeSnapshotData points to this VolumeSnapshot if len(snapshot.Spec.SnapshotDataName) == 0 { return nil, fmt.Errorf("VolumeSnapshot %s is not bound to any VolumeSnapshotData", snapshotName, err) } var snapshotData crdv1.VolumeSnapshotData err = p.crdclient.Get(). Resource(crdv1.VolumeSnapshotDataResourcePlural). Namespace(v1.NamespaceDefault). Name(snapshot.Spec.SnapshotDataName). Do().Into(&snapshotData) if err != nil { return nil, fmt.Errorf("failed to retrieve VolumeSnapshotData %s: %v", snapshot.Spec.SnapshotDataName, err) } glog.V(3).Infof("restore from VolumeSnapshotData %s", snapshot.Spec.SnapshotDataName) pvSrc, labels, err := p.snapshotRestore(snapshot.Spec.SnapshotDataName, snapshotData, options) if err != nil || pvSrc == nil { return nil, fmt.Errorf("failed to create a PV from snapshot %s: %v", snapshotName, err) } pv := &v1.PersistentVolume{ ObjectMeta: metav1.ObjectMeta{ Name: options.PVName, Annotations: map[string]string{ provisionerIDAnn: p.identity, }, }, Spec: v1.PersistentVolumeSpec{ PersistentVolumeReclaimPolicy: options.PersistentVolumeReclaimPolicy, AccessModes: options.PVC.Spec.AccessModes, Capacity: v1.ResourceList{ v1.ResourceName(v1.ResourceStorage): options.PVC.Spec.Resources.Requests[v1.ResourceName(v1.ResourceStorage)], }, PersistentVolumeSource: *pvSrc, }, } if len(labels) != 0 { if pv.Labels == nil { pv.Labels = make(map[string]string) } for k, v := range labels { pv.Labels[k] = v } } glog.Infof("successfully created Snapshot share %#v", pv) return pv, nil } // Delete removes the storage asset that was created by Provision represented // by the given PV. func (p *snapshotProvisioner) Delete(volume *v1.PersistentVolume) error { ann, ok := volume.Annotations[provisionerIDAnn] if !ok { return errors.New("identity annotation not found on PV") } if ann != p.identity { return &controller.IgnoredError{"identity annotation on PV does not match ours"} } volumeType := crdv1.GetSupportedVolumeFromPVSpec(&volume.Spec) if len(volumeType) == 0 { return fmt.Errorf("unsupported volume type found in PV %#v", *volume) } plugin, ok := volumePlugins[volumeType] if !ok { return fmt.Errorf("%s is not supported volume for %#v", volumeType, *volume) } // delete PV return plugin.VolumeDelete(volume) } var ( master = flag.String("master", "", "Master URL") kubeconfig = flag.String("kubeconfig", "", "Absolute path to the kubeconfig") id = flag.String("id", "", "Unique provisioner identity") cloudProvider = flag.String("cloudprovider", "", "aws|gce|openstack") cloudConfigFile = flag.String("cloudconfig", "", "Path to a Cloud config. Only required if cloudprovider is set.") volumePlugins = make(map[string]volume.VolumePlugin) ) func main() { flag.Parse() flag.Set("logtostderr", "true") var config *rest.Config var err error if *master != "" || *kubeconfig != "" { config, err = clientcmd.BuildConfigFromFlags(*master, *kubeconfig) } else { config, err = rest.InClusterConfig() } prId := string(uuid.NewUUID()) if *id != "" { prId = *id } if err != nil { glog.Fatalf("Failed to create config: %v", err) } clientset, err := kubernetes.NewForConfig(config) if err != nil { glog.Fatalf("Failed to create client: %v", err) } // The controller needs to know what the server version is because out-of-tree // provisioners aren't officially supported until 1.5 serverVersion, err := clientset.Discovery().ServerVersion() if err != nil { glog.Fatalf("Error getting server version: %v", err) } // build volume plugins map buildVolumePlugins() // make a crd client to list VolumeSnapshot snapshotClient, _, err := crdclient.NewClient(config) if err != nil || snapshotClient == nil { glog.Fatalf("Failed to make CRD client: %v", err) } // Create the provisioner: it implements the Provisioner interface expected by // the controller snapshotProvisioner := newSnapshotProvisioner(clientset, snapshotClient, prId) // Start the provision controller which will dynamically provision snapshot // PVs pc := controller.NewProvisionController( clientset, provisionerName, snapshotProvisioner, serverVersion.GitVersion, ) glog.Infof("starting PV provisioner %s", provisionerName) pc.Run(wait.NeverStop) } func buildVolumePlugins() { if len(*cloudProvider) != 0 { cloud, err := cloudprovider.InitCloudProvider(*cloudProvider, *cloudConfigFile) if err == nil && cloud != nil { if *cloudProvider == aws.ProviderName { awsPlugin := aws_ebs.RegisterPlugin() awsPlugin.Init(cloud) volumePlugins[aws_ebs.GetPluginName()] = awsPlugin } if *cloudProvider == gce.ProviderName { gcePlugin := gce_pd.RegisterPlugin() gcePlugin.Init(cloud) volumePlugins[gce_pd.GetPluginName()] = gcePlugin glog.Info("Register cloudprovider %s", gce_pd.GetPluginName()) } if *cloudProvider == openstack.ProviderName { cinderPlugin := cinder.RegisterPlugin() cinderPlugin.Init(cloud) volumePlugins[cinder.GetPluginName()] = cinderPlugin glog.Info("Register cloudprovider %s", cinder.GetPluginName()) } } else { glog.Warningf("failed to initialize aws cloudprovider: %v, supported cloudproviders are %#v", err, cloudprovider.CloudProviders()) } } volumePlugins[hostpath.GetPluginName()] = hostpath.RegisterPlugin() }
package keepassrpc import ( "crypto/sha256" "fmt" ) // MsgKey represents various stages of the challenge/response protocol type MsgKey struct { SecurityLevel int `json:"securityLevel"` SC string `json:"sc,omitempty"` // Server challenge CC string `json:"cc,omitempty"` // Client challenge SR string `json:"sr,omitempty"` // Server response CR string `json:"cr,omitempty"` // Client response Username string `json:"username,omitempty"` } // KeyContext is key-negotiation-specific context that we track per-client type KeyContext struct { sc string cc string } // DispatchKey handles challenge/response setup negotiation with the server func DispatchKey(c *Client, key *MsgKey) error { if key.SC != "" { return ServerChallenge(c, key) } if key.SR != "" { return ServerResponse(c, key) } return fmt.Errorf("neither server challenge nor response provided") } // EstablishKeySession establishes a session with the KeePassRPC service using // a previously-negotiated key. func EstablishKeySession(c *Client) error { challenge, err := GenKey(32) if err != nil { return err } c.KeyCtx = &KeyContext{cc: challenge.Text(16)} defer func() { c.KeyCtx = nil }() msg := &Message{ Protocol: "setup", ClientID: ClientID, ClientName: ClientName, ClientDesc: ClientDesc, Version: ProtocolVersion(), Key: &MsgKey{ Username: c.Username, SecurityLevel: 2, }, } if err := WriteMessage(c.WS, msg); err != nil { return err } return c.DispatchResponse() } // ServerChallenge responds to a challenge issued by the server, and issues // a challenge of our own. func ServerChallenge(c *Client, key *MsgKey) error { c.KeyCtx.sc = key.SC h := sha256.New() fmt.Fprintf(h, "1%x%s%s", c.SessionKey, c.KeyCtx.sc, c.KeyCtx.cc) response := fmt.Sprintf("%x", h.Sum(nil)) resp := &Message{ Protocol: "setup", Version: ProtocolVersion(), Key: &MsgKey{ CC: c.KeyCtx.cc, CR: response, SecurityLevel: 2, }, } if err := WriteMessage(c.WS, resp); err != nil { return err } return c.DispatchResponse() } // ServerResponse validates the server's response to our challenge. func ServerResponse(c *Client, key *MsgKey) error { h := sha256.New() fmt.Fprintf(h, "0%x%s%s", c.SessionKey, c.KeyCtx.sc, c.KeyCtx.cc) sr := fmt.Sprintf("%x", h.Sum(nil)) c.KeyCtx = nil if sr != key.SR { return fmt.Errorf("Server key does not match") } return nil }
package service import ( "bytes" "context" "crypto/rand" "crypto/rsa" "crypto/x509" "encoding/base64" "encoding/pem" log "github.com/sirupsen/logrus" "way-jasy-cron/common/email" "way-jasy-cron/user/ecode" "way-jasy-cron/user/internal/model/ent" ) func (svc *Service) Register(ctx context.Context, user *ent.User) error{ if err := svc.DecodePwd(ctx, user); err != nil { log.Error("decode pwd err:", err) return err } if err := svc.ent.Register(ctx, user); err != nil { log.Error("method: Register#service. Register err:", err) return err } log.Info("Register success!") return nil } func (svc *Service) GetPublicKey(ctx context.Context, username string) (string, error) { key, err := svc.ent.GetPublicKey(ctx, username) if err != nil { log.Error("GetPublicKey err:",err) } return key, err } func (svc *Service) GenerateRSA(ctx context.Context, username string) (string, error) { u, err := svc.ent.QueryUser(ctx, username) if err != nil { log.Error("method: Register#service. QueryUser err:", err) return "", err } if u != nil { return "", ecode.UserExist } pubKey, priKey, err := GenRsaKey(1024) if err != nil { log.Error("GenRsaKey err:", err) return "", err } if err := svc.ent.SaveRsaKey(ctx, username, pubKey, priKey); err != nil { log.Error("SaveRsaKey err:",err) return "", err } return pubKey, err } func GenRsaKey(bits int) (publicKeyStr, privateKeyStr string, err error) { // 生成私钥文件 privateKey, err := rsa.GenerateKey(rand.Reader, bits) if err != nil { return } derStream := x509.MarshalPKCS1PrivateKey(privateKey) block := &pem.Block{ Type: "RSA PRIVATE KEY", Bytes: derStream, } bufferPrivate := new(bytes.Buffer) err = pem.Encode(bufferPrivate, block) if err != nil { return } privateKeyStr = bufferPrivate.String() // 生成公钥文件 publicKey := &privateKey.PublicKey derPkix, err := x509.MarshalPKIXPublicKey(publicKey) if err != nil { return } block = &pem.Block{ Type: "PUBLIC KEY", Bytes: derPkix, } bufferPublic := new(bytes.Buffer) err = pem.Encode(bufferPublic, block) if err != nil { return } publicKeyStr = bufferPublic.String() return } func (svc *Service) DecodePwd(ctx context.Context, user *ent.User) error{ u, err := svc.ent.QueryUser(ctx, user.Username) if err != nil { log.Error("method: DecodePwd#user, QueryUser err:",err) return err } block, _ := pem.Decode([]byte(u.PrivateKey)) privateKey, err := x509.ParsePKCS1PrivateKey(block.Bytes) if err != nil { return err } decodeString, _ := base64.StdEncoding.DecodeString(user.Password) plainText, err := rsa.DecryptPKCS1v15(rand.Reader,privateKey,decodeString) user.Password = string(plainText) return err } func (svc *Service) GetUserInfo(ctx context.Context, name string) (user *ent.User, err error) { user, err = svc.ent.QueryUserInfo(ctx, name) if err != nil { log.Error("QueryUser err:%+v. method: GetUserInfo#user", err) return nil, err } return } func (svc *Service) TestShow(ctx context.Context, rec string) (err error) { m := email.NewEmail(svc.mail.Host, svc.mail.Username, svc.mail.Password, svc.mail.Port) m.WithInfo("测试邮件", "毕设演示",[]string{rec}) if err = m.Send(); err != nil { log.Error("send mail notice err:", err) } return err }
package proxy import ( "bytes" "fmt" "io/ioutil" "net/http" "os" "time" myhttp "github.com/Everbridge/go-proxy/http" "github.com/Everbridge/go-proxy/mapping" "github.com/Everbridge/go-proxy/statistics" ) // StartProxyServer starts the proxy server func StartProxyServer() error { certFile := os.Getenv("GO_PROXY_CERT_FILE") keyFile := os.Getenv("GO_PROXY_CERT_KEY_FILE") proxyServer := http.NewServeMux() proxyServer.HandleFunc("/", requestHandler) if certFile == "" || keyFile == "" { fmt.Printf("Starting proxy at: %s\n", GetURL()) return http.ListenAndServe(fmt.Sprintf(":%d", port), proxyServer) } isSSL = true fmt.Printf("Starting proxy at: %s\n", GetURL()) return http.ListenAndServeTLS(fmt.Sprintf(":%d", port), certFile, keyFile, proxyServer) } func requestHandler(w http.ResponseWriter, req *http.Request) { proxiedRequest, mappings, mappingError := initializeHandling(req, w) if mappingError != nil { finalizeWithError(req, w, proxiedRequest, mappingError) return } match := matchMapping(req, mappings) if match == nil { finalizeWithNotFound(req, w, proxiedRequest, "") return } response, handlingError := handleRequest(req, w, match) if handlingError == os.ErrNotExist { finalizeWithNotFound(req, w, proxiedRequest, response.executedURL) return } if handlingError != nil { finalizeWithError(req, w, proxiedRequest, handlingError) return } for name, value := range match.Mapping.Inject.Headers { proxiedRequest.RequestData.Headers[name] = []string{value} } proxiedRequest.ResponseData = statistics.HTTPData{ Body: response.body, Headers: response.headers, } proxiedRequest.ExecutedURL = response.executedURL proxiedRequest.ResponseCode = response.responseCode proxiedRequest.EndTime = getTime() statistics.AddProxiedRequest(proxiedRequest) } func finalizeWithError(req *http.Request, w http.ResponseWriter, proxiedRequest statistics.ProxiedRequest, err error) { myhttp.InternalError(req, w, err) proxiedRequest.EndTime = getTime() proxiedRequest.Error = err.Error() proxiedRequest.ResponseCode = http.StatusInternalServerError statistics.AddProxiedRequest(proxiedRequest) return } func finalizeWithNotFound(req *http.Request, w http.ResponseWriter, proxiedRequest statistics.ProxiedRequest, executedURL string) { myhttp.NotFound(req, w, executedURL) proxiedRequest.EndTime = getTime() proxiedRequest.ExecutedURL = executedURL proxiedRequest.ResponseCode = http.StatusNotFound statistics.AddProxiedRequest(proxiedRequest) } func getData(req *http.Request) (statistics.HTTPData, error) { result := statistics.HTTPData{} result.Headers = req.Header defer req.Body.Close() body, bodyErr := ioutil.ReadAll(req.Body) if bodyErr != nil { return result, bodyErr } if len(body) != 0 { if myhttp.IsText(req.Header["Content-Type"]...) { result.Body = string(body) // Rewind the body req.Body = closeableByteBuffer{bytes.NewBuffer(body)} } else { result.Body = "Binary" } } return result, nil } func getTime() int64 { return time.Now().UnixNano() / int64(time.Millisecond) } func handleRequest(req *http.Request, w http.ResponseWriter, match *mapping.MatchResult) (*proxyResponse, error) { if match.Mapping.Proxy { return proxyRequest(req, w, match) } return serveStaticFile(req, w, match) } func initializeHandling(req *http.Request, w http.ResponseWriter) (statistics.ProxiedRequest, []mapping.DynamicMapping, error) { reqData, _ := getData(req) proxiedRequest := statistics.ProxiedRequest{ Method: req.Method, RequestedURL: req.URL.String(), RequestData: reqData, StartTime: getTime(), } mapping, mappingError := mapping.GetMappings() return proxiedRequest, mapping, mappingError }
// Copyright 2020 The Cockroach Authors. // // Use of this software is governed by the Business Source License // included in the file licenses/BSL.txt. // // As of the Change Date specified in that file, in accordance with // the Business Source License, use of this software will be governed // by the Apache License, Version 2.0, included in the file // licenses/APL.txt. package covering import ( "encoding/binary" "fmt" "math/rand" "testing" "github.com/cockroachdb/cockroach/pkg/util/timeutil" "github.com/stretchr/testify/require" ) func BenchmarkOverlapCoveringMerge(b *testing.B) { var benchmark []struct { name string inputs []Covering } rand.Seed(timeutil.Now().Unix()) for _, numLayers := range []int{ 1, // single backup 24, // hourly backups 24 * 7, // hourly backups for a week. } { // number of elements per each backup instance for _, elementsPerLayer := range []int{100, 1000, 10000} { var inputs []Covering for i := 0; i < numLayers; i++ { var payload int var c Covering step := 1 + rand.Intn(10) for j := 0; j < elementsPerLayer; j += step { start := make([]byte, 4) binary.LittleEndian.PutUint32(start, uint32(j)) end := make([]byte, 4) binary.LittleEndian.PutUint32(end, uint32(j+step)) c = append(c, Range{ Start: start, End: end, Payload: payload, }) payload++ } inputs = append(inputs, c) } benchmark = append(benchmark, struct { name string inputs []Covering }{name: fmt.Sprintf("layers=%d,elems=%d", numLayers, elementsPerLayer), inputs: inputs}) } } b.ResetTimer() for _, bench := range benchmark { inputs := bench.inputs b.Run(bench.name, func(b *testing.B) { for i := 0; i < b.N; i++ { require.NotEmpty(b, OverlapCoveringMerge(inputs)) } }) } }
// Copyright © 2020. All rights reserved. // Author: Ilya Yuryevich. // Contacts: qioalice@gmail.com, https://github.com/qioalice // License: https://opensource.org/licenses/MIT package ekasys import ( "os" ) var ( posixCachedUid = uint32(os.Getuid()) posixCachedGid = uint32(os.Getgid()) ) func PosixCachedUid() uint32 { return posixCachedUid } func PosixCachedGid() uint32 { return posixCachedGid }
// Copyright 2018 The Cockroach Authors. // // Use of this software is governed by the Business Source License // included in the file licenses/BSL.txt. // // As of the Change Date specified in that file, in accordance with // the Business Source License, use of this software will be governed // by the Apache License, Version 2.0, included in the file // licenses/APL.txt. package colexec import ( "context" "testing" "github.com/cockroachdb/cockroach/pkg/sql/colexec/colexectestutils" "github.com/cockroachdb/cockroach/pkg/sql/colexecop" "github.com/cockroachdb/cockroach/pkg/sql/execinfrapb" "github.com/cockroachdb/cockroach/pkg/sql/types" "github.com/cockroachdb/cockroach/pkg/util/leaktest" "github.com/cockroachdb/cockroach/pkg/util/log" ) var topKSortTestCases []sortTestCase func init() { topKSortTestCases = []sortTestCase{ { description: "k < input length", tuples: colexectestutils.Tuples{{1}, {2}, {3}, {4}, {5}, {6}, {7}}, expected: colexectestutils.Tuples{{1}, {2}, {3}}, typs: []*types.T{types.Int}, ordCols: []execinfrapb.Ordering_Column{{ColIdx: 0}}, k: 3, }, { description: "k > input length", tuples: colexectestutils.Tuples{{1}, {2}, {3}, {4}, {5}, {6}, {7}}, expected: colexectestutils.Tuples{{1}, {2}, {3}, {4}, {5}, {6}, {7}}, typs: []*types.T{types.Int}, ordCols: []execinfrapb.Ordering_Column{{ColIdx: 0}}, k: 10, }, { description: "nulls", tuples: colexectestutils.Tuples{{1}, {2}, {nil}, {3}, {4}, {5}, {6}, {7}, {nil}}, expected: colexectestutils.Tuples{{nil}, {nil}, {1}}, typs: []*types.T{types.Int}, ordCols: []execinfrapb.Ordering_Column{{ColIdx: 0}}, k: 3, }, { description: "descending", tuples: colexectestutils.Tuples{{0, 1}, {0, 2}, {0, 3}, {0, 4}, {0, 5}, {1, 5}}, expected: colexectestutils.Tuples{{0, 5}, {1, 5}, {0, 4}}, typs: []*types.T{types.Int, types.Int}, ordCols: []execinfrapb.Ordering_Column{ {ColIdx: 1, Direction: execinfrapb.Ordering_Column_DESC}, {ColIdx: 0, Direction: execinfrapb.Ordering_Column_ASC}, }, k: 3, }, } } func TestTopKSorter(t *testing.T) { defer leaktest.AfterTest(t)() defer log.Scope(t).Close(t) for _, tc := range topKSortTestCases { log.Infof(context.Background(), "%s", tc.description) colexectestutils.RunTests(t, testAllocator, []colexectestutils.Tuples{tc.tuples}, tc.expected, colexectestutils.OrderedVerifier, func(input []colexecop.Operator) (colexecop.Operator, error) { return NewTopKSorter(testAllocator, input[0], tc.typs, tc.ordCols, tc.k), nil }) } }
// Copyright 2020 cloudeng llc. All rights reserved. // Use of this source code is governed by the Apache-2.0 // license that can be found in the LICENSE file. package subcmd_test import ( "context" "flag" "fmt" "runtime" "strings" "testing" "cloudeng.io/cmdutil/subcmd" "cloudeng.io/errors" ) func ExampleCommandSet() { ctx := context.Background() type globalFlags struct { Verbosity int `subcmd:"v,0,debugging verbosity"` } var globalValues globalFlags type rangeFlags struct { From int `subcmd:"from,1,start value for a range"` To int `subcmd:"to,2,end value for a range "` } printRange := func(ctx context.Context, values interface{}, args []string) error { r := values.(*rangeFlags) fmt.Printf("%v: %v..%v\n", globalValues.Verbosity, r.From, r.To) return nil } fs := subcmd.MustRegisterFlagStruct(&rangeFlags{}, nil, nil) // Subcommands are added using the subcmd.WithSubcommands option. cmd := subcmd.NewCommand("ranger", fs, printRange, subcmd.WithoutArguments()) cmd.Document("print an integer range") cmdSet := subcmd.NewCommandSet(cmd) globals := subcmd.NewFlagSet() globals.MustRegisterFlagStruct(&globalValues, nil, nil) cmdSet.WithGlobalFlags(globals) // Use cmdSet.Dispatch to access os.Args. fmt.Printf("%s", cmdSet.Usage("example-command")) fmt.Printf("%s", cmdSet.Defaults("example-command")) cmdSet.DispatchWithArgs(ctx, "example-command", "ranger") cmdSet.DispatchWithArgs(ctx, "example-command", "-v=3", "ranger", "--from=10", "--to=100") // Output: // Usage of example-command // // ranger - print an integer range // Usage of example-command // // ranger - print an integer range // // global flags: [--v=0] // -v int // debugging verbosity // // 0: 1..2 // 3: 10..100 } type flagsA struct { A int `subcmd:"flag-a,,a: an int flag"` B int `subcmd:"flag-b,,b: an int flag"` } type flagsB struct { X string `subcmd:"flag-x,,x: a string flag"` Y string `subcmd:"flag-y,,y: a string flag"` } func TestCommandSet(t *testing.T) { ctx := context.Background() var err error assertNoError := func() { _, _, line, _ := runtime.Caller(1) if err != nil { t.Fatalf("line %v: %v", line, err) } } out := &strings.Builder{} runnerA := func(ctx context.Context, values interface{}, args []string) error { fl, ok := values.(*flagsA) if !ok { t.Fatalf("wrong type: %T", values) } fmt.Fprintf(out, "%v .. %v\n", fl.A, fl.B) return nil } runnerB := func(ctx context.Context, values interface{}, args []string) error { fl, ok := values.(*flagsB) if !ok { t.Fatalf("wrong type: %T", values) } fmt.Fprintf(out, "%v .. %v\n", fl.X, fl.Y) return nil } cmdAFlags, err := subcmd.RegisterFlagStruct(&flagsA{}, nil, nil) assertNoError() cmdA := subcmd.NewCommand("cmd-a", cmdAFlags, runnerA) cmdA.Document("subcmd a", "<args>...") cmdBFlags, err := subcmd.RegisterFlagStruct(&flagsB{}, nil, nil) assertNoError() cmdB := subcmd.NewCommand("cmd-b", cmdBFlags, runnerB) cmdB.Document("subcmd b", "") commands := subcmd.NewCommandSet(cmdA, cmdB) commands.Document("an explanation which will be line wrapped to something sensible and approaching 80 chars") err = commands.DispatchWithArgs(ctx, "test", "cmd-a", "--flag-a=1", "--flag-b=3") assertNoError() if got, want := out.String(), "1 .. 3\n"; got != want { t.Errorf("got %v, want %v", got, want) } if got, want := commands.Usage("binary"), `Usage of binary an explanation which will be line wrapped to something sensible and approaching 80 chars cmd-a - subcmd a cmd-b - subcmd b `; got != want { t.Errorf("got %v, want %v", got, want) } out.Reset() err = commands.DispatchWithArgs(ctx, "test", "cmd-b", "--flag-x=s1", "--flag-y=s3") assertNoError() if got, want := out.String(), "s1 .. s3\n"; got != want { t.Errorf("got %v, want %v", got, want) } errHelp := func() { if err != flag.ErrHelp { t.Errorf("expected flag.ErrHelp: got %v", err) } } help := &strings.Builder{} commands.SetOutput(help) err = commands.DispatchWithArgs(ctx, "test", "help", "cmd-a") errHelp() if got, want := help.String(), `Usage of command cmd-a: subcmd a cmd-a [--flag-a=0 --flag-b=0] <args>... -flag-a int a: an int flag -flag-b int b: an int flag `; got != want { t.Errorf("got %v, want %v", got, want) } } func TestCommandOptions(t *testing.T) { ctx := context.Background() numArgs := -1 runnerA := func(ctx context.Context, values interface{}, args []string) error { if _, ok := values.(*flagsA); !ok { t.Fatalf("wrong type: %T", values) } numArgs = len(args) return nil } cmdAFlags := subcmd.NewFlagSet() err := cmdAFlags.RegisterFlagStruct(&flagsA{}, nil, nil) if err != nil { t.Fatal(err) } cmdset := subcmd.NewCommandSet( subcmd.NewCommand("exactly-two", cmdAFlags, runnerA, subcmd.ExactlyNumArguments(2)), subcmd.NewCommand("none", cmdAFlags, runnerA, subcmd.WithoutArguments()), subcmd.NewCommand("at-most-one", cmdAFlags, runnerA, subcmd.OptionalSingleArgument()), subcmd.NewCommand("at-least-two", cmdAFlags, runnerA, subcmd.AtLeastNArguments(2)), ) expectedError := func(errmsg string) { _, _, line, _ := runtime.Caller(1) if err == nil || !strings.Contains(err.Error(), errmsg) { t.Errorf("line %v: missing or incorrect error: %v does not contain %v", line, err, errmsg) } } expectedNArgs := func(n int) { _, _, line, _ := runtime.Caller(1) if err != nil { t.Fatalf("line %v: unexpected error: %v", line, err) } if got, want := numArgs, n; got != want { t.Errorf("line %v: got %v, want %v", line, got, want) } numArgs = -1 } err = cmdset.DispatchWithArgs(ctx, "test", "exactly-two") expectedError("exactly-two: accepts exactly 2 arguments") err = cmdset.DispatchWithArgs(ctx, "test", "at-least-two") expectedError("at-least-two: accepts at least 2 arguments") err = cmdset.DispatchWithArgs(ctx, "test", "exactly-two", "a", "b") expectedNArgs(2) err = cmdset.DispatchWithArgs(ctx, "test", "none", "aaa") expectedError("none: does not accept any arguments") err = cmdset.DispatchWithArgs(ctx, "test", "none") expectedNArgs(0) err = cmdset.DispatchWithArgs(ctx, "test", "at-most-one", "a", "b") expectedError("at-most-one: accepts at most one argument") err = cmdset.DispatchWithArgs(ctx, "test", "at-most-one") expectedNArgs(0) err = cmdset.DispatchWithArgs(ctx, "test", "at-most-one", "a") expectedNArgs(1) err = cmdset.DispatchWithArgs(ctx, "test", "at-least-two", "a", "b", "c") expectedNArgs(3) } func TestMultiLevel(t *testing.T) { ctx := context.Background() type globalFlags struct { Verbosity int `subcmd:"v,0,debugging verbosity"` } var ( globalValues globalFlags cmd2, cmd11, cmd12, cmd31 bool l1Main, l2Main bool ) c2 := func(ctx context.Context, values interface{}, args []string) error { cmd2 = true return nil } c11 := func(ctx context.Context, values interface{}, args []string) error { cmd11 = true return nil } c12 := func(ctx context.Context, values interface{}, args []string) error { cmd12 = true return nil } c31 := func(ctx context.Context, values interface{}, args []string) error { cmd31 = true return nil } c1Flags := subcmd.NewFlagSet() c2Flags := subcmd.NewFlagSet() c3Flags := subcmd.NewFlagSet() c11Flags := subcmd.NewFlagSet() c12Flags := subcmd.NewFlagSet() c31Flags := subcmd.NewFlagSet() globals := subcmd.NewFlagSet() errs := errors.M{} errs.Append(c1Flags.RegisterFlagStruct(&flagsA{}, nil, nil)) errs.Append(c2Flags.RegisterFlagStruct(&flagsA{}, nil, nil)) errs.Append(c3Flags.RegisterFlagStruct(&flagsA{}, nil, nil)) errs.Append(c11Flags.RegisterFlagStruct(&flagsA{}, nil, nil)) errs.Append(c12Flags.RegisterFlagStruct(&flagsA{}, nil, nil)) errs.Append(c31Flags.RegisterFlagStruct(&flagsA{}, nil, nil)) errs.Append(globals.RegisterFlagStruct(&globalValues, nil, nil)) if err := errs.Err(); err != nil { t.Fatal(err) } c11Cmd := subcmd.NewCommand("c11", c11Flags, c11) c11Cmd.Document("c11") c12Cmd := subcmd.NewCommand("c12", c12Flags, c12) c12Cmd.Document("c12") l21 := subcmd.NewCommandSet(c11Cmd, c12Cmd) l21.WithMain(func(ctx context.Context, runner func() error) error { l2Main = true return runner() }) c31Cmd := subcmd.NewCommand("c31", c31Flags, c31) c31Cmd.Document("c31") l31 := subcmd.NewCommandSet(c31Cmd) c1Cmd := subcmd.NewCommandLevel("c1", l21) c1Cmd.Document("c1") c2Cmd := subcmd.NewCommand("c2", c2Flags, c2) c2Cmd.Document("c2") c3Cmd := subcmd.NewCommandLevel("c3", l31) c3Cmd.Document("c3") l1 := subcmd.NewCommandSet(c1Cmd, c2Cmd, c3Cmd) l1.WithGlobalFlags(globals) l1.WithMain(func(ctx context.Context, runner func() error) error { l1Main = true return runner() }) if got, want := l1.Defaults("test"), `Usage of test c1 - c1 c2 - c2 c3 - c3 global flags: [--v=0] -v int debugging verbosity `; got != want { t.Errorf("got %v, want %v", got, want) } var err error assert := func(vals ...bool) { _, _, line, _ := runtime.Caller(1) if err != nil { t.Fatalf("line %v: unexpected error: %v", line, err) } for i, b := range vals { if !b { t.Errorf("line %v: val %v: expected value to be true", line, i) } } } err = l1.DispatchWithArgs(ctx, "test", "c1", "c11") assert(l2Main, cmd11) assert(!l1Main, !cmd12, !cmd2, !cmd31) l2Main, l1Main = false, false err = l1.DispatchWithArgs(ctx, "test", "c1", "c12") assert(l2Main, cmd11, cmd12) assert(!l1Main, !cmd2, !cmd31) l2Main, l1Main = false, false err = l1.DispatchWithArgs(ctx, "test", "c2") assert(l1Main, cmd11, cmd12) assert(!l2Main, cmd2, !cmd31) l2Main, l1Main = false, false err = l1.DispatchWithArgs(ctx, "test", "c3", "c31") assert(l1Main, cmd11, cmd12, cmd31) assert(!l2Main, cmd2) err = l1.DispatchWithArgs(ctx, "test", "c1") if err == nil || !strings.Contains(err.Error(), "no command specified") { t.Errorf("expected a particular error: %v", err) } err = l1.DispatchWithArgs(ctx, "test", "c1", "cx") if err == nil || !strings.Contains(err.Error(), "cx is not one of the supported commands: c11, c12") { t.Errorf("expected a particular error: %v", err) } }
package main func typecast_expr() { var a int var b int b = int(a) b = (int)(a) type num int var c num c = num(a) c = (num)(a) }
package graphite import ( "io" "log" "net" "strings" "github.com/influxdb/influxdb" ) const ( udpBufferSize = 65536 ) // UDPServer processes Graphite data received via UDP. type UDPServer struct { writer SeriesWriter parser *Parser database string Logger *log.Logger } // NewUDPServer returns a new instance of a UDPServer func NewUDPServer(p *Parser, w SeriesWriter, db string) *UDPServer { u := UDPServer{ parser: p, writer: w, database: db, } return &u } // SetLogOutput sets writer for all Graphite log output. func (s *UDPServer) SetLogOutput(w io.Writer) { s.Logger = log.New(w, "[graphite] ", log.LstdFlags) } // ListenAndServer instructs the UDPServer to start processing Graphite data // on the given interface. iface must be in the form host:port. func (u *UDPServer) ListenAndServe(iface string) error { if iface == "" { // Make sure we have an address return ErrBindAddressRequired } addr, err := net.ResolveUDPAddr("udp", iface) if err != nil { return nil } conn, err := net.ListenUDP("udp", addr) if err != nil { return err } buf := make([]byte, udpBufferSize) go func() { for { n, _, err := conn.ReadFromUDP(buf) if err != nil { return } for _, line := range strings.Split(string(buf[:n]), "\n") { point, err := u.parser.Parse(line) if err != nil { continue } // Send the data to the writer. _, e := u.writer.WriteSeries(u.database, "", []influxdb.Point{point}) if e != nil { u.Logger.Printf("failed to write data point: %s\n", e) } } } }() return nil }
package git import ( "context" "encoding/json" "errors" "fmt" "github.com/fatih/color" "sync" "time" github "github.com/google/go-github/v29/github" ) const ( perPage = 100 parallelSize = 20 requestTimeout = time.Second * 10 ) type Readme struct { Owner string `json:"readme,omitempty"` Repo string `json:"repo,omitempty"` Content string `json:"content,omitempty"` Err error `json:"-"` } type Starred struct { Owner string `json:"owner,omitempty"` Repo string `json:"repo,omitempty"` FullName string `json:"full_name,omitempty"` Url string `json:"url,omitempty"` Description string `json:"description,omitempty"` Topics []string `json:"topics,omitempty"` WatchersCount int `json:"watchers_count,omitempty"` StargazersCount int `json:"stargazers_count,omitempty"` ForksCount int `json:"forks_count,omitempty"` StarredAt JsonTime `json:"starred_at,omitempty"` CreatedAt JsonTime `json:"created_at,omitempty"` UpdateAt JsonTime `json:"updated_at,omitempty"` PushedAt JsonTime `json:"pushed_at,omitempty"` Readme string `json:"readme,omitempty"` CachedAt JsonTime `json:"cached_at,omitempty"` Error error `json:"-"` } type User struct { Owner string `json:"owner,omitempty"` AvatarURL string `json:"avatar_url,omitempty"` Url string `json:"url,omitempty"` Bio string `json:"bio,omitempty"` CreatedAt JsonTime `json:"created_at,omitempty"` UpdatedAt JsonTime `json:"updated_at,omitempty"` Token string `json:"token"` CachedAt JsonTime `json:"cached_at"` } type JsonTime struct { time.Time } // MarshalJSON converts struct to json bytes. func (jt *JsonTime) MarshalJSON() ([]byte, error) { s := jt.Format(time.RFC3339) return json.Marshal(s) } // UnmarshalJSON converts bytes to struct. func (jt *JsonTime) UnmarshalJSON(bys []byte) error { var s string if err := json.Unmarshal(bys, &s); err != nil { return err } t, err := time.Parse(time.RFC3339, s) if err != nil { return err } jt.Time = t return nil } type wrapper struct { *github.Client token string } // User returns github user object. func (w *wrapper) User() (*User, error) { ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() user, _, err := w.Users.Get(ctx, "") switch { case err == nil: if user == nil { return nil, fmt.Errorf("[err] User %w", ErrNotFound) } return &User{ Owner: user.GetLogin(), AvatarURL: user.GetAvatarURL(), Url: user.GetHTMLURL(), Bio: user.GetBio(), CreatedAt: JsonTime{user.GetCreatedAt().Time}, UpdatedAt: JsonTime{user.GetUpdatedAt().Time}, CachedAt: JsonTime{time.Now()}, Token: w.token, }, nil case errors.As(err, &githubRateLimit): return nil, fmt.Errorf("[err] NewGit %w", ErrApiQuotaExceed) default: return nil, fmt.Errorf("[err] NewGit %w", err) } } // ListStarredAll returns all of starred projects. func (w *wrapper) ListStarredAll() ([]*Starred, error) { var repos []*github.StarredRepository initPage := 1 lastPage := 1 // first requests paging, resp, err := w.listStarredPaging(initPage, perPage) if err != nil { if errors.As(err, &githubRateLimit) { return nil, fmt.Errorf("[err] ListStarredAll %w", ErrApiQuotaExceed) } return nil, fmt.Errorf("[err] ListStarredAll %w", err) } // getting last page. lastPage = resp.LastPage // append repos repos = append(repos, paging...) if initPage >= resp.LastPage { } else { lock := &sync.Mutex{} wg := sync.WaitGroup{} var multiQueue []chan int var raisedErrors []error for i := 0; i < parallelSize; i++ { wg.Add(1) ch := make(chan int, lastPage/parallelSize+parallelSize) multiQueue = append(multiQueue, ch) go func(queue chan int) { for r := range queue { paging, _, err := w.listStarredPaging(r, perPage) if err != nil { switch { case errors.As(err, &githubRateLimit): color.Red("[fail] getting github page %d %s", r, ErrApiQuotaExceed) default: color.Red("[fail] getting github page %d %s", r, err.Error()) } raisedErrors = append(raisedErrors, err) continue } // race condition. lock.Lock() repos = append(repos, paging...) lock.Unlock() } wg.Done() }(ch) } // send requests for i := initPage + 1; i <= lastPage; i++ { hole := i % parallelSize multiQueue[hole] <- i } // close channel for _, ch := range multiQueue { close(ch) } wg.Wait() if len(raisedErrors) != 0 { return nil, fmt.Errorf("[err] ListStarredAll error count %d", len(raisedErrors)) } } var starred []*Starred for _, star := range repos { starred = append(starred, &Starred{ Owner: star.Repository.Owner.GetLogin(), Repo: star.Repository.GetName(), FullName: star.Repository.GetFullName(), Url: star.Repository.GetHTMLURL(), Description: star.GetRepository().GetDescription(), Topics: star.GetRepository().Topics, WatchersCount: star.GetRepository().GetWatchersCount(), StargazersCount: star.GetRepository().GetStargazersCount(), ForksCount: star.GetRepository().GetForksCount(), StarredAt: JsonTime{star.GetStarredAt().Time}, CreatedAt: JsonTime{star.GetRepository().GetCreatedAt().Time}, UpdateAt: JsonTime{star.GetRepository().GetUpdatedAt().Time}, PushedAt: JsonTime{star.GetRepository().GetPushedAt().Time}, CachedAt: JsonTime{time.Now()}, }) } return starred, nil } // SetReadme sets readme to starred. func (w *wrapper) SetReadme(starred []*Starred) { if len(starred) == 0 { return } total := len(starred) queueSize := total/parallelSize + parallelSize wg := sync.WaitGroup{} var multiQueue []chan *Starred for i := 0; i < parallelSize; i++ { wg.Add(1) ch := make(chan *Starred, queueSize) multiQueue = append(multiQueue, ch) go func(queue chan *Starred) { for r := range queue { w.setReadmeToStarred(r) } wg.Done() }(ch) } // distributes items for i, star := range starred { hole := i % parallelSize multiQueue[hole] <- star } // close channel for _, ch := range multiQueue { close(ch) } wg.Wait() } // ListReadme returns readme list. func (w *wrapper) ListReadme(owners []string, repos []string) ([]*Readme, error) { if len(owners) == 0 || len(repos) == 0 || len(owners) != len(repos) { return nil, fmt.Errorf("[err] GetMultiReadme %w", ErrInvalidParam) } total := len(owners) queueSize := total/parallelSize + parallelSize wg := sync.WaitGroup{} var multiQueue []chan *Readme for i := 0; i < parallelSize; i++ { wg.Add(1) ch := make(chan *Readme, queueSize) multiQueue = append(multiQueue, ch) go func(queue chan *Readme) { for r := range queue { r.Content, r.Err = w.getReadme(r.Owner, r.Repo) } wg.Done() }(ch) } // distributes items var readmeList []*Readme for i, _ := range owners { hole := i % parallelSize readme := &Readme{Owner: owners[i], Repo: repos[i]} readmeList = append(readmeList, readme) multiQueue[hole] <- readme } // close channel for _, ch := range multiQueue { close(ch) } wg.Wait() return readmeList, nil } func (w *wrapper) getReadme(owner, repo string) (string, error) { ctx, cancel := context.WithTimeout(context.Background(), requestTimeout) defer cancel() readme, _, err := w.Repositories.GetReadme(ctx, owner, repo, nil) if err != nil { return "", fmt.Errorf("[err] getReadme %w", err) } content, err := readme.GetContent() if err != nil { return "", fmt.Errorf("[err] getReadme %w", err) } return content, nil } func (w *wrapper) setReadmeToStarred(s *Starred) { ctx, cancel := context.WithTimeout(context.Background(), requestTimeout) defer cancel() readme, _, err := w.Repositories.GetReadme(ctx, s.Owner, s.Repo, nil) if err != nil { s.Error = fmt.Errorf("[err] setReadmeToStarred %w", err) return } content, err := readme.GetContent() if err != nil { s.Error = fmt.Errorf("[err] setReadmeToStarred %w", err) return } s.Readme = content return } func (w *wrapper) listStarredPaging(page, perPage int) ([]*github.StarredRepository, *github.Response, error) { ctx, cancel := context.WithTimeout(context.Background(), requestTimeout) defer cancel() opt := &github.ActivityListStarredOptions{} opt.Page = page opt.PerPage = perPage return w.Activity.ListStarred(ctx, "", opt) }
package main import "fmt" func main() { bob := []string{"Bob", "IT guy"} alice := []string{"Alice", "Instagirl"} fmt.Println(bob) fmt.Println(alice) coop := [][]string{bob, alice} fmt.Println(coop) }
package main import ( "flag" "io/ioutil" "gopkg.in/yaml.v2" "goreav/gen" ) type CliArgs struct { Generator string File string } var args CliArgs func init() { flag.StringVar(&args.File, "f", "", " config") } func check(err error) { if err != nil { panic(err) } } func main() { flag.Parse() //Load template file data, err := ioutil.ReadFile(args.File) check(err) //Template struct var template = make(gen.AppTemplate) //Unmarshal yaml err = yaml.Unmarshal([]byte(data), template) check(err) //Parse template err = gen.ParseTemplate(template) check(err) }
package httpx import ( "slices" "net/http" ) // Controller implements the pattern in // https://choly.ca/post/go-experiments-with-handler/ type Controller func(w http.ResponseWriter, r *http.Request) http.Handler func (c Controller) ServeHTTP(w http.ResponseWriter, r *http.Request) { if h := c(w, r); h != nil { h.ServeHTTP(w, r) } } // Middleware is any function that wraps an http.Handler returning a new http.Handler. type Middleware = func(h http.Handler) http.Handler // Stack is a slice of Middleware for use with Router. type Stack []Middleware func (stack Stack) Clone() Stack { return slices.Clone(stack) } // Push adds Middleware to end of the stack. func (stack *Stack) Push(mw ...Middleware) { *stack = append(*stack, mw...) } // Push adds Middleware to end of the stack if cond is true. func (stack *Stack) PushIf(cond bool, mw ...Middleware) { if cond { *stack = append(*stack, mw...) } } // AsMiddleware returns a Middleware // which applies each of the members of the stack to its handlers. func (stack Stack) AsMiddleware() Middleware { return func(h http.Handler) http.Handler { for i := len(stack) - 1; i >= 0; i-- { m := (stack)[i] h = m(h) } return h } } // Handler builds an http.Handler // that applies all the middleware in the stack // before calling h. func (stack Stack) Handler(h http.Handler) http.Handler { h = stack.AsMiddleware()(h) return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { h.ServeHTTP(w, r) }) } // HandlerFunc builds an http.Handler // that applies all the middleware in the stack // before calling f. func (stack Stack) HandlerFunc(f http.HandlerFunc) http.Handler { return stack.Handler(f) } // Controller builds an http.Handler // that applies all the middleware in the stack // before calling c. func (stack Stack) Controller(c Controller) http.Handler { return stack.Handler(c) }
package leetcode71 import "testing" func TestSimplifyPath(t *testing.T) { tests := []struct { input string want string }{ {"/home/", "/home"}, {"///home/", "/home"}, {"/a/./b/../../c/", "/c"}, {"/a/../../b/../../../c", "/c"}, } format := "simplifyPath(%q) = %q\n" for _, test := range tests { got := simplifyPath(test.input) if got != test.want { t.Errorf(format, test.input, got) } } }
package main import ( "fmt" "github.com/xackery/queryservgo/packet" "github.com/xackery/queryservgo/queryserv" "time" ) var qs *queryserv.QueryServ func main() { var err error /*scm := &packet.ServerChannelMessage{ //DeliverTo: "", //To: "", From: "Xuluu_[ShinTwo]", FromAdmin: 0, NoReply: true, ChanNum: 5, GuildDBId: 0, Language: 0, Queued: 0, Message: "TTEESSTTTEST", }*/ scm := &packet.ServerWhoAll{} qs = &queryserv.QueryServ{} go connectLoop() time.Sleep(1 * time.Second) fmt.Println("Sending WhoAll") err = qs.SendPacket(scm, 2) if err != nil { fmt.Println("Error sending packet", err.Error()) } select {} } func connectLoop() { var err error for { err = qs.Connect() if err != nil { fmt.Println("Error with connect:", err.Error()) return } } }
package main import "fmt" // map 删除和清空 // map 删除 使用delete func main() { scene := make(map[string]int) scene = map[string]int{"route": 66, "brazil": 4, "china": 960} delete(scene, "route") //value: 960 //value: 4 for _, i := range scene { fmt.Printf("value: %d \n", i) } // 清空 map 中的所有元素 // Go语言中并没有为 map 提供任何清空所有元素的函数、方法,清空 map //的唯一办法就是重新 make 一个新的 map,不用担心垃圾回收的效率,Go语言中的并行垃圾回收效率比写一个清空函数要高效的多。 }
package server import ( "context" "encoding/json" "errors" "net/http" kithttp "github.com/go-kit/kit/transport/http" "github.com/gorilla/mux" v1 "github.com/turao/go-worker/api/v1" ) func makeHandler(svc Service) http.Handler { r := mux.NewRouter() var opts []kithttp.ServerOption dispatchHandler := kithttp.NewServer( makeDispatchEndpoint(svc), decodeDispatchRequest, encodeResponse, opts..., ) stopHandler := kithttp.NewServer( makeStopEndpoint(svc), decodeStopRequest, encodeResponse, opts..., ) queryInfoHandler := kithttp.NewServer( makeQueryInfoEndpoint(svc), decodeQueryInfoRequest, encodeResponse, opts..., ) r.Handle("/job", dispatchHandler).Methods("POST") r.Handle("/job/{id}/stop", stopHandler).Methods("POST") r.Handle("/job/{id}/info", queryInfoHandler).Methods("GET") return r } func decodeDispatchRequest(_ context.Context, r *http.Request) (interface{}, error) { var body struct { Name string `json:"name"` Args []string `json:"args"` } err := json.NewDecoder(r.Body).Decode(&body) if err != nil { return nil, err } return v1.DispatchRequest{ Name: body.Name, Args: body.Args, }, nil } func decodeStopRequest(_ context.Context, r *http.Request) (interface{}, error) { params := mux.Vars(r) jobID, found := params["id"] if !found { return nil, errors.New("unable to find id in URL params") } return v1.StopRequest{ ID: v1.JobID(jobID), }, nil } func decodeQueryInfoRequest(_ context.Context, r *http.Request) (interface{}, error) { params := mux.Vars(r) jobID, found := params["id"] if !found { return nil, errors.New("unable to find id in URL params") } return v1.QueryInfoRequest{ ID: v1.JobID(jobID), }, nil } func encodeResponse(_ context.Context, w http.ResponseWriter, response interface{}) error { w.Header().Set("Content-Type", "application/json; charset=utf-8") return json.NewEncoder(w).Encode(response) }
package requests import ( "encoding/json" "fmt" "io/ioutil" "net/url" "strings" "github.com/google/go-querystring/query" "github.com/atomicjolt/canvasapi" "github.com/atomicjolt/canvasapi/models" "github.com/atomicjolt/string_utils" ) // CreateGroupCategoryCourses Create a new group category // https://canvas.instructure.com/doc/api/group_categories.html // // Path Parameters: // # Path.CourseID (Required) ID // // Form Parameters: // # Form.Name (Required) Name of the group category // # Form.SelfSignup (Optional) . Must be one of enabled, restrictedAllow students to sign up for a group themselves (Course Only). // valid values are: // "enabled":: allows students to self sign up for any group in course // "restricted":: allows students to self sign up only for groups in the // same section null disallows self sign up // # Form.AutoLeader (Optional) . Must be one of first, randomAssigns group leaders automatically when generating and allocating students to groups // Valid values are: // "first":: the first student to be allocated to a group is the leader // "random":: a random student from all members is chosen as the leader // # Form.GroupLimit (Optional) Limit the maximum number of users in each group (Course Only). Requires // self signup. // # Form.SISGroupCategoryID (Optional) The unique SIS identifier. // # Form.CreateGroupCount (Optional) Create this number of groups (Course Only). // # Form.SplitGroupCount (Optional) (Deprecated) // Create this number of groups, and evenly distribute students // among them. not allowed with "enable_self_signup". because // the group assignment happens synchronously, it's recommended // that you instead use the assign_unassigned_members endpoint. // (Course Only) // type CreateGroupCategoryCourses struct { Path struct { CourseID string `json:"course_id" url:"course_id,omitempty"` // (Required) } `json:"path"` Form struct { Name string `json:"name" url:"name,omitempty"` // (Required) SelfSignup string `json:"self_signup" url:"self_signup,omitempty"` // (Optional) . Must be one of enabled, restricted AutoLeader string `json:"auto_leader" url:"auto_leader,omitempty"` // (Optional) . Must be one of first, random GroupLimit int64 `json:"group_limit" url:"group_limit,omitempty"` // (Optional) SISGroupCategoryID string `json:"sis_group_category_id" url:"sis_group_category_id,omitempty"` // (Optional) CreateGroupCount int64 `json:"create_group_count" url:"create_group_count,omitempty"` // (Optional) SplitGroupCount string `json:"split_group_count" url:"split_group_count,omitempty"` // (Optional) } `json:"form"` } func (t *CreateGroupCategoryCourses) GetMethod() string { return "POST" } func (t *CreateGroupCategoryCourses) GetURLPath() string { path := "courses/{course_id}/group_categories" path = strings.ReplaceAll(path, "{course_id}", fmt.Sprintf("%v", t.Path.CourseID)) return path } func (t *CreateGroupCategoryCourses) GetQuery() (string, error) { return "", nil } func (t *CreateGroupCategoryCourses) GetBody() (url.Values, error) { return query.Values(t.Form) } func (t *CreateGroupCategoryCourses) GetJSON() ([]byte, error) { j, err := json.Marshal(t.Form) if err != nil { return nil, nil } return j, nil } func (t *CreateGroupCategoryCourses) HasErrors() error { errs := []string{} if t.Path.CourseID == "" { errs = append(errs, "'Path.CourseID' is required") } if t.Form.Name == "" { errs = append(errs, "'Form.Name' is required") } if t.Form.SelfSignup != "" && !string_utils.Include([]string{"enabled", "restricted"}, t.Form.SelfSignup) { errs = append(errs, "SelfSignup must be one of enabled, restricted") } if t.Form.AutoLeader != "" && !string_utils.Include([]string{"first", "random"}, t.Form.AutoLeader) { errs = append(errs, "AutoLeader must be one of first, random") } if len(errs) > 0 { return fmt.Errorf(strings.Join(errs, ", ")) } return nil } func (t *CreateGroupCategoryCourses) Do(c *canvasapi.Canvas) (*models.GroupCategory, error) { response, err := c.SendRequest(t) if err != nil { return nil, err } body, err := ioutil.ReadAll(response.Body) response.Body.Close() if err != nil { return nil, err } ret := models.GroupCategory{} err = json.Unmarshal(body, &ret) if err != nil { return nil, err } return &ret, nil }
package store import ( "errors" "strings" "os" "fmt" "bytes" "io/ioutil" "compress/gzip" "github.com/PuerkitoBio/goquery" "github.com/aliyun/aliyun-oss-go-sdk/oss" "github.com/astaxie/beego" ) //OSS配置【这个不再作为数据库表,直接在oss.conf文件中进行配置】 type Oss struct { EndpointInternal string //内网的endpoint EndpointOuter string //外网的endpoint AccessKeyId string //key AccessKeySecret string //secret Bucket string //供文档预览的bucket IsInternal bool //是否内网,内网则启用内网endpoint,否则启用外网endpoint Domain string } //获取oss的配置[如果使用到多个Bucket,则这里定义一个new方法,生成不同oss配置的OSS对象] //@return oss Oss配置信息 func (this *Oss) Config() (oss Oss) { oss = Oss{ IsInternal: beego.AppConfig.DefaultBool("oss::IsInternal", false), EndpointInternal: beego.AppConfig.String("oss::EndpointInternal"), EndpointOuter: beego.AppConfig.String("oss::EndpointOuter"), AccessKeyId: beego.AppConfig.String("oss::AccessKeyId"), AccessKeySecret: beego.AppConfig.String("oss::AccessKeySecret"), Bucket: beego.AppConfig.String("oss::Bucket"), Domain: strings.TrimRight(beego.AppConfig.String("oss::Domain"), "/ "), } return oss } //判断文件对象是否存在 //@param object 文件对象 //@param isBucketPreview 是否是供预览的bucket,true表示预览bucket,false表示存储bucket //@return err 错误,nil表示文件存在,否则表示文件不存在,并告知错误信息 func (this *Oss) IsObjectExist(object string) (err error) { var ( b bool Client *oss.Client Bucket *oss.Bucket config = this.Config() bucket = config.Bucket ) if len(object) == 0 { return errors.New("文件参数为空") } if config.IsInternal { Client, err = oss.New(config.EndpointInternal, config.AccessKeyId, config.AccessKeySecret) } else { Client, err = oss.New(config.EndpointOuter, config.AccessKeyId, config.AccessKeySecret) } if err == nil { if Bucket, err = Client.Bucket(bucket); err == nil { if b, err = Bucket.IsObjectExist(object); b == true { return nil } if err == nil { err = errors.New("文件不存在") } } } return err } //文件移动到OSS进行存储[如果是图片文件,不要使用gzip压缩,否则在使用阿里云OSS自带的图片处理功能无法处理图片] //@param local 本地文件 //@param save 存储到OSS的文件 //@param IsPreview 是否是预览,是预览的话,则上传到预览的OSS,否则上传到存储的OSS。存储的OSS,只作为文档的存储,以供下载,但不提供预览等访问,为私有 //@param IsDel 文件上传后,是否删除本地文件 //@param IsGzip 是否做gzip压缩,做gzip压缩的话,需要修改oss中对象的响应头,设置gzip响应 func (this *Oss) MoveToOss(local, save string, IsDel bool, IsGzip ...bool) error { config := this.Config() isgzip := false //如果是开启了gzip,则需要设置文件对象的响应头 if len(IsGzip) > 0 && IsGzip[0] == true { isgzip = true } endpoint := config.EndpointOuter //如果是内网,则使用内网endpoint if config.IsInternal { endpoint = config.EndpointInternal } client, err := oss.New(endpoint, config.AccessKeyId, config.AccessKeySecret) if err != nil { beego.Error("OSS Client初始化错误:%v", err.Error()) return err } Bucket, err := client.Bucket(config.Bucket) if err != nil { beego.Error("OSS Bucket初始化错误:%v", err.Error()) return err } //在移动文件到OSS之前,先压缩文件 if isgzip { if bs, err := ioutil.ReadFile(local); err != nil { beego.Error(err.Error()) isgzip = false //设置为false } else { var by bytes.Buffer w := gzip.NewWriter(&by) defer w.Close() w.Write(bs) w.Flush() ioutil.WriteFile(local, by.Bytes(), 0777) } } err = Bucket.PutObjectFromFile(save, local) if err != nil { beego.Error("文件移动到OSS失败:", err.Error()) return err } //如果是开启了gzip,则需要设置文件对象的响应头 if isgzip { Bucket.SetObjectMeta(save, oss.ContentEncoding("gzip")) //设置gzip响应头 } if err == nil && IsDel { err = os.Remove(local) } return err } //从OSS中删除文件 //@param object 文件对象 //@param IsPreview 是否是预览的OSS func (this *Oss) DelFromOss(object ...string) error { config := this.Config() bucket := config.Bucket endpoint := config.EndpointOuter //如果是内网,则使用内网endpoint if config.IsInternal { endpoint = config.EndpointInternal } client, err := oss.New(endpoint, config.AccessKeyId, config.AccessKeySecret) if err != nil { return err } Bucket, err := client.Bucket(bucket) if err != nil { return err } _, err = Bucket.DeleteObjects(object) return err } //设置文件的下载名 //@param obj 文档对象 //@param filename 文件名 func (this *Oss) SetObjectMeta(obj, filename string) { config := this.Config() if client, err := oss.New(config.EndpointOuter, config.AccessKeyId, config.AccessKeySecret); err == nil { if Bucket, err := client.Bucket(config.Bucket); err == nil { Bucket.SetObjectMeta(obj, oss.ContentDisposition(fmt.Sprintf("attachment; filename=%v", filename))) //Bucket.SetObjectMeta(obj, oss.Meta("ContentDisposition", fmt.Sprintf("attachment; filename=%v", filename))) //Bucket.SetObjectMeta(obj, ) } } } //处理html中的OSS数据:如果是用于预览的内容,则把img等的链接的相对路径转成绝对路径,否则反之 //@param htmlstr html字符串 //@param forPreview 是否是供浏览的页面需求 //@return str 处理后返回的字符串 func (this *Oss) HandleContent(htmlstr string, forPreview bool) (str string) { doc, err := goquery.NewDocumentFromReader(strings.NewReader(htmlstr)) config := this.Config() if err == nil { doc.Find("img").Each(func(i int, s *goquery.Selection) { // For each item found, get the band and title if src, exist := s.Attr("src"); exist { //预览 if forPreview { //不存在http开头的图片链接,则更新为绝对链接 if !(strings.HasPrefix(src, "http://") || strings.HasPrefix(src, "https://")) { s.SetAttr("src", config.Domain+"/"+strings.TrimLeft(src, "./")) } } else { s.SetAttr("src", strings.TrimPrefix(src, config.Domain)) } } }) str, _ = doc.Find("body").Html() } return } //从HTML中提取图片文件,并删除 func (this *Oss) DelByHtmlPics(htmlstr string) { doc, err := goquery.NewDocumentFromReader(strings.NewReader(htmlstr)) config := this.Config() if err == nil { doc.Find("img").Each(func(i int, s *goquery.Selection) { // For each item found, get the band and title if src, exist := s.Attr("src"); exist { //不存在http开头的图片链接,则更新为绝对链接 if !(strings.HasPrefix(src, "http://") || strings.HasPrefix(src, "https://")) { this.DelFromOss(strings.TrimLeft(src, "./")) //删除 } else if strings.HasPrefix(src, config.Domain) { this.DelFromOss(strings.TrimPrefix(src, config.Domain)) //删除 } } }) } return } //根据oss文件夹 func (this *Oss) DelOssFolder(folder string) (err error) { config := this.Config() if client, err := oss.New(config.EndpointOuter, config.AccessKeyId, config.AccessKeySecret); err == nil { if Bucket, err := client.Bucket(config.Bucket); err == nil { folder = strings.Trim(folder, "/") if lists, err := Bucket.ListObjects(oss.Prefix(folder)); err != nil { return err } else { var objs []string for _, list := range lists.Objects { objs = append(objs, list.Key) } if len(objs) > 0 { this.DelFromOss(objs...) } this.DelFromOss(folder) } } } return }
package controllers import ( "crypto/md5" "encoding/base64" "github.com/astaxie/beego" "fmt" ) var ( shortyLookup *beego.BeeCache ) const DONT_EXPIRE = 0 func init() { shortyLookup = beego.NewBeeCache() shortyLookup.Every = DONT_EXPIRE shortyLookup.Start() beego.AddFuncMap("printShorties", printShorties) } type ShortenController struct { beego.Controller } func storeMe(shorturl string, longurl string) { if !shortyLookup.IsExist(shorturl) { shortyLookup.Put(shorturl, longurl, DONT_EXPIRE) shortyLookup.Put(longurl, shorturl, DONT_EXPIRE) } } func shortenMe(str string) (short string) { hasher := md5.New() hasher.Write([]byte(str)) short = base64.URLEncoding.EncodeToString(hasher.Sum(nil))[0:5] return } func (this *ShortenController) Post() { this.Layout = "layout.html" longurl := this.GetString("longurl") var shorturl string if shortyLookup.IsExist(longurl) { shorturl = shortyLookup.Get(longurl).(string) } else { shorturl = shortenMe(longurl) storeMe(shorturl, longurl) } this.Data["longurl"] = longurl this.Data["shorturl"] = "http://localhost:8080/" + shorturl this.TplNames = "shorten.get.tpl" } func printShorties(shortyLookup *beego.BeeCache) string { for key, value := range shortyLookup.Items() { fmt.Printf("\n%s => %v", key, value.Access()) } return "booty" } func (this *ShortenController) Get() { this.Layout = "layout.html" this.Data["shorties"] = shortyLookup this.TplNames = "shorten.get.tpl" } /* Redirect Handler */ type RedirectController struct { beego.Controller } func (this *RedirectController) Get() { shorturl := this.Ctx.Params[":shorturl"] if shortyLookup.IsExist(shorturl) { longy := shortyLookup.Get(shorturl).(string) this.Redirect(longy, 302) } else { this.Redirect("/", 302) } }
// Copyright 2021 The ChromiumOS Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package pre import ( "archive/zip" "context" "fmt" "io" "io/ioutil" "os" "path" "path/filepath" "strings" "time" "github.com/golang/protobuf/ptypes/empty" "chromiumos/tast/common/android/adb" "chromiumos/tast/common/testexec" "chromiumos/tast/errors" remoteadb "chromiumos/tast/remote/android/adb" "chromiumos/tast/rpc" pb "chromiumos/tast/services/cros/camerabox" "chromiumos/tast/testing" ) // To uprev |ctsVerifierX86Zip| and |ctsVerifierArmZip|, download the new zip // from https://source.android.com/compatibility/cts/downloads, replace old zip // under data folder and check the test can still pass. const ( ctsVerifierRoot = "android-cts-verifier" // CtsVerifierX86Zip is data path to ITS bundle testing x86 compatible platform. CtsVerifierX86Zip = "its/android-cts-verifier-9.0_r15-linux_x86-x86.zip" // CtsVerifierArmZip is data path to ITS bundle testing arm compatible platform. CtsVerifierArmZip = "its/android-cts-verifier-9.0_r15-linux_x86-arm.zip" // ITSPy3Patch is the data path of py2 to py3 patch for ITS test // scripts. Update the script content with the steps: // $ python3 setup_its_repo.py android-cts-verifier-XXX.zip // $ cd android-cts-verifier/CameraITS // # Do modification to *.py // $ git diff base > <Path to this patch> ITSPy3Patch = "its/its.patch" // SetupITSRepoScript is the data path of the script unpacking ITS // bundle and apply python3 patches. SetupITSRepoScript = "its/setup_its_repo.py" ) type bundleAbi string const ( x86 bundleAbi = "x86" arm = "arm" ) func (abi bundleAbi) bundlePath() (string, error) { switch abi { case x86: return CtsVerifierX86Zip, nil case arm: return CtsVerifierArmZip, nil } return "", errors.Errorf("cannot get bundle path of unknown abi %v", abi) } // itsPreImpl implements testing.Precondition. type itsPreImpl struct { cl *rpc.Client itsCl pb.ITSServiceClient abi bundleAbi dir string oldEnvPath string hostname string adbDevice *adb.Device prepared bool } // ITSHelper provides helper functions accessing ITS package and mandating ARC. type ITSHelper struct { p *itsPreImpl } // ITSX86Pre is the test precondition to run Android x86 ITS test. var ITSX86Pre = &itsPreImpl{abi: x86} // ITSArmPre is the test precondition to run Android x86-arm ITS test. var ITSArmPre = &itsPreImpl{abi: arm} func (p *itsPreImpl) String() string { return fmt.Sprintf("its_%s_precondition", p.abi) } func (p *itsPreImpl) Timeout() time.Duration { return 5 * time.Minute } func copyFile(src, dst string, perm os.FileMode) error { content, err := ioutil.ReadFile(src) if err != nil { return err } return ioutil.WriteFile(dst, content, perm) } func itsUnzip(ctx context.Context, zipPath, outDir string) error { r, err := zip.OpenReader(zipPath) if err != nil { return errors.Wrap(err, "failed to open ITS zip file") } defer r.Close() for _, f := range r.File { if f.FileInfo().IsDir() { continue } src, err := f.Open() if err != nil { return errors.Wrapf(err, "failed to open file %v in ITS zip", f.Name) } defer src.Close() dstPath := path.Join(outDir, f.Name) if err := os.MkdirAll(filepath.Dir(dstPath), 0755); err != nil { return errors.Wrapf(err, "failed to create directory for unzipped ITS file %v", f.Name) } dst, err := os.Create(dstPath) if err != nil { return errors.Wrapf(err, "failed to create file for copying ITS file %v", f.Name) } defer dst.Close() if _, err := io.Copy(dst, src); err != nil { return errors.Wrapf(err, "failed to copy ITS file %v", f.Name) } } return nil } func (p *itsPreImpl) Prepare(ctx context.Context, s *testing.PreState) interface{} { if p.prepared { return &ITSHelper{p} } d := s.DUT() // Connect to the gRPC server on the DUT. cl, err := rpc.Dial(ctx, d, s.RPCHint()) if err != nil { s.Fatal("Failed to connect to the HAL3 service on the DUT: ", err) } p.cl = cl // Set up ARC on DUT. itsClient := pb.NewITSServiceClient(cl.Conn) _, err = itsClient.SetUp(ctx, &empty.Empty{}) if err != nil { s.Fatal("Remote call Setup() failed: ", err) } p.itsCl = itsClient // Prepare temp bin dir. tempDir, err := ioutil.TempDir("", "") if err != nil { s.Fatal("Failed to create a temp dir for extra binaries: ", err) } p.dir = tempDir p.oldEnvPath = os.Getenv("PATH") os.Setenv("PATH", p.dir+":"+p.oldEnvPath) // Prepare ADB downloaded from fixed url without versioning (Same // strategy as CTS), may consider associate proper version in // tast-build-deps. if err := copyFile(s.DataPath("adb"), path.Join(p.dir, "adb"), 0755); err != nil { s.Fatal("Failed to copy adb binary: ", err) } p.hostname = d.HostName() if err := remoteadb.LaunchServer(ctx); err != nil { s.Fatal("Failed to launch adb server: ", err) } testing.ContextLog(ctx, "ADB connect to DUT") adbDevice, err := adb.Connect(ctx, p.hostname, 30*time.Second) if err != nil { s.Fatal("Failed to set up adb connection to DUT: ", err) } p.adbDevice = adbDevice // Unpack ITS bundle. bundlePath, err := p.abi.bundlePath() if err != nil { s.Fatal("Failed to get bundle path: ", err) } if err := testexec.CommandContext( ctx, "python3", s.DataPath(SetupITSRepoScript), s.DataPath(bundlePath), "--patch_path", s.DataPath(ITSPy3Patch), "--output", p.dir).Run(testexec.DumpLogOnError); err != nil { s.Fatal("Failed to setup its repo from bundle path: ", err) } // Install CTSVerifier apk. ctsVerifierRootPath := path.Join(p.dir, ctsVerifierRoot) verifierAPK := path.Join(ctsVerifierRootPath, "CtsVerifier.apk") if err := p.adbDevice.Command(ctx, "install", "-r", "-g", verifierAPK).Run(testexec.DumpLogOnError); err != nil { s.Fatal("Failed to install CTSVerifier: ", err) } p.prepared = true return &ITSHelper{p} } func (p *itsPreImpl) itsRoot() string { return path.Join(p.dir, ctsVerifierRoot, "CameraITS") } func (p *itsPreImpl) Close(ctx context.Context, s *testing.PreState) { if len(p.oldEnvPath) > 0 { if err := os.Setenv("PATH", p.oldEnvPath); err != nil { s.Errorf("Failed to restore environment variable PATH %v: %v", p.oldEnvPath, err) } } if len(p.dir) > 0 { if err := os.RemoveAll(p.dir); err != nil { s.Errorf("Failed to remove temp directory %v: %v", p.dir, err) } } if p.itsCl != nil { if _, err := p.itsCl.TearDown(ctx, &empty.Empty{}); err != nil { s.Error("Failed to call remote its TearDown(): ", err) } } if p.cl != nil { p.cl.Close(ctx) } p.prepared = false } // TestCmd returns command to run test scene with camera id. func (h *ITSHelper) TestCmd(ctx context.Context, scene, camera int) *testexec.Cmd { setupPath := path.Join("build", "envsetup.sh") scriptPath := path.Join("tools", "run_all_tests.py") cmdStr := fmt.Sprintf(`cd %s source %s python3 %s device=%s scenes=%d camera=%d skip_scene_validation`, h.p.itsRoot(), setupPath, scriptPath, h.p.hostname, scene, camera) cmd := testexec.CommandContext(ctx, "bash", "-c", cmdStr) cmd.Env = append(os.Environ(), "PYTHONUNBUFFERED=y") return cmd } // Chart returns scene chart to run test scene. func (h *ITSHelper) Chart(scene int) string { s := fmt.Sprintf("scene%d", scene) return path.Join(h.p.itsRoot(), "tests", s, s+".pdf") } // CameraID returns corresponding camera id of camera facing on DUT. func (h *ITSHelper) CameraID(ctx context.Context, facing pb.Facing) (int, error) { out, err := h.p.adbDevice.Command(ctx, "shell", "pm", "list", "features").Output(testexec.DumpLogOnError) if err != nil { return -1, errors.Wrap(err, "failed to list features on ARC") } var front, back bool for _, feature := range strings.Split(string(out), "\n") { if feature == "feature:android.hardware.camera.front" { front = true } else if feature == "feature:android.hardware.camera" { back = true } } if (facing == pb.Facing_FACING_BACK && !back) || (facing == pb.Facing_FACING_FRONT && !front) { return -1, errors.Errorf("cannot run test on DUT without %s facing camera", facing) } if back && front && facing != pb.Facing_FACING_BACK { return 1, nil } return 0, nil }
package consul import ( "fmt" "net/http" consulApi "github.com/hashicorp/consul/api" ) const ( agentDeregisterAfter = 45 agentCheckInterval = 15 agentCheckTimeout = 5 ) // AgentConfig returns new consul agent config func (c *Config) AgentConfig() *consulApi.AgentServiceRegistration { return &consulApi.AgentServiceRegistration{ ID: c.ServiceName, Name: c.ServiceName, Check: &consulApi.AgentServiceCheck{ HTTP: fmt.Sprintf("http://%s:%d%s", c.ServiceName, c.ServicePort, c.ServiceHealthCheckPath), Method: http.MethodGet, Interval: fmt.Sprintf("%ds", agentCheckInterval), Timeout: fmt.Sprintf("%ds", agentCheckTimeout), DeregisterCriticalServiceAfter: fmt.Sprintf("%ds", agentDeregisterAfter), }, Address: c.ServiceName, Port: c.ServicePort, } }
package main import ( "fmt" "unicode/utf8" ) //字符串是一种值类型,且值不可变,即创建某个文本后将无法再次修改这个文本的内容, //更深入地讲,字符串是字节的定长数组。 func main() { // 使用""来定义字符串 字符串可以使用转义符实现换行缩进等效果 常见的转义符如下所示 // \n 换行 \r 回车符 \t tab键 \u Unicode字符 \\ 反斜杠本身 str := "Java\nGo" fmt.Println(str) // 字符串拼接使用+ msg := "一个消息:" + "好消息" fmt.Println(msg) // 字符串拼接也可以使用 += s := "夏天" s += "秋天" fmt.Println(s) // 定义多行字符串 var name = `第一行 第二行 第三行 /n` fmt.Println(name) // ASCII 字符串长度使用 len() 函数。 // Unicode 字符串长度使用 utf8.RuneCountInString() 函数。 // 计算字符串长度 len() 函数的返回值的类型为 int,表示字符串的 ASCII 字符个数或字节长度。 str1 := "abcd efg" str2 := "中国" fmt.Println(len(str1)) //8 // 中国为什么是6呢而不是2呢 //这里的差异是由于 Go 语言的字符串都以 UTF-8 格式保存, //每个中文占用 3 个字节,因此使用 len() 获得两个中文文字对应的 6 个字节。 fmt.Println(len(str2)) //6 str3 := "中国,niubi" //UTF-8 包提供的 RuneCountInString() 函数,统计 Uncode 字符数量。 fmt.Println(utf8.RuneCountInString(str2)) //2 fmt.Println(utf8.RuneCountInString(str3)) //8 // 字符串遍历 有二种遍历方法 // 01 遍历每个ASCII字符 - ASCII 字符串遍历直接使用下标。 //如果出现中文就会出现乱码 str4 := "中国,China" for i := 0; i < len(str4); i++ { fmt.Printf("ascii: %c %d\n", str4[i], str4[i]) } // 按Unicode字符遍历字符串 - Unicode 字符串遍历用 for range 出现中文也不会乱码 for _, s := range str4 { fmt.Printf("unicode: %c %d\n", s, s) } }
package ssh import ( "crypto" "crypto/x509" "encoding/pem" "io" "io/ioutil" "os" "time" "golang.org/x/crypto/ssh" "github.com/pkg/errors" "github.com/pkg/sftp" ) type Dialer interface { Dial(address, username string, timeout time.Duration) (Connection, error) } type Connection interface { UploadFile(path string, data []byte) (bool, error) DownloadFile(path string) ([]byte, error) RunCommand(command string, output io.Writer) (int32, error) Close() error } func FormatPublicKey(key interface{}) ([]byte, error) { pubKey, err := ssh.NewPublicKey(key) if err != nil { return nil, errors.Wrap(err, "couldn't use public key") } return ssh.MarshalAuthorizedKey(pubKey), nil } type AuthDialer struct { authMethods []ssh.AuthMethod } func NewDialerWithKey(key crypto.Signer) (*AuthDialer, error) { signer, err := ssh.NewSignerFromKey(key) if err != nil { return nil, errors.Wrap(err, "couldn't create signer from SSH key") } return &AuthDialer{ authMethods: []ssh.AuthMethod{ssh.PublicKeys(signer)}, }, nil } func NewDialerWithPassword(password string) (*AuthDialer, error) { return &AuthDialer{ authMethods: []ssh.AuthMethod{ssh.Password(password)}, }, nil } func NewDialerWithKeyWithoutPassPhrase(pemBytes []byte) (*AuthDialer, error) { signer, err := ssh.ParsePrivateKey(pemBytes) if err != nil { return nil, errors.Wrap(err, "couldn't create signer from SSH key") } return &AuthDialer{ authMethods: []ssh.AuthMethod{ssh.PublicKeys(signer)}, }, nil } func NewDialer(keyPath, keyPassphrase string) (*AuthDialer, error) { file, err := ioutil.ReadFile(keyPath) if err != nil { return nil, errors.Wrap(err, "couldn't read SSH key") } block, _ := pem.Decode(file) if block == nil { return nil, errors.Errorf("ssh key does not contain a valid PEM block") } if keyPassphrase == "" { return NewDialerWithKeyWithoutPassPhrase(file) } der, err := x509.DecryptPEMBlock(block, []byte(keyPassphrase)) if err != nil { return nil, errors.Wrap(err, "couldn't decrypt SSH key") } key, err := x509.ParsePKCS1PrivateKey(der) if err != nil { return nil, errors.Wrap(err, "couldn't parse SSH key") } return NewDialerWithKey(key) } func (d *AuthDialer) Dial(address, username string, timeout time.Duration) (Connection, error) { client, err := ssh.Dial("tcp", address, &ssh.ClientConfig{ User: username, Auth: d.authMethods, Timeout: timeout, // TODO: Verify server public key against something (optionally)? HostKeyCallback: ssh.InsecureIgnoreHostKey(), }) if err != nil { return nil, errors.Wrap(err, "couldn't connect to SSH server") } return &sshConnection{client: client}, nil } type sshConnection struct { client *ssh.Client } func (c *sshConnection) UploadFile(path string, data []byte) (bool, error) { sftp, err := sftp.NewClient(c.client) if err != nil { return false, errors.Wrap(err, "couldn't create SFTP client") } defer sftp.Close() _, err = sftp.Lstat(path) if err == nil { return true, errors.New("file already existed") } f, err := sftp.Create(path) if err != nil { return false, errors.Wrap(err, "couldn't create file") } _, err = f.Write(data) if err != nil { return false, errors.Wrap(err, "couldn't write contents to file") } return false, nil } func (c *sshConnection) DownloadFile(path string) ([]byte, error) { sftp, err := sftp.NewClient(c.client) if err != nil { return nil, errors.Wrap(err, "couldn't create SFTP client") } defer sftp.Close() // TODO: enforce file size limit _, err = sftp.Lstat(path) if err != nil { return nil, errors.Wrap(err, "couldn't stat file") } f, err := sftp.OpenFile(path, os.O_RDONLY) if err != nil { return nil, errors.Wrap(err, "couldn't open file") } buf, err := ioutil.ReadAll(f) if err != nil { return nil, errors.Wrap(err, "couldn't read contents of file") } return buf, nil } func (c *sshConnection) RunCommand(command string, output io.Writer) (int32, error) { session, err := c.client.NewSession() if err != nil { return 0, errors.Wrap(err, "error creating SSH session") } defer session.Close() err = session.RequestPty("xterm", 40, 80, ssh.TerminalModes{}) if err != nil { return 0, errors.Wrap(err, "error requesting PTY") } session.Stdout = output session.Stderr = output err = session.Run(command) if err == nil { return 0, nil } switch err := err.(type) { case *ssh.ExitError: return int32(err.ExitStatus()), nil default: return 0, errors.Wrap(err, "error running script") } } func (c *sshConnection) Close() error { return c.client.Close() }
package main import ( "fmt" ) func main() { nums := []int{9,8,6,3,6,1,2} fmt.Println(mergeSort(nums)) } func mergeSort(nums []int) []int { if len(nums) < 2 { return nums } half := len(nums) / 2 l := mergeSort(nums[:half]) r := mergeSort(nums[half:]) return merge(l,r) } func merge(a, b []int) []int { ret := make([]int, 0, len(a)+len(b)) for len(a) > 0 || len(b) > 0 { if(len(a) == 0) { return append(ret, b...) } if(len(b) == 0) { return append(ret, a...) } if(a[0] <= b[0]) { ret = append(ret,a[0]) a = a[1:] } else { ret = append(ret, b[0]) b = b[1:] } } return ret } half := len(nums)/2 l := merge(num[:half]) return merge(l,r)
package service import ( "fmt" //"time" "github.com/Caroline1997/Service-Agenda/cli/entity" ) // log's command // Login POST /v1/user/login func Login(name string, password string) (err error) { var flag bool flag, err = entity.Check_Login() if err != nil { return err } if flag == true { var currentUser string currentUser, err = entity.GetCurrentUser() err = fmt.Errorf("There exist someone logged as '%s', please logout!", currentUser) return err } err = entity.Login(name, password) if err != nil { return err } return nil } // Logout POST /v1/user/logout func Logout() (err error) { var flag bool flag, err = entity.Check_Login() if err != nil { return err } if flag == true { err, _ = entity.Logout() if err != nil { return err } } else { return fmt.Errorf("Please log in first") } return nil } // User's command func check_user_valid(user *entity.User) error { if len(user.Username) == 0 { return fmt.Errorf("Please enter your username!") } if len(user.Password) == 0 { return fmt.Errorf("Please enter your password!") } return nil } // Register POST /v1/users func Register(username string, password string, email string, phone string) (err error) { User1 := &entity.User{ Username: username, Password: password, Email: email, Phone: phone, } err = check_user_valid(User1) if err != nil { return err } err = entity.CreateUser(User1) if err != nil { return err } return nil } // DELETE DELETE /v1/user/account func Delete_user(username string, password string) (err error) { var flag bool flag, err = entity.Check_Login() if err != nil { return err } if flag == true { err = entity.DeleteUser() if err != nil { return err } } return nil } // ListAllUsers GET /v1/users func List_all_users() ([]entity.User, error) { return entity.ListAllUsers() } // Meeting's command func check_meeting_valid(meeting *entity.Meeting) error { if len(meeting.Title) == 0 { return fmt.Errorf("Please enter your title!") } if len(meeting.Participators) == 0 { return fmt.Errorf("Please enter at least one participator!") } return nil } // Create Meeting POST /v1/meetings func Create_meeting(title string, participators []string, startTime string, endTime string) (err error) { var flag bool flag, err = entity.Check_Login() if err != nil { return err } if flag == true { sponsor, err := entity.GetCurrentUser() if err != nil { return err } Meeting1 := &entity.Meeting{ Sponsor: sponsor, Participators: participators, StartTime: startTime, EndTime: endTime, Title: title, } err = check_meeting_valid(Meeting1) if err != nil { return err } err = entity.CreateMeeting(Meeting1) if err != nil { return err } return nil } return nil } // Query Meetings GET /v1/meetings{?startDate,endDate} /*func Query_meeting(startTime string, endTime string) (meetings []entity.Meeting, err error) { var flag bool flag, err = entity.Check_Login() if err != nil { return nil, err } if flag == true { // check start time if len(startTime) == 0 { return nil, fmt.Errorf("Please enter startTime!") } // 2006-01-02 15:04:05 is time format _, err := time.Parse("2006-01-02 15:04:05", startTime) if err != nil { return nil, fmt.Errorf("Please enter correct startTime format!") } // check end time if len(endTime) == 0 { return nil, fmt.Errorf("Please enter endTime!") } _, err = time.Parse("2006-01-02 15:04:05", endTime) if err != nil { return nil, fmt.Errorf("Please enter correct endTime format!") } // compare if startTime > endTime { return nil, fmt.Errorf("startTime should not larger than endTime!") } meetings, err = entity.QueryMeeting(startTime, endTime) if err != nil { return nil, err } return meetings, nil } return nil, nil }*/
package storage import ( "errors" pb "github.com/xuperchain/xupercore/kernel/consensus/base/driver/chained-bft/pb" ) var _ QuorumCertInterface = (*QuorumCert)(nil) var ( ErrNoValidQC = errors.New("target qc is empty") ErrNoValidParentId = errors.New("parentId is empty") ) // 本文件定义了chained-bft下有关的数据结构和接口 // QuorumCertInterface 规定了pacemaker和saftyrules操作的qc接口 // QuorumCert 为一个QuorumCertInterface的实现 TODO: smr彻底接口化是否可能? // QCPendingTree 规定了smr内存存储的组织形式,其为一个QC树状结构 // QuorumCertInterface 接口 type QuorumCertInterface interface { GetProposalView() int64 GetProposalId() []byte GetParentProposalId() []byte GetParentView() int64 GetSignsInfo() []*pb.QuorumCertSign } // VoteInfo 包含了本次和上次的vote对象 type VoteInfo struct { // 本次vote的对象 ProposalId []byte ProposalView int64 // 本地上次vote的对象 ParentId []byte ParentView int64 } // ledgerCommitInfo 表示的是本地账本和QC存储的状态,包含一个commitStateId和一个voteInfoHash // commitStateId 表示本地账本状态,TODO: = 本地账本merkel root // voteInfoHash 表示本地vote的vote_info的哈希,即本地QC的最新状态 type LedgerCommitInfo struct { CommitStateId []byte VoteInfoHash []byte } func NewQuorumCert(v *VoteInfo, l *LedgerCommitInfo, s []*pb.QuorumCertSign) QuorumCertInterface { qc := QuorumCert{ VoteInfo: v, LedgerCommitInfo: l, SignInfos: s, } return &qc }
/* trader strategy */ package strategy import ( "config" "db" "logger" "sync" "trade_service" "util" ) var buy_queue_mutex = &sync.Mutex{} var buy_total_amount float64 var sell_queue_mutex = &sync.Mutex{} var sell_total_amount float64 var buy_limit float64 var sell_limit float64 func initTotalReadyAmount() { _buy_queue_amount, prs := config.Config["buy_queue_amount"] if !prs { _buy_queue_amount = "200" } _sell_queue_amount, prs := config.Config["sell_queue_amount"] if !prs { _sell_queue_amount = "200" } buy_limit = util.ToFloat(_buy_queue_amount) sell_limit = util.ToFloat(_sell_queue_amount) buy_total, sell_total := db.GetTotalReadyNow() logger.Infoln("init limit:", buy_limit, sell_limit, buy_total, sell_total) incr_buy(buy_total) incr_sell(sell_total) } func get_current_buy_total() float64 { buy_queue_mutex.Lock() defer buy_queue_mutex.Unlock() if buy_total_amount < 0 { logger.Errorln("buy_total_amount:", buy_total_amount) buy_total_amount = 0 } return buy_total_amount } func get_current_sell_total() float64 { sell_queue_mutex.Lock() defer sell_queue_mutex.Unlock() if buy_total_amount < 0 { logger.Errorln("sell_total_amount:", sell_total_amount) sell_total_amount = 0 } return sell_total_amount } func get_factor(amount float64, tradeType trade_service.TradeType) float64 { if tradeType == trade_service.TradeType_BUY { return get_buy_factor(amount) } else { return get_sell_factor(amount) } } func get_buy_factor(amount float64) float64 { factor := buy_total_amount + amount/buy_limit return factor } func get_sell_factor(amount float64) float64 { factor := sell_total_amount + amount/sell_limit return factor } func is_limit_buy(amount float64) bool { buy_queue_mutex.Lock() defer buy_queue_mutex.Unlock() if buy_total_amount+amount > buy_limit { logger.Infoln("buy_total_amount:", buy_total_amount) return true } buy_total_amount += amount logger.Infoln("buy_total_amount:", buy_total_amount) return false } func is_limit_sell(amount float64) bool { sell_queue_mutex.Lock() defer sell_queue_mutex.Unlock() if sell_total_amount+amount > sell_limit { logger.Infoln("sell_total_amount:", sell_total_amount) return true } sell_total_amount += amount logger.Infoln("sell_total_amount:", sell_total_amount) return false } func incr_buy(amount float64) { buy_queue_mutex.Lock() defer buy_queue_mutex.Unlock() buy_total_amount += amount logger.Infoln("buy_total_amount:", buy_total_amount) } func incr_sell(amount float64) { sell_queue_mutex.Lock() defer sell_queue_mutex.Unlock() sell_total_amount += amount logger.Infoln("sell_total_amount:", sell_total_amount) } func decr_buy(amount float64) { buy_queue_mutex.Lock() defer buy_queue_mutex.Unlock() buy_total_amount -= amount logger.Infoln("buy_total_amount:", buy_total_amount) } func decr_sell(amount float64) { sell_queue_mutex.Lock() defer sell_queue_mutex.Unlock() sell_total_amount -= amount logger.Infoln("sell_total_amount:", sell_total_amount) }
package entity // TODO: для описания типов использовать https://github.com/jackc/pgtype import ( "context" "github.com/jackc/pgx/v4" "github.com/pkg/errors" ) // Suggestion описывает предложения. type Suggestion struct { EntryID int `sql:"entry_id" json:"entry_id"` ExtDB string `sql:"ext_db" json:"ext_db"` ExtID string `sql:"ext_id" json:"ext_id"` Json []byte `json:"json"` Score float64 `json:"score"` } // Create записывает объект в БД. func (r *Suggestion) Create(ctx context.Context) error { err := InsertFullRec( ctx, `INSERT INTO audio.suggestion (entry_id,ext_db,ext_id,json,score)`, r.EntryID, r.ExtDB, r.ExtID, r.Json, r.Score) if err != nil { err = errors.Wrapf( err, "Suggestion.Create() failed: entry_id=%d, ext_db=%s, ext_id=%s", r.EntryID, r.ExtDB, r.ExtID) } return err } // Delete удаляет объект в БД по ID записи. func (r *Suggestion) Delete(ctx context.Context) error { err := Delete( ctx, "DELETE FROM audio.release WHERE entry_id=$1 AND ext_db=$2 AND ext_id=$3", r.EntryID, r.ExtDB, r.ExtID) if err != nil { err = errors.Wrap(err, "Suggestion.Delete() failed") } return err } // Get ищет объект по значению ключа записи. func (r *Suggestion) Get(ctx context.Context) error { qry := `SELECT json,score FROM audio.release WHERE entry_id=$1 AND ext_db=$2 AND ext_id=$3 LIMIT 1` row, err := Get(ctx, qry, r, r.EntryID, r.ExtDB, r.ExtID) if err != nil { return errors.Wrap(err, "Suggestion.Get() select failed") } err = row.Scan(&r.Json, &r.Score) if err != nil && err != pgx.ErrNoRows { err = errors.Wrap(err, "Suggestion.Get() scan failed") } return err } // EntrySuggestions возвращает список рекомендованных релизов для данного album_entry. func EntrySuggestions(ctx context.Context, entryID int) ([]*Suggestion, error) { db := ctx.Value("db").(*pgx.Conn) if db == nil { return nil, errors.Wrap(ErrConnectionInContext, "EntrySuggestions() failed") } rows, err := db.Query(ctx, "SELECT * FROM audio.suggestion WHERE entry_id=$1", entryID) if err != nil { return nil, errors.Wrap(err, "EntrySuggestions() select failed") } defer rows.Close() ret := []*Suggestion{} for rows.Next() { var s Suggestion if err = rows.Scan(&s.EntryID, &s.ExtDB, &s.ExtID, &s.Json, &s.Score); err != nil { return nil, errors.Wrap(err, "EntrySuggestions() scan failed") } ret = append(ret, &s) } return ret, nil } func DeleteEntrySuggestions(ctx context.Context, entryID int) error { err := Delete(ctx, "DELETE FROM audio.suggestion WHERE entry_id=$1", entryID) if err != nil { err = errors.Wrap(err, "DeleteEntrySuggestions() failed") } return err }
package main type X struct { Xa int Xb int } func (x X) foo() { return } func main() { x := X{ }
package main import ( "book/goroutines/channels/counter/counter" "book/goroutines/channels/counter/squarer" "fmt" ) func main() { fmt.Println("Initializing....") natural := make(chan int) squares := make(chan int) go counter.Counter(natural) go squarer.Squarer(squares, natural) printer(squares) } func printer(in <-chan int) { for v := range in { fmt.Println(v) } }
package main import ( "fmt" ) type ColorError interface { error ColorError() string } type checkError struct { coord Coord msg string colorMsg string } func newCheckError(coord Coord, format, colorFormat string, args ...interface{}) (err checkError) { return checkError{ coord: coord, msg: fmt.Sprintf(format, args...), colorMsg: fmt.Sprintf(colorFormat, args...), } } func (err checkError) Error() string { return fmt.Sprintf("%s: %s", err.coord, err.msg) } func (err checkError) ColorError() string { return fmt.Sprintf("\x1b[35m%s\x1b[39m: %s", err.coord, err.colorMsg) }
package pack import ( "bufio" "bytes" "encoding/binary" "errors" "io" ) type IndexFile []IndexRecord var indexEndianness = binary.BigEndian // increment when you make backwards-incompatible changes var indexFileMagicBytes = []byte("GOBACKIDX_0001") var errIndexHeaderMismatch = errors.New("received unexpected index file header") func (idx IndexFile) Len() int { return len(idx) } func (idx IndexFile) Swap(i, j int) { idx[i], idx[j] = idx[j], idx[i] } func (idx IndexFile) Less(i, j int) bool { return bytes.Compare(idx[i].Sum[:], idx[j].Sum[:]) < 0 } func (idx *IndexFile) ReadFrom(reader io.Reader) (int64, error) { buf := bufio.NewReader(reader) var count uint32 byteCounter := &countingWriter{} source := io.TeeReader(buf, byteCounter) magic := make([]byte, len(indexFileMagicBytes)) _, err := io.ReadFull(source, magic) if err != nil { return byteCounter.count, err } if !bytes.Equal(magic, indexFileMagicBytes) { return byteCounter.count, errIndexHeaderMismatch } err = binary.Read(source, indexEndianness, &count) if err != nil { return 0, err } *idx = make([]IndexRecord, count) for i := 0; i < int(count); i++ { idxSlice := *idx err = binary.Read(source, indexEndianness, &idxSlice[i]) if err != nil { return 0, err } } return byteCounter.count, nil } func (idx IndexFile) WriteTo(writer io.Writer) (int64, error) { buf := bufio.NewWriter(writer) count := uint32(len(idx)) byteCounter := &countingWriter{} target := io.MultiWriter(buf, byteCounter) n, err := target.Write(indexFileMagicBytes) if err != nil { return int64(n), err } err = binary.Write(target, indexEndianness, count) if err != nil { return 0, err } for _, record := range idx { err = binary.Write(target, indexEndianness, &record) if err != nil { return 0, err } } return byteCounter.count, buf.Flush() } type IndexRecord struct { Sum [20]byte Offset uint32 Length uint32 Type uint32 } var _ io.WriterTo = (IndexFile)(nil) var _ io.ReaderFrom = (*IndexFile)(nil) type countingWriter struct { count int64 } func (c *countingWriter) Write(data []byte) (int, error) { c.count += int64(len(data)) return len(data), nil }
// Copyright 2021 The Cockroach Authors. // // Use of this software is governed by the Business Source License // included in the file licenses/BSL.txt. // // As of the Change Date specified in that file, in accordance with // the Business Source License, use of this software will be governed // by the Apache License, Version 2.0, included in the file // licenses/APL.txt. package sql import ( "context" gosql "database/sql" "math" "net/url" "regexp" "strings" "testing" "github.com/cockroachdb/cockroach/pkg/base" "github.com/cockroachdb/cockroach/pkg/testutils/serverutils" "github.com/cockroachdb/cockroach/pkg/testutils/sqlutils" "github.com/cockroachdb/cockroach/pkg/util/leaktest" "github.com/cockroachdb/cockroach/pkg/util/log" "github.com/cockroachdb/cockroach/pkg/util/log/channel" "github.com/cockroachdb/cockroach/pkg/util/log/logconfig" "github.com/cockroachdb/errors" ) func installSensitiveAccessLogFileSink(sc *log.TestLogScope, t *testing.T) func() { // Enable logging channels. log.TestingResetActive() cfg := logconfig.DefaultConfig() // Make a sink for just the session log. bt := true cfg.Sinks.FileGroups = map[string]*logconfig.FileSinkConfig{ "sql-audit": { CommonSinkConfig: logconfig.CommonSinkConfig{Auditable: &bt}, Channels: logconfig.ChannelList{Channels: []log.Channel{channel.SENSITIVE_ACCESS}}, }} dir := sc.GetDirectory() if err := cfg.Validate(&dir); err != nil { t.Fatal(err) } cleanup, err := log.ApplyConfig(cfg) if err != nil { t.Fatal(err) } return cleanup } // TestAdminAuditLogBasic verifies that after enabling the admin audit log, // a SELECT statement executed by the admin user is logged to the audit log. func TestAdminAuditLogBasic(t *testing.T) { defer leaktest.AfterTest(t)() sc := log.ScopeWithoutShowLogs(t) defer sc.Close(t) cleanup := installSensitiveAccessLogFileSink(sc, t) defer cleanup() s, sqlDB, _ := serverutils.StartServer(t, base.TestServerArgs{}) defer s.Stopper().Stop(context.Background()) db := sqlutils.MakeSQLRunner(sqlDB) db.Exec(t, `SET CLUSTER SETTING sql.log.admin_audit.enabled = true;`) db.Exec(t, `SELECT 1;`) var selectAdminRe = regexp.MustCompile(`"EventType":"admin_query","Statement":"‹SELECT 1›","User":"‹root›"`) log.Flush() entries, err := log.FetchEntriesFromFiles(0, math.MaxInt64, 10000, selectAdminRe, log.WithMarkedSensitiveData) if err != nil { t.Fatal(err) } if len(entries) == 0 { t.Fatal(errors.New("no entries found")) } } // TestAdminAuditLogRegularUser verifies that after enabling the admin audit log, // a SELECT statement executed by the a regular user does not appear in the audit log. func TestAdminAuditLogRegularUser(t *testing.T) { defer leaktest.AfterTest(t)() sc := log.ScopeWithoutShowLogs(t) defer sc.Close(t) cleanup := installSensitiveAccessLogFileSink(sc, t) defer cleanup() s, sqlDB, _ := serverutils.StartServer(t, base.TestServerArgs{}) defer s.Stopper().Stop(context.Background()) db := sqlutils.MakeSQLRunner(sqlDB) db.Exec(t, `SET CLUSTER SETTING sql.log.admin_audit.enabled = true;`) db.Exec(t, `CREATE USER testuser`) pgURL, testuserCleanupFunc := sqlutils.PGUrl( t, s.ServingSQLAddr(), "TestImportPrivileges-testuser", url.User("testuser"), ) defer testuserCleanupFunc() testuser, err := gosql.Open("postgres", pgURL.String()) if err != nil { t.Fatal(err) } defer testuser.Close() if _, err = testuser.Exec(`SELECT 1`); err != nil { t.Fatal(err) } var selectRe = regexp.MustCompile(`SELECT 1`) log.Flush() entries, err := log.FetchEntriesFromFiles(0, math.MaxInt64, 10000, selectRe, log.WithMarkedSensitiveData) if err != nil { t.Fatal(err) } if len(entries) != 0 { t.Fatal(errors.New("unexpected SELECT 1 entry found")) } } // TestAdminAuditLogTransaction verifies that every statement in a transaction // is logged to the admin audit log. func TestAdminAuditLogTransaction(t *testing.T) { defer leaktest.AfterTest(t)() sc := log.ScopeWithoutShowLogs(t) defer sc.Close(t) cleanup := installSensitiveAccessLogFileSink(sc, t) defer cleanup() s, sqlDB, _ := serverutils.StartServer(t, base.TestServerArgs{}) defer s.Stopper().Stop(context.Background()) db := sqlutils.MakeSQLRunner(sqlDB) db.Exec(t, `SET CLUSTER SETTING sql.log.admin_audit.enabled = true;`) db.Exec(t, ` BEGIN; CREATE TABLE t(); SELECT * FROM t; SELECT 1; COMMIT; `) testCases := []struct { name string exp string }{ { "select-1-query", `"EventType":"admin_query","Statement":"‹SELECT 1›"`, }, { "select-*-from-table-query", `"EventType":"admin_query","Statement":"‹SELECT * FROM \"\".\"\".t›"`, }, { "create-table-query", `"EventType":"admin_query","Statement":"‹CREATE TABLE defaultdb.public.t ()›"`, }, } log.Flush() entries, err := log.FetchEntriesFromFiles( 0, math.MaxInt64, 10000, regexp.MustCompile(`"EventType":"admin_query"`), log.WithMarkedSensitiveData, ) if err != nil { t.Fatal(err) } if len(entries) == 0 { t.Fatal(errors.Newf("no entries found")) } for _, tc := range testCases { found := false for _, e := range entries { if !strings.Contains(e.Message, tc.exp) { continue } found = true } if !found { t.Fatal(errors.Newf("no matching entry found for test case %s", tc.name)) } } } // TestAdminAuditLogMultipleTransactions verifies that after enabling the admin // audit log, statements executed in a transaction by a user with admin privilege // are all logged. Once the user loses admin privileges, the statements // should no longer be logged. func TestAdminAuditLogMultipleTransactions(t *testing.T) { defer leaktest.AfterTest(t)() sc := log.ScopeWithoutShowLogs(t) defer sc.Close(t) cleanup := installSensitiveAccessLogFileSink(sc, t) defer cleanup() s, sqlDB, _ := serverutils.StartServer(t, base.TestServerArgs{}) defer s.Stopper().Stop(context.Background()) db := sqlutils.MakeSQLRunner(sqlDB) db.Exec(t, `SET CLUSTER SETTING sql.log.admin_audit.enabled = true;`) db.Exec(t, `CREATE USER testuser`) pgURL, testuserCleanupFunc := sqlutils.PGUrl( t, s.ServingSQLAddr(), "TestImportPrivileges-testuser", url.User("testuser"), ) defer testuserCleanupFunc() testuser, err := gosql.Open("postgres", pgURL.String()) if err != nil { t.Fatal(err) } defer testuser.Close() db.Exec(t, `GRANT admin TO testuser`) if _, err := testuser.Exec(` BEGIN; CREATE TABLE t(); SELECT * FROM t; SELECT 1; COMMIT; `); err != nil { t.Fatal(err) } testCases := []struct { name string exp string }{ { "select-1-query", `"EventType":"admin_query","Statement":"‹SELECT 1›"`, }, { "select-*-from-table-query", `"EventType":"admin_query","Statement":"‹SELECT * FROM \"\".\"\".t›"`, }, { "create-table-query", `"EventType":"admin_query","Statement":"‹CREATE TABLE defaultdb.public.t ()›"`, }, } log.Flush() entries, err := log.FetchEntriesFromFiles( 0, math.MaxInt64, 10000, regexp.MustCompile(`"EventType":"admin_query"`), log.WithMarkedSensitiveData, ) if err != nil { t.Fatal(err) } if len(entries) == 0 { t.Fatal(errors.Newf("no entries found")) } for _, tc := range testCases { found := false for _, e := range entries { if !strings.Contains(e.Message, tc.exp) { continue } found = true } if !found { t.Fatal(errors.Newf("no matching entry found for test case %s", tc.name)) } } // Remove admin from testuser, statements should no longer appear in the // log. db.Exec(t, "REVOKE admin FROM testuser") // SELECT 2 should not appear in the log. if _, err := testuser.Exec(` BEGIN; SELECT 2; COMMIT; `); err != nil { t.Fatal(err) } log.Flush() entries, err = log.FetchEntriesFromFiles( 0, math.MaxInt64, 10000, regexp.MustCompile(`SELECT 2`), log.WithMarkedSensitiveData, ) if err != nil { t.Fatal(err) } if len(entries) != 0 { t.Fatal(errors.Newf("unexpected entries found")) } }
// date: 2019-03-15 package main func main() { }
package main import ( "flag" pb "github.com/lintflow/core/proto" "golang.org/x/net/context" "fmt" "google.golang.org/grpc" "google.golang.org/grpc/grpclog" "io" "strconv" ) var DefaultInspector string = `localhost:4568` var ( uri = flag.String(`repo`, `https://github.com/lintflow/golang-test-project.git`, `your repo with go project for validate here`) ) func main() { flag.Parse() command := flag.Arg(0) // Set up a connection to the lookupd services conn, err := grpc.Dial(DefaultInspector, grpc.WithInsecure()) if err != nil { grpclog.Fatalf("failed to listen inspector services: %v", err) } defer conn.Close() inspector := pb.NewInspectorServiceClient(conn) switch command { case `services`: resp, err := inspector.Services(context.Background(), new(pb.ListRequest)) if err != nil { grpclog.Fatalf("failed get services: %v", err) } else { fmt.Println(`services:`) for _, service := range resp.GetServices() { fmt.Println("\t" + service.String()) } } case `inspect`: resp, err := inspector.Services(context.Background(), new(pb.ListRequest)) task := &pb.Task{} if err != nil { grpclog.Fatalf("failed get services: %v", err) } else { for _, service := range resp.GetServices() { switch service.Type { case pb.Service_LINTER: task.Validators = &pb.Task_Args{Service: service} case pb.Service_REPORTER: task.Reporters = &pb.Task_Args{Service: service} case pb.Service_RESOURCER: task.Resourcers = &pb.Task_Args{ Service: service, Config: []byte(`{"url":"` + *uri + `"}`), } } } } progress, err := inspector.Inspect(context.Background(), task) if err != nil { grpclog.Fatalf("failed start incpect task %s: %v", task, err) } for { info, err := progress.Recv() if err == io.EOF || info == nil { progress.CloseSend() println(`Finish!`) return } if err != nil { grpclog.Fatalf("failed recive data: %v", err) } println("\t", info.Current, `/`, info.Total) if info.Link != "" { println(`see your report here - ` + info.Link) println(`was finded ` + strconv.Itoa(int(info.Problems)) + ` problems in ` + strconv.Itoa(int(info.Total)) + ` files.`) } } } }
package util func Add( a, b int) int { return a + b }
package main import ( "day_daily/day_proficient/day_9/chatroom/server/model" "fmt" "net" "time" ) //处理客户端通信 func process(conn net.Conn) { //这里需要延时关闭 defer conn.Close() processor := &Processor{ Conn : conn, } err := processor.process2() if err != nil { fmt.Println("客户端和服务器的通讯协程错误err: ", err) return } } //编写一个函数,完成对userDao的初始化任务 func initUserDao() { model.MyUserDao = model.NewUserDao(pool) } func main() { //当服务器启动时,我们就初始化我们的redis链接池 initPool("localhost:6379", 16, 0, 300 * time.Second) initUserDao() //提示信息 fmt.Println("服务器在8889端口监听...") listen, err := net.Listen("tcp", "0.0.0.0:8889") if err != nil { fmt.Println("net listen err: ", err) return } //一旦监听成功就等待客户端连接服务器 for { fmt.Println("等待客户端来链接服务器...") conn, err := listen.Accept() if err != nil { fmt.Println("listen Accept err: ", err) } go process(conn) } }
package usecase import ( "github.com/shiv3/slackube/app/adapter/k8s" "github.com/shiv3/slackube/app/adapter/registory/gcr" gcr2 "github.com/shiv3/slackube/app/usecase/gcr" k8susecase "github.com/shiv3/slackube/app/usecase/k8s" ) type UsecasesImpl struct { *k8susecase.K8sUseCaseImpl *gcr2.UseCaseImpl } func NewUsecasesImpl() (*UsecasesImpl, error) { client, err := k8s.NewK8SClientClient() if err != nil { return nil, err } gcrImpl := gcr.NewGcrAdapterImpl("asia.gcr.io") return &UsecasesImpl{ K8sUseCaseImpl: &k8susecase.K8sUseCaseImpl{ K8SAdapter: client, }, UseCaseImpl: gcr2.NewUseCaseImpl(gcrImpl), }, nil }
/* B1 Yönetim Sistemleri Yazılım ve Danışmanlık Ltd. Şti. User : ICI Name : Ibrahim ÇOBANİ Date : 16.08.2019 10:15 Notes : */ package models import ( "encoding/json" "fmt" bolt "go.etcd.io/bbolt" "log" "time" ) type LocationTable struct { Language string `json:"Language"` Version int32 `json:"Version,omitempty"` Key string `json:"Key,omitempty"` Type string `json:"Type,omitempty"` Rank int32 `json:"Rank,omitempty"` LocalizedName string `json:"LocalizedName,omitempty"` EnglishName string `json:"EnglishName,omitempty"` PrimaryPostalCode string `json:"PrimaryPostalCode,omitempty"` RegionID string `json:"region_id"` RegionName string `json:"region_name"` RegionENU string `json:"region_enu"` CountryID string `json:"country_id"` CountryName string `json:"country_name"` CountryENU string `json:"country_enu"` AdministrativeAreaID string `json:"administrative_area_id"` AdministrativeAreaLocalizedName string `json:"administrative_area_localized_name"` AdministrativeAreaNameENU string `json:"administrative_area_name_enu"` TimeZoneCode string `json:"time_zone_code"` TimeZoneName string `json:"time_zone_name"` TimeZoneGMTOffset float32 `json:"time_zone_gmt_offset"` TimeZoneNextOffsetChange time.Time `json:"time_zone_next_offset_change"` TimeZoneIsDaylightSaving bool `json:"time_zone_is_daylight_saving"` GeoPositionLatitude float64 `json:"geo_position_latitude"` GeoPositionLongitude float64 `json:"geo_position_latitude"` } func (this *LocationTable) Save(db *bolt.DB) error { // Store the user model in the user bucket using the username as the key. var key = fmt.Sprintf("%s|%s|%s", this.EnglishName, this.AdministrativeAreaNameENU, this.Language) log.Println(key) err := db.Update(func(tx *bolt.Tx) error { b, err := tx.CreateBucketIfNotExists([]byte("Locations")) if err != nil { return err } encoded, err := json.Marshal(this) if err != nil { return err } return b.Put([]byte(key), encoded) }) return err } func (this *LocationTable) Get(db *bolt.DB) { var key = this.GetPrimaryValue() db.View(func(tx *bolt.Tx) error { b := tx.Bucket([]byte("Locations")) v := b.Get([]byte(key)) err := json.Unmarshal([]byte(v), &this) if err != nil { return err } return nil }) } func (this *LocationTable) Delete(db *bolt.DB) { var key = this.GetPrimaryValue() db.View(func(tx *bolt.Tx) error { b := tx.Bucket([]byte("Locations")) err := b.Delete([]byte(key)) if err != nil { return err } return nil }) } func (this *LocationTable) GetPrimaryValue() string { return fmt.Sprintf("%s|%s|%s", this.EnglishName, this.AdministrativeAreaNameENU, this.Language) }
package metadata_test import ( "net/http" "net/http/httptest" "net/url" "github.com/digitalocean/go-metadata" ) var opts = stubMetadata() func stubMetadata() metadata.ClientOption { srv := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { rw.Write([]byte(`{"interfaces":{"public":[{"ipv4":{"ip_address":"192.168.0.100"}}]}}`)) })) u, err := url.Parse(srv.URL) if err != nil { panic(err) } // the server is not closed since the Example process is about to die anyways. // makes for a cleaner Example in the docs. return metadata.WithBaseURL(u) }
package hash import ( "testing" "github.com/stretchr/testify/assert" ) var ( // Excerpt from `All Watched Over by Machines of Loving Grace` (1967) // by Richard Brautigan poem = []byte(`I like to think (it has to be!) of a cybernetic ecology where we are free of our labors and joined back to nature, returned to our mammal brothers and sisters, and all watched over by machines of loving grace.`) poemDigest = [32]uint8{0x6c, 0x71, 0x46, 0x96, 0xd0, 0xdd, 0x37, 0x4b, 0x39, 0xe, 0xe, 0xe0, 0x61, 0xa1, 0xa, 0xe3, 0x5e, 0x9d, 0x2a, 0x2e, 0x26, 0xa7, 0x93, 0x71, 0xba, 0x15, 0xb2, 0xc, 0x90, 0x4e, 0xcd, 0x81} ) func TestSHA256(t *testing.T) { { msg := "" digest := [32]byte{0xe3, 0xb0, 0xc4, 0x42, 0x98, 0xfc, 0x1c, 0x14, 0x9a, 0xfb, 0xf4, 0xc8, 0x99, 0x6f, 0xb9, 0x24, 0x27, 0xae, 0x41, 0xe4, 0x64, 0x9b, 0x93, 0x4c, 0xa4, 0x95, 0x99, 0x1b, 0x78, 0x52, 0xb8, 0x55} assert.Equal(t, digest, SHA256([]byte(msg))) } { msg := "foo" digest := [32]uint8{0x2c, 0x26, 0xb4, 0x6b, 0x68, 0xff, 0xc6, 0x8f, 0xf9, 0x9b, 0x45, 0x3c, 0x1d, 0x30, 0x41, 0x34, 0x13, 0x42, 0x2d, 0x70, 0x64, 0x83, 0xbf, 0xa0, 0xf9, 0x8a, 0x5e, 0x88, 0x62, 0x66, 0xe7, 0xae} assert.Equal(t, digest, SHA256([]byte(msg))) } { assert.Equal(t, poemDigest, SHA256(poem)) } } func BenchmarkGolibbySHA256(b *testing.B) { for n := 0; n < b.N; n++ { _ = SHA256(poem) } }
package pipe type Pipelines []Pipeline type Stream struct { nodes []Pipeline } func New() *Stream { return &Stream{} } // Use appends a pipeline processor to the Stream pipeline stack. func (s *Stream) Use(nodes ...Pipeline) { s.nodes = append(s.nodes, nodes...) } // chain builds a Connector composed of an inline pipeline stack and endpoint // processor in the order they are passed. func chain(nodes []Pipeline, src Connector) Connector { c := nodes[0](src) for i := 1; i < len(nodes); i++ { c = nodes[i](c) } return c } // Handle registers a source and maps it to a sink. func (s *Stream) Handle(src Source, dest Sink) { dest(chain(s.nodes, src())) }
package finddisappearednumbers import ( "reflect" "testing" ) func TestFindDisappearedNumbers(t *testing.T) { var result, expect []int result = findDisappearedNumbers([]int{4, 3, 2, 7, 8, 2, 3, 1}) expect = []int{5, 6} if reflect.DeepEqual(result, expect) != true { t.Errorf("Get %v, Expect %v", result, expect) } }
package client import ( "errors" "fmt" "github.com/kuaidaili/golang-sdk/api-sdk/kdl/endpoint" "github.com/kuaidaili/golang-sdk/api-sdk/kdl/signtype" "github.com/kuaidaili/golang-sdk/api-sdk/kdl/utils" ) // GetKps 获取独享代理 // return: 代理slice func (client Client) GetKps(num int, signType signtype.SignType, kwargs map[string]interface{}) ([]string, error) { ep := endpoint.GetKpsProxy if kwargs != nil { kwargs["num"] = num } else { kwargs = map[string]interface{}{"num": num} } params := client.getParams(ep, signType, kwargs) res, err := client.getBaseRes("GET", ep, params) if err != nil { if res.Code == 1043 { // format 不为json, 将原始字符串放入[]string并返回 return []string{res.Msg}, nil } return []string{}, err } if data, ok := res.Data.(map[string]interface{}); ok { if count, ok := data["count"].(float64); ok && count == 0 { return []string{}, nil } else if count > 0 { if proxies, ok := data["proxy_list"].([]interface{}); ok { var ips []string for _, v := range proxies { ips = append(ips, utils.TypeSwitcher(v)) } return ips, nil } return []string{}, nil } } return []string{}, errors.New("KdlError: fail to parse response data: " + fmt.Sprint(res.Data)) }
// Copyright 2021 The ChromiumOS Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package firmware import ( "context" "github.com/golang/protobuf/ptypes" "github.com/golang/protobuf/ptypes/empty" "github.com/golang/protobuf/ptypes/wrappers" "google.golang.org/grpc" "chromiumos/tast/common/firmware/serial" "chromiumos/tast/errors" pb "chromiumos/tast/services/cros/firmware" "chromiumos/tast/testing" ) func init() { testing.AddService(&testing.Service{ Register: func(srv *grpc.Server, s *testing.ServiceState) { pb.RegisterSerialPortServiceServer(srv, &SerialPortService{s: s}) }, }) } // SerialPortService implements tast.cros.firmware.SerialPortService type SerialPortService struct { s *testing.ServiceState ports map[uint32]serial.Port nextPort uint32 } // Open handles the Open rpc call. func (s *SerialPortService) Open(ctx context.Context, in *pb.SerialPortConfig) (*pb.PortId, error) { testing.ContextLog(ctx, "Opening service port") readTimeout, err := ptypes.Duration(in.GetReadTimeout()) if err != nil { return nil, errors.Wrap(err, "converting ReadTimeout") } p, err := serial.NewConnectedPortOpener(in.GetName(), int(in.GetBaud()), readTimeout).OpenPort(ctx) if err != nil { return nil, err } if s.ports == nil { s.ports = make(map[uint32]serial.Port) s.nextPort = 1 } id := s.nextPort s.nextPort++ s.ports[id] = p return &pb.PortId{Value: id}, nil } func (s *SerialPortService) getPort(id uint32) (serial.Port, error) { if s.ports == nil { return nil, errors.New("no ports have been opened") } p, ok := s.ports[id] if !ok { return nil, errors.Errorf("port %d not found", id) } return p, nil } // Read handles the Read rpc call. func (s *SerialPortService) Read(ctx context.Context, in *pb.SerialReadRequest) (*wrappers.BytesValue, error) { p, err := s.getPort(in.GetId().GetValue()) if err != nil { return nil, err } buf := make([]byte, in.GetMaxLen()) readLen, err := p.Read(ctx, buf) if err != nil { return nil, err } return &wrappers.BytesValue{Value: buf[:readLen]}, err } // Write handles the Write rpc call. func (s *SerialPortService) Write(ctx context.Context, in *pb.SerialWriteRequest) (*wrappers.Int64Value, error) { p, err := s.getPort(in.GetId().GetValue()) if err != nil { return nil, err } n, err := p.Write(ctx, in.GetBuffer()) if err != nil { return nil, err } return &wrappers.Int64Value{Value: int64(n)}, err } // Flush handles the Flush rpc call. func (s *SerialPortService) Flush(ctx context.Context, in *pb.PortId) (*empty.Empty, error) { p, err := s.getPort(in.GetValue()) if err != nil { return nil, err } return &empty.Empty{}, p.Flush(ctx) } // Close handles the Close rpc call. func (s *SerialPortService) Close(ctx context.Context, in *pb.PortId) (*empty.Empty, error) { id := in.GetValue() p, err := s.getPort(id) if err != nil { return nil, err } if err = p.Close(ctx); err != nil { return nil, err } delete(s.ports, id) return &empty.Empty{}, nil }
package sort import ( "reflect" "testing" ) type res struct { l1 *ListNode l2 *ListNode exp *ListNode } func buildWithSlice(a []int) *ListNode { var h, c *ListNode for _, v := range a { n := &ListNode{v, nil} if c != nil { c.Next = n } if h == nil { h = n } c = n } return h } func TestMergeTwoLists(t *testing.T) { cases := []res{ res{nil, nil, nil}, res{nil, buildWithSlice([]int{5}), buildWithSlice([]int{5})}, res{buildWithSlice([]int{1, 4, 6}), buildWithSlice([]int{5}), buildWithSlice([]int{1, 4, 5, 6})}, } for _, c := range cases { ret := MergeTwoLists(c.l1, c.l2) if !reflect.DeepEqual(ret, c.exp) { t.Errorf("expected %v but got %v with input %v,%v", c.exp, ret, c.l1, c.l2) } } t.Log("passed") }
// Copyright 2022 The ChromiumOS Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Package enterprisecuj contains the test code for enterprise CUJ. package enterprisecuj import ( "context" "time" "chromiumos/tast/common/perf" "chromiumos/tast/ctxutil" "chromiumos/tast/errors" cx "chromiumos/tast/local/bundles/cros/spera/enterprisecuj/citrix" "chromiumos/tast/local/chrome" "chromiumos/tast/local/chrome/browser" "chromiumos/tast/local/chrome/cuj" "chromiumos/tast/local/chrome/uiauto" "chromiumos/tast/local/chrome/uiauto/faillog" "chromiumos/tast/local/input" "chromiumos/tast/local/ui/cujrecorder" "chromiumos/tast/testing" ) // TestParams stores data common to the tests run in this package. type TestParams struct { OutDir string CitrixUserName string CitrixPassword string CitrixServerURL string DesktopName string TabletMode bool TestMode cx.TestMode DataPath func(string) string UIHandler cuj.UIActionHandler } // Run runs the enterprisecuj test. func Run(ctx context.Context, cr *chrome.Chrome, scenario CitrixScenario, p *TestParams) (retErr error) { const desktopTitle = "VDA" cleanupCtx := ctx ctx, cancel := ctxutil.Shorten(ctx, 15*time.Second) defer cancel() tconn, err := cr.TestAPIConn(ctx) if err != nil { return errors.Wrap(err, "failed to create test API connection") } kb, err := input.Keyboard(ctx) if err != nil { return errors.Wrap(err, "failed to open the keyboard") } defer kb.Close() // Give 10 seconds to set initial settings. It is critical to ensure // cleanupSetting can be executed with a valid context so it has its // own cleanup context from other cleanup functions. This is to avoid // other cleanup functions executed earlier to use up the context time. cleanupSettingsCtx := ctx ctx, cancel = ctxutil.Shorten(ctx, 10*time.Second) defer cancel() cleanupSetting, err := cuj.InitializeSetting(ctx, tconn) if err != nil { return errors.Wrap(err, "failed to set initial settings") } defer cleanupSetting(cleanupSettingsCtx) testing.ContextLog(ctx, "Start to get browser start time") _, browserStartTime, err := cuj.GetBrowserStartTime(ctx, tconn, true, p.TabletMode, browser.TypeAsh) if err != nil { return errors.Wrap(err, "failed to get browser start time") } options := cujrecorder.NewPerformanceCUJOptions() recorder, err := cujrecorder.NewRecorder(ctx, cr, tconn, nil, options) if err != nil { return errors.Wrap(err, "failed to create a recorder") } defer recorder.Close(cleanupCtx) if err := cuj.AddPerformanceCUJMetrics(browser.TypeAsh, tconn, nil, recorder); err != nil { return errors.Wrap(err, "failed to add metrics to recorder") } citrix := cx.NewCitrix(tconn, kb, p.DataPath, desktopTitle, p.TabletMode, p.TestMode) if err := uiauto.NamedCombine("open and login citrix", citrix.Open(), citrix.Login(p.CitrixServerURL, p.CitrixUserName, p.CitrixPassword), )(ctx); err != nil { return errors.Wrap(err, "failed to login Citrix") } defer citrix.Close(ctx) defer faillog.DumpUITreeWithScreenshotOnError(ctx, p.OutDir, func() bool { return retErr != nil }, cr, "ui_dump") if err := recorder.Run(ctx, func(ctx context.Context) error { return scenario.Run(ctx, tconn, kb, citrix, p) }); err != nil { return errors.Wrap(err, "failed to run the clinician workstation cuj") } if p.TestMode == cx.RecordMode { if err := citrix.SaveRecordFile(ctx, p.OutDir); err != nil { return err } } pv := perf.NewValues() pv.Set(perf.Metric{ Name: "Browser.StartTime", Unit: "ms", Direction: perf.SmallerIsBetter, }, float64(browserStartTime.Milliseconds())) appStartTime := citrix.AppStartTime() if appStartTime > 0 { pv.Set(perf.Metric{ Name: "Apps.StartTime", Unit: "ms", Direction: perf.SmallerIsBetter, }, float64(appStartTime)) } if err := recorder.Record(ctx, pv); err != nil { return errors.Wrap(err, "failed to record") } if err = pv.Save(p.OutDir); err != nil { return errors.Wrap(err, "failed to store values") } if err := recorder.SaveHistograms(p.OutDir); err != nil { return errors.Wrap(err, "failed to save histogram raw data") } return nil }
package app import ( "context" "encoding/json" "fmt" "io" "net/http" "github.com/MakeNowJust/heredoc" go_version "github.com/hashicorp/go-version" "github.com/spf13/viper" "github.com/dikaeinstein/godl/internal/pkg/version" "github.com/dikaeinstein/godl/pkg/text" ) type Asset struct { Name string `json:"name"` } type Release struct { TagName string `json:"tag_name"` Assets []Asset `json:"assets"` } type ListReleasesResult []Release type ListReleasesErrorResp struct { Message string `json:"message"` DocumentationURL string `json:"documentation_url"` } // Update checks for if there are updates available for Godl type Update struct { Client *http.Client Output io.Writer } func (u *Update) Run(ctx context.Context, currentVersion string) error { exists, latest, err := u.CheckForUpdate(ctx, currentVersion) if err != nil { return err } if exists { fmt.Fprint(u.Output, heredoc.Docf(` %s The latest version is %s. You can update by downloading from https://github.com/dikaeinstein/godl/releases `, text.Red("Your version of Godl is out of date!"), latest.TagName)) } else { fmt.Fprintln(u.Output, "No update available.") } return nil } func (u *Update) CheckForUpdate(ctx context.Context, currentVersion string) (bool, *Release, error) { url := "https://api.github.com/repos/dikaeinstein/godl/releases?per_page=10" releases, err := u.fetchReleaseList(ctx, url) if err != nil { return false, nil, err } // Only a single version exists or no version :) const minNumOfRelease = 2 if len(releases) < minNumOfRelease { return false, nil, nil } // pick latest release r := releases[0] latest := version.Segments(go_version.Must(go_version.NewSemver(r.TagName))) current := version.Segments(go_version.Must(go_version.NewSemver(currentVersion))) return latest.GreaterThan(current), &r, nil } func (u *Update) fetchReleaseList(ctx context.Context, url string) (ListReleasesResult, error) { req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, http.NoBody) if err != nil { return nil, err } req.Header.Set("Accept", "application/vnd.github.v3+json") req.Header.Set("User-Agent", "godl") ghToken := viper.GetString("gh_token") if ghToken != "" { req.Header.Set("Authorization", fmt.Sprintf("token %s", ghToken)) } res, err := u.Client.Do(req) if err != nil { return nil, err } defer res.Body.Close() if res.StatusCode != http.StatusOK && res.StatusCode != http.StatusNotFound { var errResp ListReleasesErrorResp // using io.ReadAll because res.Body is very small data, err := io.ReadAll(res.Body) if err != nil { return nil, err } err = json.Unmarshal(data, &errResp) if err != nil { return nil, err } return nil, fmt.Errorf("%s: %v %v", url, res.StatusCode, errResp.Message) } var releases ListReleasesResult err = json.NewDecoder(res.Body).Decode(&releases) if err != nil { return nil, err } return releases, nil }
package configmap import ( "context" "testing" "github.com/stretchr/testify/require" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/types" "k8s.io/utils/pointer" ctrlclient "sigs.k8s.io/controller-runtime/pkg/client" "github.com/tilt-dev/tilt/internal/controllers/fake" "github.com/tilt-dev/tilt/pkg/apis/core/v1alpha1" ) const configMapName = "fe-disable" const configMap2Name = "be-disable" const key = "isDisabled" func TestMaybeNewDisableStatusNoSource(t *testing.T) { f := newDisableFixture(t) newStatus, err := MaybeNewDisableStatus(f.ctx, f.fc, nil, nil) require.NoError(t, err) require.NotNil(t, newStatus) require.Equal(t, false, newStatus.Disabled) require.Equal(t, v1alpha1.DisableStateEnabled, newStatus.State) require.Contains(t, newStatus.Reason, "does not specify a DisableSource") } func TestMaybeNewDisableStatusNoConfigMapDisableSource(t *testing.T) { f := newDisableFixture(t) newStatus, err := MaybeNewDisableStatus(f.ctx, f.fc, &v1alpha1.DisableSource{}, nil) require.NoError(t, err) require.NotNil(t, newStatus) require.Equal(t, true, newStatus.Disabled) require.Equal(t, v1alpha1.DisableStateError, newStatus.State) require.Contains(t, newStatus.Reason, "specifies no valid sources") } func TestMaybeNewDisableStatusNoConfigMap(t *testing.T) { f := newDisableFixture(t) newStatus, err := MaybeNewDisableStatus(f.ctx, f.fc, disableSource(), nil) require.NoError(t, err) require.NotNil(t, newStatus) require.Equal(t, true, newStatus.Disabled) require.Equal(t, v1alpha1.DisableStatePending, newStatus.State) require.Contains(t, newStatus.Reason, "ConfigMap \"fe-disable\" does not exist") } func TestMaybeNewDisableStatusNoKey(t *testing.T) { f := newDisableFixture(t) f.createConfigMap(nil) newStatus, err := MaybeNewDisableStatus(f.ctx, f.fc, disableSource(), nil) require.NoError(t, err) require.NotNil(t, newStatus) require.Equal(t, true, newStatus.Disabled) require.Equal(t, v1alpha1.DisableStateError, newStatus.State) require.Contains(t, newStatus.Reason, "has no key") } func TestMaybeNewDisableStatusTrue(t *testing.T) { f := newDisableFixture(t) f.createConfigMap(pointer.StringPtr("true")) newStatus, err := MaybeNewDisableStatus(f.ctx, f.fc, disableSource(), nil) require.NoError(t, err) require.NotNil(t, newStatus) require.Equal(t, true, newStatus.Disabled) require.Equal(t, v1alpha1.DisableStateDisabled, newStatus.State) require.Contains(t, newStatus.Reason, "is true") } func TestMaybeNewDisableStatusFalse(t *testing.T) { f := newDisableFixture(t) f.createConfigMap(pointer.StringPtr("false")) newStatus, err := MaybeNewDisableStatus(f.ctx, f.fc, disableSource(), nil) require.NoError(t, err) require.NotNil(t, newStatus) require.Equal(t, false, newStatus.Disabled) require.Equal(t, v1alpha1.DisableStateEnabled, newStatus.State) require.Contains(t, newStatus.Reason, "is false") } func TestMaybeNewDisableStatusEveryTrue(t *testing.T) { f := newDisableFixture(t) f.createConfigMapNamed(configMapName, pointer.StringPtr("true")) f.createConfigMapNamed(configMap2Name, pointer.StringPtr("true")) newStatus, err := MaybeNewDisableStatus(f.ctx, f.fc, everyDisableSource(), nil) require.NoError(t, err) require.NotNil(t, newStatus) require.Equal(t, true, newStatus.Disabled) require.Equal(t, v1alpha1.DisableStateDisabled, newStatus.State) require.Contains(t, newStatus.Reason, "Every ConfigMap disabled") } func TestMaybeNewDisableStatusEveryMixed(t *testing.T) { f := newDisableFixture(t) f.createConfigMapNamed(configMapName, pointer.StringPtr("true")) f.createConfigMapNamed(configMap2Name, pointer.StringPtr("false")) newStatus, err := MaybeNewDisableStatus(f.ctx, f.fc, everyDisableSource(), nil) require.NoError(t, err) require.NotNil(t, newStatus) require.Equal(t, false, newStatus.Disabled) require.Equal(t, v1alpha1.DisableStateEnabled, newStatus.State) require.Contains(t, newStatus.Reason, "is false") } func TestMaybeNewDisableStatusGobbledygookValue(t *testing.T) { f := newDisableFixture(t) f.createConfigMap(pointer.StringPtr("asdf")) newStatus, err := MaybeNewDisableStatus(f.ctx, f.fc, disableSource(), nil) require.NoError(t, err) require.NotNil(t, newStatus) require.Equal(t, true, newStatus.Disabled) require.Equal(t, v1alpha1.DisableStateError, newStatus.State) require.Contains(t, newStatus.Reason, "strconv.ParseBool: parsing \"asdf\"") } func TestMaybeNewDisableStatusNoChange(t *testing.T) { f := newDisableFixture(t) f.createConfigMap(pointer.StringPtr("false")) status, err := MaybeNewDisableStatus(f.ctx, f.fc, disableSource(), nil) require.NoError(t, err) newStatus, err := MaybeNewDisableStatus(f.ctx, f.fc, disableSource(), status) require.NoError(t, err) require.Same(t, status, newStatus) } func TestMaybeNewDisableStatusChange(t *testing.T) { f := newDisableFixture(t) f.createConfigMap(pointer.StringPtr("false")) status, err := MaybeNewDisableStatus( f.ctx, f.fc, disableSource(), nil, ) require.NoError(t, err) f.updateConfigMap(pointer.StringPtr("true")) newStatus, err := MaybeNewDisableStatus(f.ctx, f.fc, disableSource(), status) require.NoError(t, err) require.NotSame(t, status, newStatus) } type disableFixture struct { t *testing.T fc ctrlclient.Client ctx context.Context } func (f *disableFixture) createConfigMap(isDisabled *string) { f.createConfigMapNamed(configMapName, isDisabled) } func (f *disableFixture) createConfigMapNamed(name string, isDisabled *string) { m := make(map[string]string) if isDisabled != nil { m[key] = *isDisabled } err := f.fc.Create(f.ctx, &v1alpha1.ConfigMap{ ObjectMeta: metav1.ObjectMeta{ Name: name, }, Data: m, }) require.NoError(f.t, err) } func (f *disableFixture) updateConfigMap(isDisabled *string) { m := make(map[string]string) if isDisabled != nil { m[key] = *isDisabled } var cm v1alpha1.ConfigMap err := f.fc.Get(f.ctx, types.NamespacedName{Name: configMapName}, &cm) require.NoError(f.t, err) cm.Data = m err = f.fc.Update(f.ctx, &cm) require.NoError(f.t, err) } func disableSource() *v1alpha1.DisableSource { return &v1alpha1.DisableSource{ ConfigMap: &v1alpha1.ConfigMapDisableSource{ Name: configMapName, Key: key, }, } } func everyDisableSource() *v1alpha1.DisableSource { return &v1alpha1.DisableSource{ EveryConfigMap: []v1alpha1.ConfigMapDisableSource{ { Name: configMapName, Key: key, }, { Name: configMap2Name, Key: key, }, }, } } func newDisableFixture(t *testing.T) *disableFixture { fc := fake.NewFakeTiltClient() ctx := context.Background() return &disableFixture{ t: t, fc: fc, ctx: ctx, } }
// Copyright 2018 The Cockroach Authors. // // Use of this software is governed by the Business Source License // included in the file licenses/BSL.txt. // // As of the Change Date specified in that file, in accordance with // the Business Source License, use of this software will be governed // by the Apache License, Version 2.0, included in the file // licenses/APL.txt. package split import ( "bytes" "math" "time" "github.com/cockroachdb/cockroach/pkg/roachpb" ) // Load-based splitting. // // - Engage split for ranges: // - With size exceeding min-range-bytes // - with reqs/s rate over a configurable threshold // - Disengage when a range no longer meets the criteria // - During split: // - Record start time // - Keep a sample of 10 keys // - Each sample contains three counters: left, right and contained. // - On each span, increment the left and/or right counters, depending // on whether the span falls entirely to the left, to the right. // If exactly on the key, increment neither. // - If the span overlaps with the key, increment the contained counter. // - When a sample is replaced, discard its counters. // - If a range is on for more than a threshold interval: // - Examine sample for the smallest diff between left and right counters, // excluding any whose counters are not sufficiently advanced; // If not less than some constant threshold, skip split. // - Use the contained counters to give lower priority to potential split // points that have more requests that span over it. // - If a desired point is reached, add range to split queue with the chosen // key as split key, and provide hint to scatter the replicas. const ( // RecordDurationThreshold is the minimum duration of time the split finder // will record a range for, before being ready for a split. RecordDurationThreshold = 10 * time.Second // 10s splitKeySampleSize = 20 // size of split key sample splitKeyMinCounter = 100 // min aggregate counters before consideration splitKeyThreshold = 0.25 // 25% difference between left/right counters splitKeyContainedThreshold = 0.50 // too many spanning queries over split point ) type sample struct { key roachpb.Key left, right, contained int } // Finder is a structure that is used to determine the split point // using the Reservoir Sampling method. type Finder struct { startTime time.Time samples [splitKeySampleSize]sample count int } // NewFinder initiates a Finder with the given time. func NewFinder(startTime time.Time) *Finder { return &Finder{ startTime: startTime, } } // Ready checks if the Finder has been initialized with a sufficient // sample duration. func (f *Finder) Ready(nowTime time.Time) bool { return nowTime.Sub(f.startTime) > RecordDurationThreshold } // Record informs the Finder about where the span lies with // regard to the keys in the samples. func (f *Finder) Record(span roachpb.Span, intNFn func(int) int) { if f == nil { return } var idx int count := f.count f.count++ if count < splitKeySampleSize { idx = count } else if idx = intNFn(count); idx >= splitKeySampleSize { // Increment all existing keys' counters. for i := range f.samples { if span.ProperlyContainsKey(f.samples[i].key) { f.samples[i].contained++ } else { // If the split is chosen to be here and the key is on or to the left // of the start key of the span, we know that the request the span represents // - would be isolated to the right of the split point. // Similarly, if the split key is greater than the start key of the span // (and given that it is not properly contained by the span) it must mean // that the request the span represents would be on the left. if comp := bytes.Compare(f.samples[i].key, span.Key); comp <= 0 { f.samples[i].right++ } else if comp > 0 { f.samples[i].left++ } } } return } // Note we always use the start key of the span. We could // take the average of the byte slices, but that seems // unnecessarily complex for practical usage. f.samples[idx] = sample{key: span.Key} } // Key finds an appropriate split point based on the Reservoir sampling method. // Returns a nil key if no appropriate key was found. func (f *Finder) Key() roachpb.Key { if f == nil { return nil } var bestIdx = -1 var bestScore float64 = 2 for i, s := range f.samples { if s.left+s.right+s.contained < splitKeyMinCounter { continue } balanceScore := math.Abs(float64(s.left-s.right)) / float64(s.left+s.right) containedScore := (float64(s.contained) / float64(s.left+s.right+s.contained)) finalScore := balanceScore + containedScore if balanceScore >= splitKeyThreshold || containedScore >= splitKeyContainedThreshold { continue } if finalScore < bestScore { bestIdx = i bestScore = finalScore } } if bestIdx == -1 { return nil } return f.samples[bestIdx].key }
package spanner import ( "context" "reflect" "time" lib_errors "github.com/tomwangsvc/lib-svc/errors" lib_json "github.com/tomwangsvc/lib-svc/json" lib_log "github.com/tomwangsvc/lib-svc/log" lib_misc "github.com/tomwangsvc/lib-svc/misc" ) type CarCustomerAssociation struct { CarId string `json:"car_id" spanner:"car_id"` CustomerId string `json:"customer_id" spanner:"customer_id"` DateCreated time.Time `json:"date_created" spanner:"date_created"` DateRentalEnd time.Time `json:"date_rental_end" spanner:"date_rental_end"` DateRentalStart time.Time `json:"date_rental_start" spanner:"DateRentalStart"` DateUpdated time.Time `json:"date_updated" spanner:"date_updated"` Test bool `json:"test" spanner:"test"` } var ( CarCustomerAssociationColumns = lib_misc.StructTaggedFieldNames(reflect.TypeOf(CarCustomerAssociation{}), "spanner") CarCustomerAssociationFieldMetaData = lib_json.StructFieldMetadata(reflect.TypeOf(CarCustomerAssociation{})) ) const ( tableCarCustomerAssociation = "car_customer_association" ) var () func (c client) TransformBrandClassAssociationToJson(ctx context.Context, carCustomerAssociation CarCustomerAssociation) ([]byte, error) { lib_log.Info(ctx, "Transforming", lib_log.FmtAny("carCustomerAssociation", carCustomerAssociation)) carCustomerAssociationListJson, err := lib_json.GenerateJson(carCustomerAssociation, CarCustomerAssociationFieldMetaData, "") if err != nil { return nil, lib_errors.Wrap(err, "Failed generating json list") } lib_log.Info(ctx, "Transformed", lib_log.FmtInt("len(carCustomerAssociationListJson)", len(carCustomerAssociationListJson))) return carCustomerAssociationListJson, nil } func (c client) TransformBrandClassAssociationsToJson(ctx context.Context, carCustomerAssociations []CarCustomerAssociation) ([]byte, error) { lib_log.Info(ctx, "Transforming", lib_log.FmtInt("len(carCustomerAssociations)", len(carCustomerAssociations))) if len(carCustomerAssociations) == 0 { lib_log.Info(ctx, "Transformed") return nil, nil } var carCustomerAssociationsList []interface{} for _, v := range carCustomerAssociationsList { carCustomerAssociationsList = append(carCustomerAssociationsList, v) } carCustomerAssociationsListJson, err := lib_json.GenerateJsonList(carCustomerAssociationsList, CarCustomerAssociationFieldMetaData, "") if err != nil { return nil, lib_errors.Wrap(err, "Failed generating json list") } lib_log.Info(ctx, "Transformed", lib_log.FmtInt("len(carCustomerAssociationsListJson)", len(carCustomerAssociationsListJson))) return carCustomerAssociationsListJson, nil }
package service import ( "fmt" "github.com/thisiserico/golabox/domain" ) func (srv *Service) GetOrder(oID domain.OrderId) (*domain.Order, error) { order := srv.queryRepo.GetOrder(oID) if order == nil { return nil, fmt.Errorf("Non existing order %s", oID) } return order, nil }
package server import ( "fmt" "mall/app/api/admin/user/conf" "mall/app/api/admin/user/model" "mall/app/api/admin/user/service" serviceUserModel "mall/app/service/main/user/model" "mall/lib/net/http/middleware/auth" "mall/lib/net/http/middleware/cors" "github.com/gin-gonic/gin" "github.com/jinzhu/gorm" ) var svr *service.Service func initUser() { _, err := svr.QueryUser(model.UserQuery{Username: "amdin"}) if err == gorm.ErrRecordNotFound { admin := serviceUserModel.RegisterParam{ Username: "admin", Pwd: "123456", } if err := svr.Register(admin); err != nil { fmt.Println(err.Error()) } } } func Init(c *conf.Config) { svr = service.New() initUser() r := gin.Default() router(r, c) r.Run(fmt.Sprintf(":%s", c.Http.Port)) } func router(r *gin.Engine, c *conf.Config) { r.Use(cors.Cors()) authMiddleware := auth.New(c.Auth) authMiddleware.PayloadFunc = auth.PayloadFunc authMiddleware.IdentityHandler = auth.IdentityHandler authMiddleware.Authenticator = Authenticator authMiddleware.Unauthorized = Unauthorized r.POST("/login", authMiddleware.LoginHandler) r.POST("/register", register) r.Use(authMiddleware.MiddlewareFunc()) r.GET("/info", info) r.POST("/list", userList) r.POST("/changeStatus/:uid", changeState) r.POST("/select/:uid", selectUser) r.POST("/update", updateUser) }
// Copyright 2016 The Cockroach Authors. // // Use of this software is governed by the Business Source License // included in the file licenses/BSL.txt. // // As of the Change Date specified in that file, in accordance with // the Business Source License, use of this software will be governed // by the Apache License, Version 2.0, included in the file // licenses/APL.txt. // teamcity-trigger launches a variety of nightly build jobs on TeamCity using // its REST API. It is intended to be run from a meta-build on a schedule // trigger. // // One might think that TeamCity would support scheduling the same build to run // multiple times with different parameters, but alas. The feature request has // been open for ten years: https://youtrack.jetbrains.com/issue/TW-6439 package main import ( "fmt" "log" "os" "time" "github.com/abourget/teamcity" "github.com/cockroachdb/cockroach/pkg/cmd/cmdutil" "github.com/kisielk/gotool" ) func main() { if len(os.Args) != 1 { fmt.Fprintf(os.Stderr, "usage: %s\n", os.Args[0]) os.Exit(1) } branch := cmdutil.RequireEnv("TC_BUILD_BRANCH") serverURL := cmdutil.RequireEnv("TC_SERVER_URL") username := cmdutil.RequireEnv("TC_API_USER") password := cmdutil.RequireEnv("TC_API_PASSWORD") tcClient := teamcity.New(serverURL, username, password) runTC(func(buildID string, opts map[string]string) { build, err := tcClient.QueueBuild(buildID, branch, opts) if err != nil { log.Fatalf("failed to create teamcity build (buildID=%s, branch=%s, opts=%+v): %s", build, branch, opts, err) } log.Printf("created teamcity build (buildID=%s, branch=%s, opts=%+v): %s", buildID, branch, opts, build) }) } const baseImportPath = "github.com/cockroachdb/cockroach/pkg/" var importPaths = gotool.ImportPaths([]string{baseImportPath + "..."}) func runTC(queueBuild func(string, map[string]string)) { // Queue stress builds. One per configuration per package. for _, importPath := range importPaths { // By default, run each package for up to 100 iterations. maxRuns := 100 // By default, run each package for up to 1h. maxTime := 1 * time.Hour // By default, fail the stress run on the first test failure. maxFails := 1 // By default, a single test times out after 40 minutes. testTimeout := 40 * time.Minute // The stress program by default runs as many instances in parallel as there // are CPUs. Each instance itself can run tests in parallel. The amount of // parallelism needs to be reduced, or we can run into OOM issues, // especially for race builds and/or logic tests (see // https://github.com/cockroachdb/cockroach/pull/10966). // // We limit both the stress program parallelism and the go test parallelism // to 4 for non-race builds and 2 for race builds. For logic tests, we // halve these values. parallelism := 4 opts := map[string]string{ "env.PKG": importPath, } // Conditionally override settings. switch importPath { case baseImportPath + "kv/kvnemesis": // Disable -maxruns for kvnemesis. Run for the full 1h. maxRuns = 0 opts["env.COCKROACH_KVNEMESIS_STEPS"] = "10000" case baseImportPath + "sql/logictest": // Stress logic tests with reduced parallelism (to avoid overloading the // machine, see https://github.com/cockroachdb/cockroach/pull/10966). parallelism /= 2 // Increase logic test timeout. testTimeout = 2 * time.Hour maxTime = 3 * time.Hour } opts["env.TESTTIMEOUT"] = testTimeout.String() // Run non-race build. opts["env.GOFLAGS"] = fmt.Sprintf("-parallel=%d", parallelism) opts["env.STRESSFLAGS"] = fmt.Sprintf("-maxruns %d -maxtime %s -maxfails %d -p %d", maxRuns, maxTime, maxFails, parallelism) queueBuild("Cockroach_Nightlies_Stress", opts) // Run race build. With run with -p 1 to avoid overloading the machine. noParallelism := 1 opts["env.GOFLAGS"] = fmt.Sprintf("-race -parallel=%d", parallelism) opts["env.STRESSFLAGS"] = fmt.Sprintf("-maxruns %d -maxtime %s -maxfails %d -p %d", maxRuns, maxTime, maxFails, noParallelism) queueBuild("Cockroach_Nightlies_Stress", opts) } }
//go:generate protoc -I ./rpc --go_out=plugins=grpc:./rpc ./rpc/chat.proto package main import ( "log" "net" pb "./protobufs" "fmt" "golang.org/x/net/context" "google.golang.org/grpc" "google.golang.org/grpc/reflection" "os" ) const defaultPort = ":50051" func main() { port := getEnv("PORT", defaultPort) lis, err := net.Listen("tcp", port) if err != nil { log.Fatalf("failed to listen: %v", err) } server := grpc.NewServer() pb.RegisterChatServer(server, &chat{}) reflection.Register(server) if err := server.Serve(lis); err != nil { log.Fatalf("failed to serve: %v", err) } } func getEnv(envName string, defaults string) string { val := os.Getenv(envName) if val == "" { return defaults } return val } type chat struct{} var subscribers = map[pb.Chat_SubscribeServer]*pb.User{} func (s *chat) Subscribe(subscriber *pb.User, stream pb.Chat_SubscribeServer) error { stream.Send(&pb.Reply{fmt.Sprintf("Greetings %s! Feel free to chat here.", subscriber.Name)}) notifyAllSubs(pb.Reply{fmt.Sprintf("%s joined the chat!", subscriber.Name)}) subscribers[stream] = subscriber defer delete(subscribers, stream) defer notifyAllSubs(pb.Reply{fmt.Sprintf("%s left the chat.", subscriber.Name)}) <-stream.Context().Done() // Waiting channel to be closed by client log.Printf("Closing %s's channel.", subscriber.Name) return nil } func (s *chat) SendMessage(ctx context.Context, message *pb.Message) (*pb.Reply, error) { log.Printf("Got message from %s: %s", message.User.Name, message.Text) msg := fmt.Sprintf("%s: %s", message.User.Name, message.Text) notifyAllSubs(pb.Reply{Message: msg}) msg = fmt.Sprintf("Received message from %s \"%s\"", message.User.Name, message.Text) return &pb.Reply{Message: msg}, nil } func notifyAllSubs(msg pb.Reply) { for stream, user := range subscribers { err := stream.Send(&msg) if err != nil { log.Printf("Failed send message to %s. Reason: %s", user.Name, err) } } }
package apiserver import ( "github.com/fission/fission-workflows/pkg/api" "github.com/fission/fission-workflows/pkg/api/aggregates" "github.com/fission/fission-workflows/pkg/api/store" "github.com/fission/fission-workflows/pkg/fes" "github.com/fission/fission-workflows/pkg/types" "github.com/fission/fission-workflows/pkg/types/validate" "github.com/golang/protobuf/ptypes/empty" "golang.org/x/net/context" ) // Workflow is responsible for all functionality related to managing workflows. type Workflow struct { api *api.Workflow store *store.Workflows backend fes.Backend } func NewWorkflow(api *api.Workflow, store *store.Workflows, backend fes.Backend) *Workflow { return &Workflow{ api: api, store: store, backend: backend, } } func (ga *Workflow) Create(ctx context.Context, spec *types.WorkflowSpec) (*types.ObjectMetadata, error) { id, err := ga.api.Create(spec, api.WithContext(ctx)) if err != nil { return nil, toErrorStatus(err) } return &types.ObjectMetadata{Id: id}, nil } func (ga *Workflow) Get(ctx context.Context, workflowID *types.ObjectMetadata) (*types.Workflow, error) { wf, err := ga.store.GetWorkflow(workflowID.GetId()) if err != nil { return nil, toErrorStatus(err) } return wf, nil } func (ga *Workflow) Delete(ctx context.Context, workflowID *types.ObjectMetadata) (*empty.Empty, error) { err := ga.api.Delete(workflowID.GetId()) if err != nil { return nil, toErrorStatus(err) } return &empty.Empty{}, nil } func (ga *Workflow) List(ctx context.Context, req *empty.Empty) (*WorkflowList, error) { var results []string wfs := ga.store.List() for _, result := range wfs { results = append(results, result.Id) } return &WorkflowList{results}, nil } func (ga *Workflow) Validate(ctx context.Context, spec *types.WorkflowSpec) (*empty.Empty, error) { err := validate.WorkflowSpec(spec) if err != nil { return nil, toErrorStatus(err) } return &empty.Empty{}, nil } func (ga *Workflow) Events(ctx context.Context, md *types.ObjectMetadata) (*ObjectEvents, error) { events, err := ga.backend.Get(fes.Aggregate{ Id: md.Id, Type: aggregates.TypeWorkflow, }) if err != nil { return nil, toErrorStatus(err) } return &ObjectEvents{ Metadata: md, Events: events, }, nil }
package tyVpnServer import ( "crypto/tls" "fmt" "github.com/tachyon-protocol/udw/tyTlsPacketDebugger" "github.com/tachyon-protocol/udw/tyVpnProtocol" "github.com/tachyon-protocol/udw/udwBinary" "github.com/tachyon-protocol/udw/udwBytes" "github.com/tachyon-protocol/udw/udwLog" "github.com/tachyon-protocol/udw/udwTlsSelfSignCertV2" "net" "sync" "time" ) type vpnClient struct { id uint64 vpnIpOffset int vpnIp net.IP connLock sync.Mutex connToClient net.Conn connRelaySide net.Conn connLastRwTimeLock sync.Mutex connLastRwTime time.Time } func (s *Server) gcClientThread() { go func() { for { time.Sleep(time.Minute * 5) s.lock.Lock() now := time.Now() for _, client := range s.clientMap { client.connLastRwTimeLock.Lock() t := client.connLastRwTime client.connLastRwTimeLock.Unlock() if now.Sub(t) < time.Minute*15 { continue } udwLog.Log("[dzr1zb5e3wz] gc remove client", client.id) if s.clientMap != nil { delete(s.clientMap, client.id) } s.vpnIpList[client.vpnIpOffset] = nil client.connLock.Lock() if client.connToClient != nil { _ = client.connToClient.Close() } if client.connRelaySide != nil { _ = client.connRelaySide.Close() } client.connLock.Unlock() } s.lock.Unlock() } }() } func (vc *vpnClient) getConnToClient() net.Conn { vc.connLock.Lock() conn := vc.connToClient vc.connLock.Unlock() return conn } func (s *Server) getClient(clientId uint64) *vpnClient { s.lock.Lock() if s.clientMap == nil { s.clientMap = map[uint64]*vpnClient{} } client := s.clientMap[clientId] s.lock.Unlock() if client != nil { client.connLastRwTimeLock.Lock() client.connLastRwTime = time.Now() client.connLastRwTimeLock.Unlock() } return client } func (s *Server) newOrUpdateClientFromDirectConn(clientId uint64, connToClient net.Conn) { s.lock.Lock() if s.clientMap == nil { s.clientMap = map[uint64]*vpnClient{} } client := s.clientMap[clientId] if client != nil { client.connLock.Lock() client.connToClient = connToClient //reconnect client.connLock.Unlock() s.lock.Unlock() return } client = &vpnClient{ id: clientId, connToClient: connToClient, } s.clientMap[client.id] = client err := s.clientAllocateVpnIp_NoLock(client) s.lock.Unlock() if err != nil { panic("[ub4fm53v26] " + err.Error()) } return } func (s *Server) getOrNewClientFromRelayConn(clientId uint64) *vpnClient { s.lock.Lock() if s.clientMap == nil { s.clientMap = map[uint64]*vpnClient{} } client := s.clientMap[clientId] if client != nil { s.lock.Unlock() return client } client = &vpnClient{ id: clientId, } left, right := tyVpnProtocol.NewInternalConnectionDual(func() { s.lock.Lock() delete(s.clientMap, clientId) s.lock.Unlock() }, nil) right = tls.Server(right, &tls.Config{ Certificates: []tls.Certificate{ //TODO optimize allocate *udwTlsSelfSignCertV2.GetTlsCertificate(), }, NextProtos: []string{"http/1.1"}, MinVersion: tls.VersionTLS12, }) client.connToClient = right client.connRelaySide = left s.clientMap[client.id] = client err := s.clientAllocateVpnIp_NoLock(client) go s.clientTcpConnHandle(client.getConnToClient()) s.lock.Unlock() if err != nil { panic("[ub4fm53v26] " + err.Error()) } go func() { vpnPacket := &tyVpnProtocol.VpnPacket{ Cmd: tyVpnProtocol.CmdForward, ClientIdSender: s.clientId, ClientIdReceiver: clientId, } buf := make([]byte, 16*1024) bufW := udwBytes.NewBufWriter(nil) for { n, err := client.connRelaySide.Read(buf) if err != nil { udwLog.Log("[cz2xvv1smx] close conn", err) _ = client.connRelaySide.Close() return } if tyVpnProtocol.Debug { fmt.Println("read from connRelaySide write to relayConn", vpnPacket.ClientIdSender, "->", vpnPacket.ClientIdReceiver) if tyVpnProtocol.Debug { tyTlsPacketDebugger.Dump("---", buf[:n]) } } vpnPacket.Data = buf[:n] bufW.Reset() vpnPacket.Encode(bufW) err = udwBinary.WriteByteSliceWithUint32LenNoAllocV2(s.getRelayConn(), bufW.GetBytes()) //TODO lock if err != nil { udwLog.Log("[ar1nr4wf3s]", err) continue } } }() return client }
package main //Valid //The block of if can shadow the init variables func f () { if a:=0; a < 10 { a := "gg" } else { } }
package main import ( "fmt" ) // 汉诺塔游戏 // n个盘子 start() end() temp() // n-1 start -> end -> temp // start -> end // n-1 temp -> start -> end // 终止条件 1 -> start -> end func tower(start string, end string, temp string, layer int) { if (layer == 1) { fmt.Println(start, "->", end) return } tower(start, temp, end, layer-1) fmt.Println(start, "->", end) tower(temp, end, start, layer -1) } func main() { tower("塔1","塔3","塔2",3) }
package pp import ( "context" "fmt" "cloud.google.com/go/bigquery" ) func RunQuery(ctx context.Context, projectID string, query string) error { // Создаём клиента для BigQuery client, err := bigquery.NewClient(ctx, projectID) if err != nil { return fmt.Errorf("bigquery.NewClient: %v", err) } // Вызываем query _, err = client.Query(query).Run(ctx) if err != nil { return fmt.Errorf("client.Query.Run: %v", err) } // Закрываем клиента и выходим _ = client.Close() return nil }
package problem0206 // ListNode is a struct type ListNode struct { Val int Next *ListNode } func reverseList(head *ListNode) *ListNode { var prev, curr *ListNode curr = head for curr != nil { nextTemp := curr.Next curr.Next = prev prev = curr curr = nextTemp } return prev }
/* * Copyright 2018, Oath Inc. * Licensed under the terms of the MIT license. See LICENSE file in the project root for terms. */ package config import ( "fmt" "log" "regexp" ) var endpointPattern = regexp.MustCompile(`^(\S+?)://(.*)$`) var addressPattern = regexp.MustCompile(`^(\S+):(\d+)$`) type Endpoint interface { Protocol() string String() string IsHttp() bool } type RawEndpoint interface { Endpoint Address() string } type HttpEndpoint interface { Endpoint Url() string } type EndpointData struct { protocol string } type RawEndpointData struct { EndpointData address string } type HttpEndpointData struct { EndpointData url string } func (e *RawEndpointData) String() string { return fmt.Sprintf("%s", e.address) } func (e *HttpEndpointData) String() string { return fmt.Sprintf("%s", e.url) } func (e *EndpointData) Protocol() string { return e.protocol } func (e *EndpointData) IsHttp() bool { return isHttp(e.Protocol()) } func isHttp(protocol string) bool { return protocol == "http" || protocol == "https" } func (e *RawEndpointData) Address() string { return e.address } func (e *HttpEndpointData) Url() string { return e.url } func ParseEndpoint(str string) Endpoint { match := endpointPattern.FindStringSubmatch(str) if match == nil || len(match) != 3 { log.Panicf("Endpoint malformed: '%s'", str) } protocol := match[1] address := match[2] if isHttp(protocol) { return CreateHttp(protocol, str) } else { return CreateRaw(protocol, address) } } func CreateRaw(protocol string, address string) RawEndpoint { match := addressPattern.FindStringSubmatch(address) if match == nil || len(match) != 3 { log.Panicf("Address malformed: '%s'", address) } return &RawEndpointData{EndpointData{protocol}, address} } func CreateHttp(protocol string, url string) HttpEndpoint { return &HttpEndpointData{EndpointData{protocol}, url} }
package interfaces import ( "github.com/aswinda/notifyme/application/api/models" ) type IUserRepository interface { GetUserDetail(userId int) (models.UserModel, error) }
package main import ( "./handler" "fmt" "log" "net/http" ) func staticDirHandler(mux *http.ServeMux, prefix string, staticDir string) { mux.HandleFunc(prefix, func(w http.ResponseWriter, r *http.Request) { file := staticDir + r.URL.Path[len(prefix)-1:] fmt.Println(file) http.ServeFile(w, r, file) }) } func main() { mux := http.NewServeMux() staticDirHandler(mux, "/assets/", "./static") mux.HandleFunc("/index", handler.IndexHandler) mux.HandleFunc("/book/create", handler.AddBookHandler) mux.HandleFunc("/book/borrow", handler.BorrowBookHandler) mux.HandleFunc("/book/note/create", handler.BookNoteHandler) mux.HandleFunc("/user/login", handler.LoginHandler) mux.HandleFunc("/user/register", handler.RegisterHandler) mux.HandleFunc("/user/logout", handler.LogOutHandler) mux.HandleFunc("/feed", handler.LoginHandler) mux.HandleFunc("/book_shop", handler.BookShopShowHandler) mux.HandleFunc("/book_shops", handler.UsersShowHandler) mux.HandleFunc("/my_shop", handler.ProfileHandler) mux.HandleFunc("/about", handler.LoginHandler) log.Fatal(http.ListenAndServe("0.0.0.0:80", mux)) }
package client import ( "fmt" "testing" "github.com/stretchr/testify/assert" v1 "k8s.io/api/core/v1" "github.com/G-Research/armada/pkg/api" ) func TestCreateChunkedSubmitRequests(t *testing.T) { requestItems := createJobRequestItems(MaxJobsPerRequest + 1) result := CreateChunkedSubmitRequests("queue", "jobsetid", requestItems) assert.Equal(t, len(result), 2) assert.Equal(t, len(result[0].JobRequestItems), MaxJobsPerRequest) assert.Equal(t, len(result[1].JobRequestItems), 1) } func TestCreateChunkedSubmitRequests_MaintainsOrderOfJobs(t *testing.T) { requestItems := createJobRequestItems(MaxJobsPerRequest + 1) result := CreateChunkedSubmitRequests("queue", "jobsetid", requestItems) position := 0 for _, request := range result { for i := 0; i < len(request.JobRequestItems); i++ { assert.Equal(t, request.JobRequestItems[i], requestItems[position]) position++ } } } func createJobRequestItems(numberOfItems int) []*api.JobSubmitRequestItem { requestItems := make([]*api.JobSubmitRequestItem, 0, numberOfItems) for i := 0; i < numberOfItems; i++ { requestItem := &api.JobSubmitRequestItem{ Priority: 0, PodSpec: &v1.PodSpec{ Containers: []v1.Container{ { Name: fmt.Sprintf("Container%d", i), }, }, }, } requestItems = append(requestItems, requestItem) } return requestItems }
package main import ( "fmt" ) func main() { v1 := struct { doors int price int lux bool }{ doors: 4, price: 100000, lux: false, } fmt.Println(v1) }
package utils import ( "net/http" "io/ioutil" "encoding/json" "encoding/xml" "fmt" "strings" ) func RemoteFile (url string, headers map[string]string, body map[string]interface{}) []byte { client := &http.Client{} req, err := http.NewRequest("POST", url, strings.NewReader( MapToUrl(body) )) PanicIf(err, "Error creating new request") if body != nil {req.Header.Add("Content-Type", "application/x-www-form-urlencoded")} for k, v := range headers {req.Header.Add(k, v)} x, err := client.Do(req) PanicIf(err, "HTTP Request error") defer x.Body.Close() if x.StatusCode != http.StatusOK { panic( fmt.Errorf("Response Status error: %v", x.StatusCode) )} data, err := ioutil.ReadAll(x.Body) PanicIf(err, "Failed to read body") return data } func LocalFile (path string) []byte { res, err := ioutil.ReadFile( Fmt("data/{0}", path) ) PanicIf(err, "Failed to read file") return []byte(res) } func FromJson (res interface{}, file []byte) { PanicIf(json.Unmarshal(file, res), "Failed to parse json")} func FromXml (res interface{}, file []byte) { PanicIf(xml.Unmarshal(file, res), "Failed to parse xml")}
package main import "fmt" import "os" import "reflect" type Node struct { Value int Left *Node Right *Node } func insert(curr *Node, val int) *Node { if curr == nil { return &Node{Value: val} } if val == curr.Value { return curr } else if val > curr.Value { curr.Right = insert(curr.Right, val) } else { curr.Left = insert(curr.Left, val) } return curr } func inorder(curr *Node, agg []int) []int { if curr == nil { return agg } agg = inorder(curr.Left, agg) agg = append(agg, curr.Value) agg = inorder(curr.Right, agg) return agg } func preorder(curr *Node, agg []int) []int { if curr == nil { return agg } agg = append(agg, curr.Value) agg = preorder(curr.Left, agg) agg = preorder(curr.Right, agg) return agg } func postorder(curr *Node, agg []int) []int { if curr == nil { return agg } agg = postorder(curr.Left, agg) agg = postorder(curr.Right, agg) agg = append(agg, curr.Value) return agg } func main() { var head *Node = insert(nil, 5) insert(head, 3) insert(head, 7) insert(head, 11) insert(head, 1) insert(head, 4) insert(head, 20) var resp []int = inorder(head, []int{}) var inorder_arr = []int{1, 3, 4, 5, 7, 11, 20} if !reflect.DeepEqual(resp, inorder_arr) { fmt.Println("Inorder %v ", resp) os.Exit(-1) } resp = preorder(head, []int{}) var preorder_arr = []int{5, 3, 1, 4, 7, 11, 20} if !reflect.DeepEqual(resp, preorder_arr) { fmt.Println("Preorder %v ", resp) os.Exit(-1) } resp = postorder(head, []int{}) var postorder_arr = []int{1, 4, 3, 20, 11, 7, 5} if !reflect.DeepEqual(resp, postorder_arr) { fmt.Println("Postorder %v ", resp) os.Exit(-1) } fmt.Println("everything worked") }
// Copyright (C) 2017 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package scanner_test import ( "fmt" "testing" "github.com/google/gapid/core/assert" "github.com/google/gapid/gapis/stringtable/minidown/scanner" "github.com/google/gapid/gapis/stringtable/minidown/token" ) var source = `# This is a H1 heading` type tok struct{ Text, Kind string } func TestScanner(t *testing.T) { assert := assert.To(t) B := func() tok { return tok{"*", "token.Bullet"} } H := func(t string) tok { return tok{t, "token.Heading"} } E := func(t string) tok { return tok{t, "token.Emphasis"} } T := func(t string) tok { return tok{t, "token.Text"} } TAG := func(t string) tok { return tok{"{{" + t + "}}", "token.Tag"} } OB := func(r rune) tok { return tok{string([]rune{r}), "token.OpenBracket"} } CB := func(r rune) tok { return tok{string([]rune{r}), "token.CloseBracket"} } NL := func() tok { return tok{"\n", "token.NewLine"} } for _, test := range []struct { source string expected []tok }{ {`Some basic-text ¢ 12 34`, []tok{T("Some"), T("basic-text"), T("¢"), T("12"), T("34")}}, {`# A H1 heading`, []tok{H("#"), T("A"), T("H1"), T("heading")}}, {`## A H2 heading`, []tok{H("##"), T("A"), T("H2"), T("heading")}}, {`A ### H3 heading`, []tok{T("A"), H("###"), T("H3"), T("heading")}}, {` Multi whitespace `, []tok{T("Multi"), T("whitespace")}}, {`An *emphasised* _string_`, []tok{T("An"), E("*"), T("emphasised"), E("*"), E("_"), T("string"), E("_")}}, {`Not an * emphasised * _ string _`, []tok{ T("Not"), T("an"), B(), T("emphasised"), B(), T("_"), T("string"), T("_"), }}, {`this_is__not_emphasised`, []tok{T("this_is__not_emphasised")}}, {`this*bit is*emphasised`, []tok{T("this"), E("*"), T("bit"), T("is"), E("*"), T("emphasised")}}, {`_*__**nested emphasis**__*_`, []tok{ E("_"), E("*"), E("__"), E("**"), T("nested"), T("emphasis"), E("**"), E("__"), E("*"), E("_"), }}, {`Some text split over several ` + "\r\nlines", []tok{T("Some"), T("text"), NL(), T("split"), T("over"), T("several"), NL(), NL(), T("lines")}}, {`{here's [some] (brackets)}`, []tok{ OB('{'), T("here's"), OB('['), T("some"), CB(']'), OB('('), T("brackets"), CB(')'), CB('}'), }}, {`{{these}} {{are}} {{t_a_g_s_111}}`, []tok{ TAG("these"), TAG("are"), TAG("t_a_g_s_111"), }}, {`[{{person}}]({{link}}) likes to use [google](http://www.google.com).`, []tok{ OB('['), TAG("person"), CB(']'), OB('('), TAG("link"), CB(')'), T("likes"), T("to"), T("use"), OB('['), T("google"), CB(']'), OB('('), T("http://www.google.com"), CB(')'), T("."), }}, {`\[This\] \\ \*has \*escaped\{\} characters`, []tok{ T("["), T("This"), T("]"), T("\\"), T("*"), T("has"), T("*"), T("escaped"), T("{"), T("}"), T("characters"), }}, {`This is a slash \\. This is a slash \. and so is this \`, []tok{ T("This"), T("is"), T("a"), T("slash"), T("\\"), T("."), T("This"), T("is"), T("a"), T("slash"), T("\\"), T("."), T("and"), T("so"), T("is"), T("this"), T("\\"), }}, {`\[{{Tag_in_brackets}}\]`, []tok{ T("["), TAG("Tag_in_brackets"), T("]"), }}, } { tokens, errs := scanner.Scan("test", test.source) assert.For(test.source).ThatSlice(errs).IsEmpty() got := make([]tok, len(tokens)) for i, t := range tokens { switch t := t.(type) { case token.Text: got[i] = tok{t.String(), fmt.Sprintf("%T", t)} default: got[i] = tok{t.CST().Tok().String(), fmt.Sprintf("%T", t)} } } assert.For(test.source).That(got).DeepEquals(test.expected) } }
// gopup.go // a go implementation of a pack unpack utility for byte buffers
// Copyright 2018 The Cockroach Authors. // // Use of this software is governed by the Business Source License // included in the file licenses/BSL.txt. // // As of the Change Date specified in that file, in accordance with // the Business Source License, use of this software will be governed // by the Apache License, Version 2.0, included in the file // licenses/APL.txt. package main import ( "bytes" "context" "io/ioutil" "regexp" "sort" "strings" "testing" "time" "github.com/cockroachdb/cockroach/pkg/testutils" "github.com/cockroachdb/cockroach/pkg/util/syncutil" "github.com/cockroachdb/cockroach/pkg/util/version" "github.com/kr/pretty" ) const OwnerUnitTest Owner = `unittest` const defaultParallelism = 10 func TestMatchOrSkip(t *testing.T) { testCases := []struct { filter []string name string tags []string expected bool expectedSkip string }{ {nil, "foo", nil, true, ""}, {nil, "foo", []string{"bar"}, true, "[tag:default] does not match [bar]"}, {[]string{"tag:b"}, "foo", []string{"bar"}, true, ""}, {[]string{"tag:b"}, "foo", nil, true, "[tag:b] does not match [default]"}, {[]string{"tag:default"}, "foo", nil, true, ""}, {[]string{"tag:f"}, "foo", []string{"bar"}, true, "[tag:f] does not match [bar]"}, {[]string{"f"}, "foo", []string{"bar"}, true, "[tag:default] does not match [bar]"}, {[]string{"f"}, "bar", []string{"bar"}, false, ""}, {[]string{"f", "tag:b"}, "foo", []string{"bar"}, true, ""}, {[]string{"f", "tag:f"}, "foo", []string{"bar"}, true, "[tag:f] does not match [bar]"}, } for _, c := range testCases { t.Run("", func(t *testing.T) { f := newFilter(c.filter) spec := &testSpec{Name: c.name, Owner: OwnerUnitTest, Tags: c.tags} if value := spec.matchOrSkip(f); c.expected != value { t.Fatalf("expected %t, but found %t", c.expected, value) } else if value && c.expectedSkip != spec.Skip { t.Fatalf("expected %s, but found %s", c.expectedSkip, spec.Skip) } }) } } func nilLogger() *logger { lcfg := loggerConfig{ stdout: ioutil.Discard, stderr: ioutil.Discard, } l, err := lcfg.newLogger("" /* path */) if err != nil { panic(err) } return l } func TestRunnerRun(t *testing.T) { ctx := context.Background() r, err := makeTestRegistry() if err != nil { t.Fatal(err) } r.Add(testSpec{ Name: "pass", Owner: OwnerUnitTest, Run: func(ctx context.Context, t *test, c *cluster) {}, Cluster: makeClusterSpec(0), }) r.Add(testSpec{ Name: "fail", Owner: OwnerUnitTest, Run: func(ctx context.Context, t *test, c *cluster) { t.Fatal("failed") }, Cluster: makeClusterSpec(0), }) testCases := []struct { filters []string expErr string }{ {nil, "some tests failed"}, {[]string{"pass"}, ""}, {[]string{"fail"}, "some tests failed"}, {[]string{"pass|fail"}, "some tests failed"}, {[]string{"pass", "fail"}, "some tests failed"}, {[]string{"notests"}, "no test"}, } for _, c := range testCases { t.Run("", func(t *testing.T) { tests := testsToRun(ctx, r, newFilter(c.filters)) cr := newClusterRegistry() runner := newTestRunner(cr, r.buildVersion) lopt := loggingOpt{ l: nilLogger(), tee: noTee, stdout: ioutil.Discard, stderr: ioutil.Discard, artifactsDir: "", } copt := clustersOpt{ typ: roachprodCluster, user: "test_user", cpuQuota: 1000, keepClustersOnTestFailure: false, } err := runner.Run(ctx, tests, 1, /* count */ defaultParallelism, copt, "" /* artifactsDir */, lopt) if !testutils.IsError(err, c.expErr) { t.Fatalf("expected err: %q, but found %v. Filters: %s", c.expErr, err, c.filters) } }) } } type syncedBuffer struct { mu syncutil.Mutex buf bytes.Buffer } func (b *syncedBuffer) Write(p []byte) (n int, err error) { b.mu.Lock() defer b.mu.Unlock() return b.buf.Write(p) } func (b *syncedBuffer) String() string { b.mu.Lock() defer b.mu.Unlock() return b.buf.String() } func TestRunnerTestTimeout(t *testing.T) { ctx := context.Background() cr := newClusterRegistry() runner := newTestRunner(cr, version.Version{}) var buf syncedBuffer lopt := loggingOpt{ l: nilLogger(), tee: noTee, stdout: &buf, stderr: &buf, artifactsDir: "", } copt := clustersOpt{ typ: roachprodCluster, user: "test_user", cpuQuota: 1000, keepClustersOnTestFailure: false, } test := testSpec{ Name: `timeout`, Owner: OwnerUnitTest, Timeout: 10 * time.Millisecond, Cluster: makeClusterSpec(0), Run: func(ctx context.Context, t *test, c *cluster) { <-ctx.Done() }, } err := runner.Run(ctx, []testSpec{test}, 1, /* count */ defaultParallelism, copt, "" /* artifactsDir */, lopt) if !testutils.IsError(err, "some tests failed") { t.Fatalf("expected error \"some tests failed\", got: %v", err) } out := buf.String() timeoutRE := regexp.MustCompile(`(?m)^.*test timed out \(.*\)$`) if !timeoutRE.MatchString(out) { t.Fatalf("unable to find \"timed out\" message:\n%s", out) } } func TestRegistryPrepareSpec(t *testing.T) { dummyRun := func(context.Context, *test, *cluster) {} var listTests = func(t *testSpec) []string { return []string{t.Name} } testCases := []struct { spec testSpec expectedErr string expectedTests []string }{ { testSpec{ Name: "a", Owner: OwnerUnitTest, Run: dummyRun, Cluster: makeClusterSpec(0), }, "", []string{"a"}, }, { testSpec{ Name: "a", Owner: OwnerUnitTest, MinVersion: "v2.1.0", Run: dummyRun, Cluster: makeClusterSpec(0), }, "", []string{"a"}, }, { testSpec{ Name: "a", Owner: OwnerUnitTest, MinVersion: "foo", Run: dummyRun, Cluster: makeClusterSpec(0), }, "a: unable to parse min-version: invalid version string 'foo'", nil, }, } for _, c := range testCases { t.Run("", func(t *testing.T) { r, err := makeTestRegistry() if err != nil { t.Fatal(err) } err = r.prepareSpec(&c.spec) if !testutils.IsError(err, c.expectedErr) { t.Fatalf("expected %q, but found %q", c.expectedErr, err.Error()) } if c.expectedErr == "" { tests := listTests(&c.spec) sort.Strings(tests) if diff := pretty.Diff(c.expectedTests, tests); len(diff) != 0 { t.Fatalf("unexpected tests:\n%s", strings.Join(diff, "\n")) } } }) } } func TestRegistryMinVersion(t *testing.T) { ctx := context.Background() testCases := []struct { buildVersion string expectedA bool expectedB bool expErr string }{ {"v1.1.0", false, false, "no test matched filters"}, {"v2.0.0", true, false, ""}, {"v2.1.0", true, true, ""}, } for _, c := range testCases { t.Run(c.buildVersion, func(t *testing.T) { var runA, runB bool r, err := makeTestRegistry() if err != nil { t.Fatal(err) } r.Add(testSpec{ Name: "a", Owner: OwnerUnitTest, MinVersion: "v2.0.0", Cluster: makeClusterSpec(0), Run: func(ctx context.Context, t *test, c *cluster) { runA = true }, }) r.Add(testSpec{ Name: "b", Owner: OwnerUnitTest, MinVersion: "v2.1.0", Cluster: makeClusterSpec(0), Run: func(ctx context.Context, t *test, c *cluster) { runB = true }, }) if err := r.setBuildVersion(c.buildVersion); err != nil { t.Fatal(err) } tests := testsToRun(ctx, r, newFilter(nil)) var buf syncedBuffer lopt := loggingOpt{ l: nilLogger(), tee: noTee, stdout: &buf, stderr: &buf, artifactsDir: "", } copt := clustersOpt{ typ: roachprodCluster, user: "test_user", cpuQuota: 1000, keepClustersOnTestFailure: false, } cr := newClusterRegistry() runner := newTestRunner(cr, r.buildVersion) err = runner.Run(ctx, tests, 1, /* count */ defaultParallelism, copt, "" /* artifactsDir */, lopt) if !testutils.IsError(err, c.expErr) { t.Fatalf("expected err: %q, got: %v", c.expErr, err) } if c.expectedA != runA || c.expectedB != runB { t.Fatalf("expected %t,%t, but got %t,%t\n%s", c.expectedA, c.expectedB, runA, runB, buf.String()) } }) } }
package webhooks type List struct { Meta struct { Count int `json:"count"` PageCount int `json:"pageCount"` TotalCount int `json:"totalCount"` Next interface{} `json:"next"` Previous interface{} `json:"previous"` Self string `json:"self"` First string `json:"first"` Last string `json:"last"` } `json:"meta"` Data []struct { ID int `json:"id"` Event string `json:"event"` Target string `json:"target"` Enabled bool `json:"enabled"` Conditions []struct { Key string `json:"key"` Condition string `json:"condition"` Value string `json:"value"` } `json:"conditions"` } `json:"data"` } type Retrieve struct { Data struct { ID int `json:"id"` Event string `json:"event"` Target string `json:"target"` Enabled bool `json:"enabled"` Conditions []struct { Key string `json:"key"` Condition string `json:"condition"` Value string `json:"value"` } `json:"conditions"` } `json:"data"` } type CreateBody struct { Event string `json:"event"` Target string `json:"target"` Enabled string `json:"enabled"` Conditions []Condition `json:"Conditions"` } type Create struct { Data struct { ID int `json:"id"` Event string `json:"event"` Target string `json:"target"` Token string `json:"token"` Enabled bool `json:"enabled"` Conditions []struct { Key string `json:"key"` Condition string `json:"condition"` Value string `json:"value"` } `json:"conditions"` } `json:"data"` }