text
stringlengths
11
4.05M
package main import ( "fmt" ) func catMouseGame(graph [][]int) int { N := len(graph) dp := make([][][]int, N) for i := range graph { dp[i] = make([][]int, N) for j := range graph { dp[i][j] = make([]int, N+N) for k := range dp[i][j] { dp[i][j][k] = -1 } } } return whoWins(graph, 1, 2, 0, dp) } func whoWins(graph [][]int, mouse, cat, turn int, dp [][][]int) int { if turn >= 2*len(graph) { return 0 } if dp[mouse][cat][turn] < 0 { if turn%2 == 0 { // mouse results := make([]int, 0, len(graph[mouse])) mouseWin := false for _, next := range graph[mouse] { if next == cat { continue } if next == 0 { mouseWin = true dp[mouse][cat][turn] = 1 break } results = append(results, whoWins(graph, next, cat, turn+1, dp)) } if !mouseWin { dp[mouse][cat][turn] = 2 for _, r := range results { if r == 0 { dp[mouse][cat][turn] = 0 break } } for _, r := range results { if r == 1 { dp[mouse][cat][turn] = 1 break } } } } else { // cat results := make([]int, 0, len(graph[cat])) catWin := false for _, next := range graph[cat] { if next == 0 { continue } if next == mouse { catWin = true dp[mouse][cat][turn] = 2 break } results = append(results, whoWins(graph, mouse, next, turn+1, dp)) } if !catWin { dp[mouse][cat][turn] = 1 for _, r := range results { if r == 0 { dp[mouse][cat][turn] = 0 break } } for _, r := range results { if r == 2 { dp[mouse][cat][turn] = 2 break } } } } } return dp[mouse][cat][turn] } func main() { fmt.Println("abc") graph := [][]int{{2, 5}, {3}, {0, 4, 5}, {1, 4, 5}, {2, 3}, {0, 2, 3}} a := catMouseGame(graph) fmt.Println(a) }
package main import ( "time" c "github.com/dlapiduz/govcode.org/common" "github.com/go-martini/martini" "github.com/martini-contrib/cors" "github.com/martini-contrib/gzip" "github.com/martini-contrib/render" ) func main() { m := App() m.Run() } func App() *martini.ClassicMartini { m := martini.Classic() m.Use(gzip.All()) m.Use(render.Renderer(render.Options{ Directory: "templates", })) m.Use(cors.Allow(&cors.Options{ AllowAllOrigins: true, })) m.Group("/repos", func(r martini.Router) { r.Get("", ReposIndex) r.Get("/:name", ReposShow) }) m.Group("/orgs", func(r martini.Router) { r.Get("", OrgsIndex) r.Get("/:id", OrgsShow) }) m.Group("/users", func(r martini.Router) { r.Get("", UserIndex) r.Get("/:id", UserShow) }) m.Get("/stats", StatsIndex) return m } func ReposIndex(r render.Render) { var results []c.Repository rows := c.DB.Table("repositories") rows = rows.Select(`repositories.*, organizations.login as organization_login, coalesce(date_part('day', now() - last_pull), -1) as days_since_pull, coalesce(date_part('day', now() - last_commit), -1) as days_since_commit `) rows = rows.Joins("inner join organizations on organizations.id = repositories.organization_id") rows.Scan(&results) r.JSON(200, results) } func ReposShow(r render.Render, params martini.Params) { var repo c.Repository c.DB.Where("name = ?", params["name"]).First(&repo) c.DB.Model(&repo).Related(&repo.Organization) c.DB.Model(&repo).Related(&repo.RepoStat) r.JSON(200, repo) } func OrgsIndex(r render.Render) { var results []c.Organization c.DB.Find(&results) r.JSON(200, results) } func OrgsShow(r render.Render, params martini.Params) { var result c.Organization c.DB.Where("id = ?", params["id"]).First(&result) r.JSON(200, result) } func UserIndex(r render.Render) { var results []c.User c.DB.Find(&results) r.JSON(200, results) } func UserShow(r render.Render, params martini.Params) { var result c.User c.DB.Where("id = ?", params["id"]).First(&result) r.JSON(200, result) } func StatsIndex(r render.Render) { // Get the repo counts per org type repoCount struct { OrganizationLogin string RepoCount int64 } var repo_counts []repoCount rows := c.DB.Table("repositories") rows = rows.Select(`organizations.login as organization_login, count(repositories.name) as repo_count `) rows = rows.Joins("inner join organizations on organizations.id = repositories.organization_id") rows = rows.Group("organizations.login") rows = rows.Order("repo_count desc") rows.Scan(&repo_counts) // Get commit stats per org per month for the past year type orgStat struct { OrganizationLogin string Week time.Time Month string Add int64 Del int64 Commits int64 } var org_stats []orgStat rows = c.DB.Debug().Table("repo_stats") rows = rows.Select(`organizations.login as organization_login, min(repo_stats.week) as week, TO_CHAR(repo_stats.week, 'Mon YYYY') as month, sum(repo_stats.add) as add, sum(repo_stats.del) as del, sum(repo_stats.commits) as commits `) rows = rows.Joins(`inner join repositories on repositories.id = repo_stats.repository_id inner join organizations on organizations.id = repositories.organization_id `) rows = rows.Where("repo_stats.week > now()::date - 365") rows = rows.Group("organizations.login, month") rows = rows.Order("week") rows.Scan(&org_stats) var result map[string]interface{} result = make(map[string]interface{}) result["repo_counts"] = repo_counts result["org_stats"] = org_stats r.JSON(200, result) }
package base58 import ( "testing" "github.com/c2nc/gosys/crypto/uuid" ) var ( uid []byte token string encoder = Ripple ) // generate shorted UUID in base58 enconding func generateToken() string { return Encode(uuid.GenerateBytesUUID(), encoder) } func BenchmarkEncode(b *testing.B) { for i := 1; i < b.N; i++ { _ = generateToken() } } func TestEncode(t *testing.T) { uid = uuid.GenerateBytesUUID() t.Logf("Generated UUID: %s", uuid.StringFromUUID(uid)) token = Encode(uid, encoder) t.Logf("Generated token: %s", token) } func TestDecode(t *testing.T) { b, err := Decode(token, encoder) if err != nil { t.Fatalf("Decode base58 error: %v", err) } t.Logf("Decoded UID: %s", uuid.StringFromUUID(b)) }
// Copyright 2021 Google LLC. All Rights Reserved. // // 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 server import ( "context" "github.com/GoogleCloudPlatform/declarative-resource-client-library/dcl" emptypb "github.com/GoogleCloudPlatform/declarative-resource-client-library/python/proto/empty_go_proto" gkemulticloudpb "github.com/GoogleCloudPlatform/declarative-resource-client-library/python/proto/gkemulticloud/gkemulticloud_go_proto" "github.com/GoogleCloudPlatform/declarative-resource-client-library/services/google/gkemulticloud" ) // Server implements the gRPC interface for AzureCluster. type AzureClusterServer struct{} // ProtoToAzureClusterStateEnum converts a AzureClusterStateEnum enum from its proto representation. func ProtoToGkemulticloudAzureClusterStateEnum(e gkemulticloudpb.GkemulticloudAzureClusterStateEnum) *gkemulticloud.AzureClusterStateEnum { if e == 0 { return nil } if n, ok := gkemulticloudpb.GkemulticloudAzureClusterStateEnum_name[int32(e)]; ok { e := gkemulticloud.AzureClusterStateEnum(n[len("GkemulticloudAzureClusterStateEnum"):]) return &e } return nil } // ProtoToAzureClusterNetworking converts a AzureClusterNetworking resource from its proto representation. func ProtoToGkemulticloudAzureClusterNetworking(p *gkemulticloudpb.GkemulticloudAzureClusterNetworking) *gkemulticloud.AzureClusterNetworking { if p == nil { return nil } obj := &gkemulticloud.AzureClusterNetworking{ VirtualNetworkId: dcl.StringOrNil(p.VirtualNetworkId), } for _, r := range p.GetPodAddressCidrBlocks() { obj.PodAddressCidrBlocks = append(obj.PodAddressCidrBlocks, r) } for _, r := range p.GetServiceAddressCidrBlocks() { obj.ServiceAddressCidrBlocks = append(obj.ServiceAddressCidrBlocks, r) } return obj } // ProtoToAzureClusterControlPlane converts a AzureClusterControlPlane resource from its proto representation. func ProtoToGkemulticloudAzureClusterControlPlane(p *gkemulticloudpb.GkemulticloudAzureClusterControlPlane) *gkemulticloud.AzureClusterControlPlane { if p == nil { return nil } obj := &gkemulticloud.AzureClusterControlPlane{ Version: dcl.StringOrNil(p.Version), SubnetId: dcl.StringOrNil(p.SubnetId), VmSize: dcl.StringOrNil(p.VmSize), SshConfig: ProtoToGkemulticloudAzureClusterControlPlaneSshConfig(p.GetSshConfig()), RootVolume: ProtoToGkemulticloudAzureClusterControlPlaneRootVolume(p.GetRootVolume()), MainVolume: ProtoToGkemulticloudAzureClusterControlPlaneMainVolume(p.GetMainVolume()), DatabaseEncryption: ProtoToGkemulticloudAzureClusterControlPlaneDatabaseEncryption(p.GetDatabaseEncryption()), } return obj } // ProtoToAzureClusterControlPlaneSshConfig converts a AzureClusterControlPlaneSshConfig resource from its proto representation. func ProtoToGkemulticloudAzureClusterControlPlaneSshConfig(p *gkemulticloudpb.GkemulticloudAzureClusterControlPlaneSshConfig) *gkemulticloud.AzureClusterControlPlaneSshConfig { if p == nil { return nil } obj := &gkemulticloud.AzureClusterControlPlaneSshConfig{ AuthorizedKey: dcl.StringOrNil(p.AuthorizedKey), } return obj } // ProtoToAzureClusterControlPlaneRootVolume converts a AzureClusterControlPlaneRootVolume resource from its proto representation. func ProtoToGkemulticloudAzureClusterControlPlaneRootVolume(p *gkemulticloudpb.GkemulticloudAzureClusterControlPlaneRootVolume) *gkemulticloud.AzureClusterControlPlaneRootVolume { if p == nil { return nil } obj := &gkemulticloud.AzureClusterControlPlaneRootVolume{ SizeGib: dcl.Int64OrNil(p.SizeGib), } return obj } // ProtoToAzureClusterControlPlaneMainVolume converts a AzureClusterControlPlaneMainVolume resource from its proto representation. func ProtoToGkemulticloudAzureClusterControlPlaneMainVolume(p *gkemulticloudpb.GkemulticloudAzureClusterControlPlaneMainVolume) *gkemulticloud.AzureClusterControlPlaneMainVolume { if p == nil { return nil } obj := &gkemulticloud.AzureClusterControlPlaneMainVolume{ SizeGib: dcl.Int64OrNil(p.SizeGib), } return obj } // ProtoToAzureClusterControlPlaneDatabaseEncryption converts a AzureClusterControlPlaneDatabaseEncryption resource from its proto representation. func ProtoToGkemulticloudAzureClusterControlPlaneDatabaseEncryption(p *gkemulticloudpb.GkemulticloudAzureClusterControlPlaneDatabaseEncryption) *gkemulticloud.AzureClusterControlPlaneDatabaseEncryption { if p == nil { return nil } obj := &gkemulticloud.AzureClusterControlPlaneDatabaseEncryption{ ResourceGroupId: dcl.StringOrNil(p.ResourceGroupId), KmsKeyIdentifier: dcl.StringOrNil(p.KmsKeyIdentifier), } return obj } // ProtoToAzureClusterAuthorization converts a AzureClusterAuthorization resource from its proto representation. func ProtoToGkemulticloudAzureClusterAuthorization(p *gkemulticloudpb.GkemulticloudAzureClusterAuthorization) *gkemulticloud.AzureClusterAuthorization { if p == nil { return nil } obj := &gkemulticloud.AzureClusterAuthorization{} for _, r := range p.GetAdminUsers() { obj.AdminUsers = append(obj.AdminUsers, *ProtoToGkemulticloudAzureClusterAuthorizationAdminUsers(r)) } return obj } // ProtoToAzureClusterAuthorizationAdminUsers converts a AzureClusterAuthorizationAdminUsers resource from its proto representation. func ProtoToGkemulticloudAzureClusterAuthorizationAdminUsers(p *gkemulticloudpb.GkemulticloudAzureClusterAuthorizationAdminUsers) *gkemulticloud.AzureClusterAuthorizationAdminUsers { if p == nil { return nil } obj := &gkemulticloud.AzureClusterAuthorizationAdminUsers{ Username: dcl.StringOrNil(p.Username), } return obj } // ProtoToAzureClusterWorkloadIdentityConfig converts a AzureClusterWorkloadIdentityConfig resource from its proto representation. func ProtoToGkemulticloudAzureClusterWorkloadIdentityConfig(p *gkemulticloudpb.GkemulticloudAzureClusterWorkloadIdentityConfig) *gkemulticloud.AzureClusterWorkloadIdentityConfig { if p == nil { return nil } obj := &gkemulticloud.AzureClusterWorkloadIdentityConfig{ IssuerUri: dcl.StringOrNil(p.IssuerUri), WorkloadPool: dcl.StringOrNil(p.WorkloadPool), IdentityProvider: dcl.StringOrNil(p.IdentityProvider), } return obj } // ProtoToAzureCluster converts a AzureCluster resource from its proto representation. func ProtoToAzureCluster(p *gkemulticloudpb.GkemulticloudAzureCluster) *gkemulticloud.AzureCluster { obj := &gkemulticloud.AzureCluster{ Name: dcl.StringOrNil(p.Name), Description: dcl.StringOrNil(p.Description), AzureRegion: dcl.StringOrNil(p.AzureRegion), ResourceGroupId: dcl.StringOrNil(p.ResourceGroupId), AzureClient: dcl.StringOrNil(p.AzureClient), Networking: ProtoToGkemulticloudAzureClusterNetworking(p.GetNetworking()), ControlPlane: ProtoToGkemulticloudAzureClusterControlPlane(p.GetControlPlane()), Authorization: ProtoToGkemulticloudAzureClusterAuthorization(p.GetAuthorization()), State: ProtoToGkemulticloudAzureClusterStateEnum(p.GetState()), Endpoint: dcl.StringOrNil(p.Endpoint), Uid: dcl.StringOrNil(p.Uid), Reconciling: dcl.Bool(p.Reconciling), CreateTime: dcl.StringOrNil(p.GetCreateTime()), UpdateTime: dcl.StringOrNil(p.GetUpdateTime()), Etag: dcl.StringOrNil(p.Etag), WorkloadIdentityConfig: ProtoToGkemulticloudAzureClusterWorkloadIdentityConfig(p.GetWorkloadIdentityConfig()), Project: dcl.StringOrNil(p.Project), Location: dcl.StringOrNil(p.Location), } return obj } // AzureClusterStateEnumToProto converts a AzureClusterStateEnum enum to its proto representation. func GkemulticloudAzureClusterStateEnumToProto(e *gkemulticloud.AzureClusterStateEnum) gkemulticloudpb.GkemulticloudAzureClusterStateEnum { if e == nil { return gkemulticloudpb.GkemulticloudAzureClusterStateEnum(0) } if v, ok := gkemulticloudpb.GkemulticloudAzureClusterStateEnum_value["AzureClusterStateEnum"+string(*e)]; ok { return gkemulticloudpb.GkemulticloudAzureClusterStateEnum(v) } return gkemulticloudpb.GkemulticloudAzureClusterStateEnum(0) } // AzureClusterNetworkingToProto converts a AzureClusterNetworking resource to its proto representation. func GkemulticloudAzureClusterNetworkingToProto(o *gkemulticloud.AzureClusterNetworking) *gkemulticloudpb.GkemulticloudAzureClusterNetworking { if o == nil { return nil } p := &gkemulticloudpb.GkemulticloudAzureClusterNetworking{ VirtualNetworkId: dcl.ValueOrEmptyString(o.VirtualNetworkId), } for _, r := range o.PodAddressCidrBlocks { p.PodAddressCidrBlocks = append(p.PodAddressCidrBlocks, r) } for _, r := range o.ServiceAddressCidrBlocks { p.ServiceAddressCidrBlocks = append(p.ServiceAddressCidrBlocks, r) } return p } // AzureClusterControlPlaneToProto converts a AzureClusterControlPlane resource to its proto representation. func GkemulticloudAzureClusterControlPlaneToProto(o *gkemulticloud.AzureClusterControlPlane) *gkemulticloudpb.GkemulticloudAzureClusterControlPlane { if o == nil { return nil } p := &gkemulticloudpb.GkemulticloudAzureClusterControlPlane{ Version: dcl.ValueOrEmptyString(o.Version), SubnetId: dcl.ValueOrEmptyString(o.SubnetId), VmSize: dcl.ValueOrEmptyString(o.VmSize), SshConfig: GkemulticloudAzureClusterControlPlaneSshConfigToProto(o.SshConfig), RootVolume: GkemulticloudAzureClusterControlPlaneRootVolumeToProto(o.RootVolume), MainVolume: GkemulticloudAzureClusterControlPlaneMainVolumeToProto(o.MainVolume), DatabaseEncryption: GkemulticloudAzureClusterControlPlaneDatabaseEncryptionToProto(o.DatabaseEncryption), } p.Tags = make(map[string]string) for k, r := range o.Tags { p.Tags[k] = r } return p } // AzureClusterControlPlaneSshConfigToProto converts a AzureClusterControlPlaneSshConfig resource to its proto representation. func GkemulticloudAzureClusterControlPlaneSshConfigToProto(o *gkemulticloud.AzureClusterControlPlaneSshConfig) *gkemulticloudpb.GkemulticloudAzureClusterControlPlaneSshConfig { if o == nil { return nil } p := &gkemulticloudpb.GkemulticloudAzureClusterControlPlaneSshConfig{ AuthorizedKey: dcl.ValueOrEmptyString(o.AuthorizedKey), } return p } // AzureClusterControlPlaneRootVolumeToProto converts a AzureClusterControlPlaneRootVolume resource to its proto representation. func GkemulticloudAzureClusterControlPlaneRootVolumeToProto(o *gkemulticloud.AzureClusterControlPlaneRootVolume) *gkemulticloudpb.GkemulticloudAzureClusterControlPlaneRootVolume { if o == nil { return nil } p := &gkemulticloudpb.GkemulticloudAzureClusterControlPlaneRootVolume{ SizeGib: dcl.ValueOrEmptyInt64(o.SizeGib), } return p } // AzureClusterControlPlaneMainVolumeToProto converts a AzureClusterControlPlaneMainVolume resource to its proto representation. func GkemulticloudAzureClusterControlPlaneMainVolumeToProto(o *gkemulticloud.AzureClusterControlPlaneMainVolume) *gkemulticloudpb.GkemulticloudAzureClusterControlPlaneMainVolume { if o == nil { return nil } p := &gkemulticloudpb.GkemulticloudAzureClusterControlPlaneMainVolume{ SizeGib: dcl.ValueOrEmptyInt64(o.SizeGib), } return p } // AzureClusterControlPlaneDatabaseEncryptionToProto converts a AzureClusterControlPlaneDatabaseEncryption resource to its proto representation. func GkemulticloudAzureClusterControlPlaneDatabaseEncryptionToProto(o *gkemulticloud.AzureClusterControlPlaneDatabaseEncryption) *gkemulticloudpb.GkemulticloudAzureClusterControlPlaneDatabaseEncryption { if o == nil { return nil } p := &gkemulticloudpb.GkemulticloudAzureClusterControlPlaneDatabaseEncryption{ ResourceGroupId: dcl.ValueOrEmptyString(o.ResourceGroupId), KmsKeyIdentifier: dcl.ValueOrEmptyString(o.KmsKeyIdentifier), } return p } // AzureClusterAuthorizationToProto converts a AzureClusterAuthorization resource to its proto representation. func GkemulticloudAzureClusterAuthorizationToProto(o *gkemulticloud.AzureClusterAuthorization) *gkemulticloudpb.GkemulticloudAzureClusterAuthorization { if o == nil { return nil } p := &gkemulticloudpb.GkemulticloudAzureClusterAuthorization{} for _, r := range o.AdminUsers { p.AdminUsers = append(p.AdminUsers, GkemulticloudAzureClusterAuthorizationAdminUsersToProto(&r)) } return p } // AzureClusterAuthorizationAdminUsersToProto converts a AzureClusterAuthorizationAdminUsers resource to its proto representation. func GkemulticloudAzureClusterAuthorizationAdminUsersToProto(o *gkemulticloud.AzureClusterAuthorizationAdminUsers) *gkemulticloudpb.GkemulticloudAzureClusterAuthorizationAdminUsers { if o == nil { return nil } p := &gkemulticloudpb.GkemulticloudAzureClusterAuthorizationAdminUsers{ Username: dcl.ValueOrEmptyString(o.Username), } return p } // AzureClusterWorkloadIdentityConfigToProto converts a AzureClusterWorkloadIdentityConfig resource to its proto representation. func GkemulticloudAzureClusterWorkloadIdentityConfigToProto(o *gkemulticloud.AzureClusterWorkloadIdentityConfig) *gkemulticloudpb.GkemulticloudAzureClusterWorkloadIdentityConfig { if o == nil { return nil } p := &gkemulticloudpb.GkemulticloudAzureClusterWorkloadIdentityConfig{ IssuerUri: dcl.ValueOrEmptyString(o.IssuerUri), WorkloadPool: dcl.ValueOrEmptyString(o.WorkloadPool), IdentityProvider: dcl.ValueOrEmptyString(o.IdentityProvider), } return p } // AzureClusterToProto converts a AzureCluster resource to its proto representation. func AzureClusterToProto(resource *gkemulticloud.AzureCluster) *gkemulticloudpb.GkemulticloudAzureCluster { p := &gkemulticloudpb.GkemulticloudAzureCluster{ Name: dcl.ValueOrEmptyString(resource.Name), Description: dcl.ValueOrEmptyString(resource.Description), AzureRegion: dcl.ValueOrEmptyString(resource.AzureRegion), ResourceGroupId: dcl.ValueOrEmptyString(resource.ResourceGroupId), AzureClient: dcl.ValueOrEmptyString(resource.AzureClient), Networking: GkemulticloudAzureClusterNetworkingToProto(resource.Networking), ControlPlane: GkemulticloudAzureClusterControlPlaneToProto(resource.ControlPlane), Authorization: GkemulticloudAzureClusterAuthorizationToProto(resource.Authorization), State: GkemulticloudAzureClusterStateEnumToProto(resource.State), Endpoint: dcl.ValueOrEmptyString(resource.Endpoint), Uid: dcl.ValueOrEmptyString(resource.Uid), Reconciling: dcl.ValueOrEmptyBool(resource.Reconciling), CreateTime: dcl.ValueOrEmptyString(resource.CreateTime), UpdateTime: dcl.ValueOrEmptyString(resource.UpdateTime), Etag: dcl.ValueOrEmptyString(resource.Etag), WorkloadIdentityConfig: GkemulticloudAzureClusterWorkloadIdentityConfigToProto(resource.WorkloadIdentityConfig), Project: dcl.ValueOrEmptyString(resource.Project), Location: dcl.ValueOrEmptyString(resource.Location), } return p } // ApplyAzureCluster handles the gRPC request by passing it to the underlying AzureCluster Apply() method. func (s *AzureClusterServer) applyAzureCluster(ctx context.Context, c *gkemulticloud.Client, request *gkemulticloudpb.ApplyGkemulticloudAzureClusterRequest) (*gkemulticloudpb.GkemulticloudAzureCluster, error) { p := ProtoToAzureCluster(request.GetResource()) res, err := c.ApplyAzureCluster(ctx, p) if err != nil { return nil, err } r := AzureClusterToProto(res) return r, nil } // ApplyAzureCluster handles the gRPC request by passing it to the underlying AzureCluster Apply() method. func (s *AzureClusterServer) ApplyGkemulticloudAzureCluster(ctx context.Context, request *gkemulticloudpb.ApplyGkemulticloudAzureClusterRequest) (*gkemulticloudpb.GkemulticloudAzureCluster, error) { cl, err := createConfigAzureCluster(ctx, request.ServiceAccountFile) if err != nil { return nil, err } return s.applyAzureCluster(ctx, cl, request) } // DeleteAzureCluster handles the gRPC request by passing it to the underlying AzureCluster Delete() method. func (s *AzureClusterServer) DeleteGkemulticloudAzureCluster(ctx context.Context, request *gkemulticloudpb.DeleteGkemulticloudAzureClusterRequest) (*emptypb.Empty, error) { cl, err := createConfigAzureCluster(ctx, request.ServiceAccountFile) if err != nil { return nil, err } return &emptypb.Empty{}, cl.DeleteAzureCluster(ctx, ProtoToAzureCluster(request.GetResource())) } // ListGkemulticloudAzureCluster handles the gRPC request by passing it to the underlying AzureClusterList() method. func (s *AzureClusterServer) ListGkemulticloudAzureCluster(ctx context.Context, request *gkemulticloudpb.ListGkemulticloudAzureClusterRequest) (*gkemulticloudpb.ListGkemulticloudAzureClusterResponse, error) { cl, err := createConfigAzureCluster(ctx, request.ServiceAccountFile) if err != nil { return nil, err } resources, err := cl.ListAzureCluster(ctx, ProtoToAzureCluster(request.GetResource())) if err != nil { return nil, err } var protos []*gkemulticloudpb.GkemulticloudAzureCluster for _, r := range resources.Items { rp := AzureClusterToProto(r) protos = append(protos, rp) } return &gkemulticloudpb.ListGkemulticloudAzureClusterResponse{Items: protos}, nil } func createConfigAzureCluster(ctx context.Context, service_account_file string) (*gkemulticloud.Client, error) { conf := dcl.NewConfig(dcl.WithUserAgent("dcl-test"), dcl.WithCredentialsFile(service_account_file)) return gkemulticloud.NewClient(conf), nil }
package service import ( "context" "fmt" "github.com/bqxtt/book_online/api/adapter" "github.com/bqxtt/book_online/api/model/entity" "github.com/bqxtt/book_online/rpc/clients/rpc_user" "github.com/bqxtt/book_online/rpc/model/base" "github.com/bqxtt/book_online/rpc/model/userpb" "strconv" ) type IUserService interface { Register(userAuth *entity.UserAuth) error Login(userAuth *entity.UserAuth) (*entity.User, error) GetUserInfo(userId string) (*entity.User, error) UpdateUserInfo(user *entity.User) (*entity.User, error) DeleteUser(userId string) error ListUsersByPage(page int32, pageSize int32) ([]*entity.User, *entity.PageInfo, error) } type userServiceImpl struct{} var UserService IUserService = &userServiceImpl{} func (svc *userServiceImpl) Register(user *entity.UserAuth) error { userId, err := strconv.Atoi(user.UserId) if err != nil { return fmt.Errorf("user id error, err: %v", err) } request := &userpb.RegisterRequest{ UserAuth: &userpb.UserAuth{ UserId: int64(userId), PwdDigest: user.Password, }, } resp, err := rpc_user.UserServiceClient.Register(context.Background(), request) if err != nil { return err } if resp == nil { return fmt.Errorf("register response is nil") } if resp.Reply.Status != 1 { return fmt.Errorf("%v", resp.Reply.Message) } return nil } func (svc *userServiceImpl) Login(userAuth *entity.UserAuth) (*entity.User, error) { userId, err := strconv.Atoi(userAuth.UserId) if err != nil { return nil, fmt.Errorf("user id error, err: %v", err) } request := &userpb.LoginRequest{ UserAuth: &userpb.UserAuth{ UserId: int64(userId), PwdDigest: userAuth.Password, }, } resp, err := rpc_user.UserServiceClient.Login(context.Background(), request) if err != nil { return nil, fmt.Errorf("rpc user service error, err: %v", err) } if resp == nil { return nil, fmt.Errorf("login response is nil") } if resp.Reply.Status != 1 { return nil, fmt.Errorf("%v", resp.Reply.Message) } return adapter.RpcUserToEntityUser(resp.User), nil } func (svc *userServiceImpl) GetUserInfo(userId string) (*entity.User, error) { id, err := strconv.Atoi(userId) if err != nil { return nil, fmt.Errorf("user id error, err: %v", err) } request := &userpb.GetInfoRequest{ UserId: int64(id), } resp, err := rpc_user.UserServiceClient.GetInfo(context.Background(), request) if err != nil { return nil, fmt.Errorf("rpc user service error, err: %v", err) } if resp == nil { return nil, fmt.Errorf("get user info resp is nil") } if resp.Reply.Status != 1 { return nil, fmt.Errorf("rpc resp message: %v", resp.Reply.Message) } return adapter.RpcUserToEntityUser(resp.User), nil } func (svc *userServiceImpl) UpdateUserInfo(user *entity.User) (*entity.User, error) { if user == nil { return nil, fmt.Errorf("user is nil") } request := &userpb.UpdateInfoRequest{ UserInfo: adapter.EntityUserToRpcUser(user), } resp, err := rpc_user.UserServiceClient.UpdateInfo(context.Background(), request) if err != nil { return nil, fmt.Errorf("rpc user service error, err: %v", err) } if resp == nil { return nil, fmt.Errorf("update user info resp is nil") } if resp.Reply.Status != 1 { return nil, fmt.Errorf("rpc resp message: %v", resp.Reply.Message) } return adapter.RpcUserToEntityUser(resp.ResultUserInfo), nil } func (svc *userServiceImpl) DeleteUser(userId string) error { id, err := strconv.Atoi(userId) if err != nil { return fmt.Errorf("user id error, err: %v", err) } request := &userpb.DeleteUserRequest{ UserId: int64(id), } resp, err := rpc_user.UserServiceClient.DeleteUser(context.Background(), request) if err != nil { return fmt.Errorf("rpc user service error, err: %v", err) } if resp == nil { return fmt.Errorf("update user info resp is nil") } if resp.Reply.Status != 1 { return fmt.Errorf("rpc resp message: %v", resp.Reply.Message) } return nil } func (svc *userServiceImpl) ListUsersByPage(page int32, pageSize int32) ([]*entity.User, *entity.PageInfo, error) { request := &userpb.ListUsersPagedRequest{Page: &base.Page{ PageNo: int64(page), PageSize: int64(pageSize), }} resp, err := rpc_user.UserServiceClient.ListUsersPaged(context.Background(), request) if err != nil { return nil, nil, fmt.Errorf("rpc user service error, err: %v", err) } if resp == nil { return nil, nil, fmt.Errorf("list user resp is nil") } if resp.Reply.Status != 1 { return nil, nil, fmt.Errorf("rpc resp message: %v", resp.Reply.Message) } var users []*entity.User for _, user := range resp.Users { users = append(users, adapter.RpcUserToEntityUser(user)) } return users, &entity.PageInfo{ TotalPages: resp.TotalPages, TotalCount: resp.TotalCount, }, nil }
package gate import ( "hub000.xindong.com/rookie/rookie-framework/protobuf" "hub000.xindong.com/rookie/rookie-framework/log" ) type MsgHandler interface { Unmarshal(int, []byte, string) (protobuf.CSRequest, error) Marshal(resp protobuf.CSResponse) (*Message, error) } type Processor struct { g *WSGate Router *Router handler MsgHandler } func NewProcessor(h MsgHandler) *Processor{ router := NewRouter() processor := &Processor{} router.p = processor processor.Router = router processor.handler = h return processor } func (p *Processor)MessageHandler(conn *WsConn, t int ,msg []byte){ req, err := p.handler.Unmarshal(t, msg ,conn.player) if err != nil { mylog.Error("MessageHandler fail.",err) }else{ p.Router.Operate(req) } } func (p *Processor)Send(resp protobuf.CSResponse){ message, err := p.handler.Marshal(resp) if err != nil { mylog.Error("Send fail.",err) }else{ p.g.SendToPlayer(resp.ClientID, message) } }
package cmd import ( // 3rd Party "github.com/spf13/cobra" ) // Represents the create labels command var createLabelsCmd = &cobra.Command{ Use: "create", Short: "Creates a new set of github labels", Run: GithubLabelCreatorHandler, } func init() { createLabelsCmd.Flags().StringVarP(&Application, "application", "a", "", "The name of the application you want to release") createLabelsCmd.Flags().StringVarP(&Organization, "organization", "o", "SweatWorks", "The name of the organization/owner of the repo") createLabelsCmd.Flags().StringVarP(&LabelFile, "file", "f", "", "The json file of the labels") createLabelsCmd.MarkFlagRequired("application") createLabelsCmd.MarkFlagRequired("file") }
package db import ( "github.com/pkg/errors" "gorm.io/driver/mysql" "gorm.io/gorm" "gorm.io/gorm/logger" "github.com/YusukeKishino/go-blog/config" ) func ConnectDB(conf *config.AppConfig) (*gorm.DB, error) { var logLebel logger.LogLevel if config.IsDev() { logLebel = logger.Info } else { logLebel = logger.Error } db, err := gorm.Open( mysql.New(mysql.Config{ DSN: conf.DBUrl, }), &gorm.Config{ AllowGlobalUpdate: false, Logger: logger.Default.LogMode(logLebel), }) if err != nil { return nil, errors.Wrap(err, "failed to connecting database") } return db, nil }
package pgsql import ( "bytes" "encoding/hex" "time" ) const ( dateLayout = "2006-01-02" timeLayout = "15:04:05.999" timetzLayout = "15:04:05.999-07:00" timestampLayout = "2006-01-02 15:04:05.999" timestamptzLayout = "2006-01-02 15:04:05.999-07" ) var noZone = time.FixedZone("", 0) func srcbytes(src interface{}) ([]byte, error) { switch src := src.(type) { case []byte: return src, nil case string: return []byte(src), nil case nil: return nil, nil } return nil, nil // TODO error } // parse as single bytes func pgparsearray2(a []byte) (out []byte) { out = make([]byte, 0, len(a)) a = a[1 : len(a)-1] // drop curly braces for i := 0; i < len(a); i++ { if a[i] == '"' { if a[i+1] == '\\' { out = append(out, a[i+2]) i += 3 continue } else { out = append(out, a[i+1]) i += 2 continue } } if a[i] != ',' { out = append(out, a[i]) } } return out } // parse as single runes func pgparsearray3(a []byte) (out []rune) { out = make([]rune, 0) a = a[1 : len(a)-1] // drop curly braces r := bytes.Runes(a) for i := 0; i < len(r); i++ { if r[i] == '"' { if r[i+1] == '\\' { out = append(out, r[i+2]) i += 3 continue } else { out = append(out, r[i+1]) i += 2 continue } } if r[i] != ',' { out = append(out, r[i]) } } return out } func pgparsehstore(a []byte) (out [][2][]byte) { if len(a) == 0 { return out // nothing to do if empty } var ( idx uint8 // pair index 0=key 1=val pair [2][]byte // current pair ) for i := 0; i < len(a); i++ { if a[i] == '"' { // start of key or value? for j := i + 1; j < len(a); j++ { if a[j] == '\\' { j++ // skip escaped char pair[idx] = append(pair[idx], a[j]) continue } if a[j] == '"' { // end of key or value? i = j break } pair[idx] = append(pair[idx], a[j]) } if idx == 1 { // is the pair done? out = append(out, pair) pair = [2][]byte{} // next pair } // flip the index idx ^= 1 } if a[i] == 'N' { i += 4 idx = 0 out = append(out, pair) pair = [2][]byte{} } } return out } func pgparsehstorearr(a []byte) (out [][][2][]byte) { if len(a) == 0 { return out // nothing to do if empty } a = a[1 : len(a)-1] // drop array delimiters var ( idx uint8 // pair index 0=key 1=val pair [2][]byte // current pair ) for i := 0; i < len(a); i++ { if a[i] == '"' { // start of hstore in array? hstore := [][2][]byte{} for j := i + 1; j < len(a); j++ { if a[j] == '\\' && a[j+1] == '"' { // start of key or value? for k := j + 2; k < len(a); k++ { if a[k] == '\\' { if a[k+1] == '\\' { // escape?? k += 3 // skip escaped char pair[idx] = append(pair[idx], a[k]) continue } if a[k+1] == '"' { // key or value ending quote? j = k + 2 break } } pair[idx] = append(pair[idx], a[k]) } if idx == 1 { // is the pair done? hstore = append(hstore, pair) pair = [2][]byte{} // next pair } // flip the index idx ^= 1 } // handle NULL value in pair if a[j] == 'N' { j += 4 idx = 0 hstore = append(hstore, pair) pair = [2][]byte{} // next pair } if a[j] == '"' { // end of hstore in array? out = append(out, hstore) i = j break } } } // handle NULL hstore if a[i] == 'N' { out = append(out, nil) i += 4 } } return out } func pgparsedate(a []byte) (time.Time, error) { return time.ParseInLocation(dateLayout, string(a), time.UTC) } func pgParseRange(a []byte) (out [2][]byte) { a = a[1 : len(a)-1] // drop range delimiters for i := 0; i < len(a); i++ { if a[i] == ',' { out[0] = a[:i] out[1] = a[i+1:] break } } return out } // Expected format: '{STRING [, ...]}' where STRING is a double quoted string. func pgParseQuotedStringArray(a []byte) (out [][]byte) { a = a[1 : len(a)-1] // drop curly braces mainloop: for i := 0; i < len(a); i++ { if a[i] == '"' { // start of string for j := i + 1; j < len(a); j++ { if a[j] == '\\' { j++ // skip escaped char continue } if a[j] == '"' { // end of string out = append(out, a[i+1:j]) i = j + 1 continue mainloop } } } if a[i] == 'N' { // NULL? out = append(out, []byte(nil)) i += 4 } } return out } // Expected format: '{STRING [, ...]}' where STRING is either an unquoted or a double quoted string. func pgParseStringArray(a []byte) (out [][]byte) { a = a[1 : len(a)-1] // drop curly braces mainloop: for i := 0; i < len(a); i++ { switch a[i] { case ',': // element separator? continue mainloop case '"': // start of double quoted string str := []byte{} for j := i + 1; j < len(a); j++ { if a[j] == '\\' { // escape sequence str = append(str, a[i+1:j]...) i = j j++ continue } if a[j] == '"' { // end of string str = append(str, a[i+1:j]...) out = append(out, str) i = j continue mainloop } } case 'N': // NULL? if len(a) > i+3 && string(a[i:i+4]) == `NULL` { out = append(out, []byte(nil)) i = i + 3 continue mainloop } fallthrough default: // start of unquoted string var j int for j = i + 1; j < len(a); j++ { if a[j] == ',' { // end of string out = append(out, a[i:j]) i = j continue mainloop } } // end of the last element out = append(out, a[i:j]) i = j } } return out } // Expected format: '`[`(X1,Y1),(X2,Y2)`]`' where Xn and Yn are numbers. func pgParseLseg(a []byte) (out [2][2][]byte) { a = a[1 : len(a)-1] // drop the surrounding brackets n := 0 for i := 0; i < len(a); i++ { if a[i] == '(' { var point [2][]byte for j := i + 1; j < len(a); j++ { if a[j] == ',' { point[0] = a[i+1 : j] i = j } else if a[j] == ')' { point[1] = a[i+1 : j] i = j break } } out[n] = point n += 1 } } return out } // Expected format: '{"[(X1,Y1),(X2,Y2)]"[, ...]}' where Xn and Yn are numbers. func pgParseLsegArray(a []byte) (out [][2][2][]byte) { a = a[1 : len(a)-1] // drop the surrounding curlies for i := 0; i < len(a); i++ { if a[i] == '"' { // lseg start var lseg [2][2][]byte i += 3 // len(`"[(`) == 3 n := 0 for j := i; j < len(a); j++ { if a[j] == ',' { lseg[n][0] = a[i:j] i = j + 1 } else if a[j] == ')' { lseg[n][1] = a[i:j] if n == 0 { j += 3 // len(`),(`) == 3 n = 1 } i = j } else if a[j] == ']' { i = j break } } out = append(out, lseg) i += 2 // skip closing `"` and `,` separator } else if a[i] == 'N' { // handle NULL out = append(out, [2][2][]byte{}) i += 4 } } return out } // Expected format: '{A,B,C}' where A, B, and C are numbers. func pgParseLine(a []byte) (out [3][]byte) { a = a[1 : len(a)-1] // drop the surrounding curly braces for i := 0; i < len(a); i++ { if a[i] == ',' { out[0] = a[:i] for j := i + 1; j < len(a); j++ { if a[j] == ',' { out[1] = a[i+1 : j] out[2] = a[j+1:] break } } break } } return out } // Expected format: '{"{A,B,C}"[, ...]}' where A, B, and C are numbers. func pgParseLineArray(a []byte) (out [][3][]byte) { a = a[1 : len(a)-1] // drop the surrounding curlies for i := 0; i < len(a); i++ { if a[i] == '"' { // line start var line [3][]byte i += 2 // len(`"{`) == 2 n := 0 for j := i; j < len(a); j++ { if a[j] == ',' { line[n] = a[i:j] i = j + 1 n += 1 } else if a[j] == '}' { line[2] = a[i:j] i = j break } } out = append(out, line) i += 2 // skip closing `"` and `,` separator } else if a[i] == 'N' { // handle NULL out = append(out, [3][]byte{}) i += 4 } } return out } // Expected format: '(X,Y)' where X and Y are numbers. func pgParsePoint(a []byte) (out [2][]byte) { a = a[1 : len(a)-1] // drop the surrounding parentheses for i := 0; i < len(a); i++ { if a[i] == ',' { out[0] = a[:i] out[1] = a[i+1:] break } } return out } // Expected format: '{"(X,Y)"[, ...]}' where X and Y are numbers. func pgParsePointArray(a []byte) (out [][2][]byte) { a = a[1 : len(a)-1] // drop the surrounding curlies for i := 0; i < len(a); i++ { if a[i] == '"' { // point start var point [2][]byte for j := i + 2; j < len(a); j++ { if a[j] == ',' { point[0] = a[i+2 : j] i = j } else if a[j] == ')' { point[1] = a[i+1 : j] i = j break } } out = append(out, point) i += 2 // skip closing `"` and `,` separator } else if a[i] == 'N' { // handle NULL out = append(out, [2][]byte{}) i += 4 } } return out } // Expected format: '(X,Y)[, ...]' where X and Y are numbers. func pgParsePointList(a []byte) (out [][2][]byte) { for i := 0; i < len(a); i++ { if a[i] == '(' { var point [2][]byte for j := i + 1; j < len(a); j++ { if a[j] == ',' { point[0] = a[i+1 : j] i = j } else if a[j] == ')' { point[1] = a[i+1 : j] i = j break } } out = append(out, point) } } return out } // Expected format: '((X,Y)[, ...])' where X and Y are numbers. func pgParsePolygon(a []byte) (out [][2][]byte) { a = a[1 : len(a)-1] // drop the first `(` and last `)` return pgParsePointList(a) } // Expected format: '{"((X,Y)[, ...])"[, ...]}' where X and Y are numbers. func pgParsePolygonArray(a []byte) (out [][][2][]byte) { a = a[1 : len(a)-1] // drop the first `{` and last `}` for i := 0; i < len(a); i++ { var polygon [][2][]byte if a[i] == '"' { // polygon start for j := i + 2; j < len(a); j++ { if a[j] == '(' { var point [2][]byte for k := j + 1; k < len(a); k++ { if a[k] == ',' { point[0] = a[j+1 : k] j = k } else if a[k] == ')' { point[1] = a[j+1 : k] j = k break } } polygon = append(polygon, point) } else if a[j] == '"' { // polygon end out = append(out, polygon) i = j break } } } else if a[i] == 'N' { // handle NULL out = append(out, [][2][]byte(nil)) i += 4 } } return out } // Expected format: '((X,Y)[, ...]) | `[`(X,Y)[, ...]`]`' where X and Y are numbers. func pgParsePath(a []byte) (out [][2][]byte, closed bool) { closed = (a[0] == '(') a = a[1 : len(a)-1] // drop the surrounding parentheses or square brackets return pgParsePointList(a), closed } // Expected format: '{"((X,Y)[, ...])" | "`[`(X,Y)[, ...]`]`" [, ...]}' where X and Y are numbers. func pgParsePathArray(a []byte) (out [][][2][]byte) { a = a[1 : len(a)-1] // drop the first `{` and last `}` for i := 0; i < len(a); i++ { var path [][2][]byte if a[i] == '"' { // path start for j := i + 2; j < len(a); j++ { if a[j] == '(' || a[j] == '[' { var point [2][]byte for k := j + 1; k < len(a); k++ { if a[k] == ',' { point[0] = a[j+1 : k] j = k } else if a[k] == ']' || a[k] == ')' { point[1] = a[j+1 : k] j = k break } } path = append(path, point) } else if a[j] == '"' { // path end out = append(out, path) i = j break } } } else if a[i] == 'N' { // handle NULL out = append(out, [][2][]byte(nil)) i += 4 } } return out } // Expected format: '(X1,Y1),(X2,Y2)' where X and Y are numbers. func pgParseBox(a []byte) (out [][]byte) { a = a[1 : len(a)-1] // drop the first '(' and last ')' n := 0 // start of next elem for i := 0; i < len(a); i++ { if a[i] == ',' { out = append(out, a[n:i]) n = i + 1 } if a[i] == ')' { out = append(out, a[n:i]) i += 2 // skip over ",(" n = i + 1 } } // append the last element if n > 0 { out = append(out, a[n:]) } return out } // Expected format: '{(X1,Y1),(X2,Y2)[; ...]}' where X and Y are numbers. func pgParseBoxArray(a []byte) (out [][]byte) { if len(a) == 2 { return out // nothing to do if empty "{}" } a = a[2 : len(a)-2] // drop the first "{(" and last ")}" n := 0 // start of next elem for i := 0; i < len(a); i++ { if a[i] == ',' { out = append(out, a[n:i]) n = i + 1 } if a[i] == ')' { out = append(out, a[n:i]) i += 2 // skip over ",(" or ";(" n = i + 1 } } // append the last element if n > 0 { out = append(out, a[n:]) } return out } // Expected format: '{X [, ...]}' where X is anything that doesn't contain a comma. func pgParseCommaArray(a []byte) (out [][]byte) { a = a[1 : len(a)-1] // drop curly braces n := 0 // start of next elem for i := 0; i < len(a); i++ { if a[i] == ',' { out = append(out, a[n:i]) n = i + 1 } } // append the last element if len(a) > 0 { out = append(out, a[n:]) } return out } // Expected format: 'E[ ...]' (space separated list of elements). func pgParseVector(a []byte) (out [][]byte) { var j int for i := 0; i < len(a); i++ { if a[i] == ' ' { out = append(out, a[j:i]) j = i + 1 } } if len(a) > 0 { out = append(out, a[j:]) // last } return out } // Expected format: '{VEC [, ...]}' where VEC is a space separated list of elements, // the list being enclosed in double quotes, or a single unquoted element, or NULL. func pgParseVectorArray(a []byte) (out [][][]byte) { if len(a) == 0 { return out // nothing to do if empty } a = a[1 : len(a)-1] // drop array delimiters for i := 0; i < len(a); i++ { switch a[i] { case '"': // quoted element vector := [][]byte{} k := i + 1 // vector start for j := k; j < len(a); j++ { if a[j] == '"' { // vector end vector = append(vector, a[k:j]) i = j + 1 break } if a[j] == ' ' { vector = append(vector, a[k:j]) k = j + 1 } } out = append(out, vector) case 'N': // NULL element? if len(a) > i+3 && string(a[i:i+4]) == `NULL` { out = append(out, [][]byte(nil)) i = i + 3 } default: // unquoted element k, j := i, i // elem start for ; j < len(a); j++ { if a[j] == ',' { // elem end i = j break } } out = append(out, [][]byte{a[k:j]}) } } return out } // Expected format: 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx'. func pgParseUUID(data []byte) (arr [16]byte, err error) { if _, err = hex.Decode(arr[0:4], data[0:8]); err != nil { return arr, err } if _, err = hex.Decode(arr[4:6], data[9:13]); err != nil { return arr, err } if _, err = hex.Decode(arr[6:8], data[14:18]); err != nil { return arr, err } if _, err = hex.Decode(arr[8:10], data[19:23]); err != nil { return arr, err } if _, err = hex.Decode(arr[10:], data[24:]); err != nil { return arr, err } return arr, nil } // pgFormatUUID converts the given array to a slice of bytes in the following // format "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" representing a uuid. func pgFormatUUID(arr [16]byte) (out []byte) { out = make([]byte, 36) _ = hex.Encode(out[0:8], arr[0:4]) _ = hex.Encode(out[9:13], arr[4:6]) _ = hex.Encode(out[14:18], arr[6:8]) _ = hex.Encode(out[19:23], arr[8:10]) _ = hex.Encode(out[24:], arr[10:]) out[8] = '-' out[13] = '-' out[18] = '-' out[23] = '-' return out } // pgAppendQuote1 func pgAppendQuote1(buf, elem []byte) []byte { buf = append(buf, '"') for i := 0; i < len(elem); i++ { switch elem[i] { case '"', '\\': buf = append(buf, '\\', elem[i]) case '\a': buf = append(buf, '\\', '\a') case '\b': buf = append(buf, '\\', '\b') case '\f': buf = append(buf, '\\', '\f') case '\n': buf = append(buf, '\\', '\n') case '\r': buf = append(buf, '\\', '\r') case '\t': buf = append(buf, '\\', '\t') case '\v': buf = append(buf, '\\', '\v') default: buf = append(buf, elem[i]) } } return append(buf, '"') } // pgAppendQuote2 func pgAppendQuote2(buf, elem []byte) []byte { buf = append(buf, '\\', '"') for i := 0; i < len(elem); i++ { switch elem[i] { case '"', '\\': buf = append(buf, '\\', '\\', '\\', elem[i]) case '\a': buf = append(buf, '\\', '\\', '\\', '\a') case '\b': buf = append(buf, '\\', '\\', '\\', '\b') case '\f': buf = append(buf, '\\', '\\', '\\', '\f') case '\n': buf = append(buf, '\\', '\\', '\\', '\n') case '\r': buf = append(buf, '\\', '\\', '\\', '\r') case '\t': buf = append(buf, '\\', '\\', '\\', '\t') case '\v': buf = append(buf, '\\', '\\', '\\', '\v') default: buf = append(buf, elem[i]) } } return append(buf, '\\', '"') }
package records import ( "strings" "github.com/coredns/caddy" "github.com/coredns/coredns/core/dnsserver" "github.com/coredns/coredns/plugin" clog "github.com/coredns/coredns/plugin/pkg/log" "github.com/miekg/dns" ) var log = clog.NewWithPlugin("records") func init() { plugin.Register("records", setup) } func setup(c *caddy.Controller) error { re, err := recordsParse(c) if err != nil { return plugin.Error("records", err) } dnsserver.GetConfig(c).AddPlugin(func(next plugin.Handler) plugin.Handler { re.Next = next return re }) return nil } func recordsParse(c *caddy.Controller) (*Records, error) { re := New() i := 0 for c.Next() { if i > 0 { return re, plugin.ErrOnce } i++ // copy the server block origins, if ZONES are given we will overwrite these again re.origins = make([]string, len(c.ServerBlockKeys)) copy(re.origins, c.ServerBlockKeys) args := c.RemainingArgs() if len(args) > 0 { re.origins = args } for i := range re.origins { re.origins[i] = plugin.Host(re.origins[i]).Normalize() } if len(re.origins) == 0 { // do we really need this default, just in the tests? re.origins = []string{"."} } // c.Val() + c.RemainingArgs() is the record we need to parse (for each zone given; now tracked in re.origins). When parsing // the record we just set the ORIGIN to the correct value and magic will happen. If no origin we set it to "." for c.NextBlock() { s := c.Val() + " " s += strings.Join(c.RemainingArgs(), " ") for _, o := range re.origins { rr, err := dns.NewRR("$ORIGIN " + o + "\n" + s + "\n") if err != nil { return nil, err } rr.Header().Name = strings.ToLower(rr.Header().Name) re.m[o] = append(re.m[o], rr) } } } return re, nil }
package model import ( "testing" ) var U User func loginUser() User { var u User u.Username = "naughtydevelopement" u.Password = "12341234" return u } func TestSignUpUser(t *testing.T) { //config.Init() //Init() //db.LogMode(true) //U = loginUser() //up, err := SignUp(U) //if err != nil { // t.Error(err) //} // //assert.True(t, up.ID > 0) //assert.Equal(t, up.Username, U.Username) }
// Copyright 2015 Alexey Martseniuk. All rights reserved. // Use of this source code is governed by a MIT license // that can be found in the LICENSE file. package linq_test import ( "bytes" "fmt" "github.com/zx48/linq" ) func Example() { res, err := linq.FromSequence(2, 3, 5).Where(func(v linq.T) bool { return v.(int) < 5 }).Select(func(v linq.T) linq.T { i := v.(int) return i * i }).ToSlice() if err != nil { fmt.Println(err) return } fmt.Println(res) // Output: // [4 9] } func ExampleEnumerable_Enumerator() { en := linq.FromSequence(1, 2, 3, 4, 5).Where(func(v linq.T) bool { return v.(int) > 2 }).Enumerator() en.Reset() en.Next() en.Next() fmt.Println(en.Value()) en.Reset() en.Next() fmt.Println(en.Value()) // Output: // 4 // 3 } func ExampleEnumerable_Aggregate() { res, err := linq.FromSequence(1, 2, 3, 4, 5).Aggregate(func(v1, v2 linq.T) linq.T { return v1.(int) * v2.(int) }) if err != nil { fmt.Println(err) return } fmt.Println(res) // Output: // 120 } func ExampleEnumerable_All() { res, err := linq.FromSequence(1, 2, 3, -1, 5).All(func(v linq.T) bool { return v.(int) > 0 }) if err != nil { fmt.Println(err) return } fmt.Println(res) // Output: // false } func ExampleEnumerable_Any() { res, err := linq.FromSequence(1, 2, 3, -1, 5).Any(func(v linq.T) bool { return v.(int) < 0 }) if err != nil { fmt.Println(err) return } fmt.Println(res) // Output: // true } func ExampleEnumerable_Apply_max() { data := []int{1, 2, 7, 3, 4, 5} def := data[0] res, err := linq.FromSlice(data).Apply(func(v linq.T) linq.T { vi := v.(int) if def < vi { def = vi } return def }, nil) if err != nil { fmt.Println(err) return } fmt.Println(res) // Output: // 7 } func ExampleEnumerable_Apply_min() { data := []int{3, 2, 9, 1, 4, 5} def := data[0] res, err := linq.FromSlice(data).Apply(func(v linq.T) linq.T { vi := v.(int) if def > vi { def = vi } return def }, nil) if err != nil { fmt.Println(err) return } fmt.Println(res) // Output: // 1 } func ExampleEnumerable_Apply_sum() { def := 0 res, err := linq.FromSequence(1, 2, 3, 4, 5).Apply(func(v linq.T) linq.T { def += v.(int) return def }, nil) if err != nil { fmt.Println(err) return } fmt.Println(res) // Output: // 15 } func ExampleEnumerable_Apply_average() { data := []float32{7., 1., 2., 3., 8., 3.} def := float32(0) n := float32(0) res, err := linq.FromSlice(data).Apply(func(v linq.T) linq.T { def += v.(float32) n++ return def / n }, nil) if err != nil { fmt.Println(err) return } fmt.Println(res) // Output: // 4 } func ExampleEnumerable_Concat() { data1 := []int{1, 2, 3} data2 := []int{4, 5} res, err := linq.FromSlice(data1).Concat(linq.FromSlice(data2)).ToSlice() if err != nil { fmt.Println(err) return } fmt.Println(res) // Output: // [1 2 3 4 5] } func ExampleEnumerable_Contains() { e := linq.FromSequence(1, 2, 3, 4, 5) res, err := e.Contains(-2, nil) if err != nil { fmt.Println(err) return } fmt.Println(res) res, err = e.Contains(3, nil) if err != nil { fmt.Println(err) return } fmt.Println(res) // Output: // false // true } func ExampleEnumerable_Count() { res, err := linq.FromSequence(1, 2, 3, 4, 5).Count() if err != nil { fmt.Println(err) return } fmt.Println(res) // Output: // 5 } func ExampleEnumerable_DefaultIfEmpty() { res, err := linq.FromSequence(1, 2, 3, 4, 5).DefaultIfEmpty(-1).ToSlice() if err != nil { fmt.Println(err) return } fmt.Println(res) res, err = linq.FromSequence().DefaultIfEmpty(-3).ToSlice() if err != nil { fmt.Println(err) return } fmt.Println(res) // Output: // [1 2 3 4 5] // [-3] } func ExampleEnumerable_Distinct() { res, err := linq.FromSequence(1, 1, 2, 2, 1, 3, 2, 1, 3, 2, 4, 1, 5).Distinct(nil).ToSlice() if err != nil { fmt.Println(err) return } fmt.Println(res) // Output: // [1 2 3 4 5] } func ExampleEnumerable_ElementAtOrDefault() { e := linq.FromSequence(1, 2, 3, 4, 5) res, err := e.ElementAtOrDefault(2, -1) if err != nil { fmt.Println(err) return } fmt.Println(res) res, err = e.ElementAtOrDefault(9, -1) if err != nil { fmt.Println(err) return } fmt.Println(res) // Output: // 3 // -1 } func ExampleEnumerable_Except() { res, err := linq.FromSequence(1, 2, 3, 4, 5).Except(linq.FromSequence(1, 3, 4), nil).ToSlice() if err != nil { fmt.Println(err) return } fmt.Println(res) // Output: // [2 5] } func ExampleEnumerable_FirstOrDefault() { e := linq.FromSequence(1, 2, 3, 4, 5) res, err := e.FirstOrDefault(func(v linq.T) bool { return v.(int) > 2 }, -1) if err != nil { fmt.Println(err) return } fmt.Println(res) res, err = e.FirstOrDefault(func(v linq.T) bool { return v.(int) > 7 }, -1) if err != nil { fmt.Println(err) return } fmt.Println(res) // Output: // 3 // -1 } func ExampleEnumerable_GroupBy() { type Product struct { Owner string Name string } data := []Product{ {Owner: "Google", Name: "Chrome"}, {Owner: "Microsoft", Name: "Windows"}, {Owner: "Google", Name: "GMail"}, {Owner: "Microsoft", Name: "VisualStudio"}, {Owner: "Google", Name: "GMail"}, {Owner: "Microsoft", Name: "XBox"}, {Owner: "Google", Name: "GMail"}, {Owner: "Google", Name: "AppEngine"}, {Owner: "Intel", Name: "ParallelStudio"}, {Owner: "Intel", Name: "VTune"}, {Owner: "Microsoft", Name: "Office"}, {Owner: "Intel", Name: "Edison"}, {Owner: "Google", Name: "GMail"}, {Owner: "Microsoft", Name: "PowerShell"}, {Owner: "Google", Name: "GMail"}, {Owner: "Google", Name: "GDrive"}, } res, err := linq.FromSlice(data).GroupBy(func(v linq.T) linq.T { return v.(Product).Owner }, func(v linq.T, en linq.Enumerator) linq.T { count, _ := linq.From(en).Count() return struct { Name string Count uint }{Name: v.(string), Count: count} }, nil).OrderBy(func(v linq.T) linq.T { return v.(struct { Name string Count uint }).Name }, func(v1, v2 linq.T) bool { return v1.(string) < v2.(string) }).ToSlice() if err != nil { fmt.Println(err) return } fmt.Println(res) // Output: // [{Google 8} {Intel 3} {Microsoft 5}] } func ExampleEnumerable_GroupJoin() { type Person struct { Name string } type Pet struct { Name string Age int Owner Person } owners := []Person{ {Name: "Hedlund, Magnus"}, {Name: "Adams, Terry"}, {Name: "Weiss, Charlotte"}, } pets := []Pet{ {Name: "Barley", Age: 8, Owner: owners[1]}, {Name: "Boots", Age: 4, Owner: owners[1]}, {Name: "Whiskers", Age: 1, Owner: owners[2]}, {Name: "Daisy", Age: 4, Owner: owners[0]}, } res, err := linq.FromSlice(owners).GroupJoin(linq.FromSlice(pets), func(v linq.T) linq.T { return v.(Person).Name }, func(v linq.T) linq.T { return v.(Pet).Owner.Name }, func(v1 linq.T, vs linq.Enumerator) linq.T { ret := v1.(Person).Name + ":" if err := vs.Reset(); err == nil { for ok, err := vs.Next(); ok && err == nil; ok, err = vs.Next() { ret += " " + vs.Value().(Pet).Name } } return ret + ";" }, nil).ToSlice() if err != nil { fmt.Println(err) return } fmt.Println(res) // Output: // [Hedlund, Magnus: Daisy; Adams, Terry: Barley Boots; Weiss, Charlotte: Whiskers;] } func ExampleEnumerable_Intersect() { res, err := linq.FromSequence(1, 2, 3, 4, 5).Intersect(linq.FromSequence(0, 2, 3, 6), nil).ToSlice() if err != nil { fmt.Println(err) return } fmt.Println(res) // Output: // [2 3] } func ExampleEnumerable_Join() { type Person struct { Name string } type Pet struct { Name string Age int Owner Person } owners := []Person{ {Name: "Hedlund, Magnus"}, {Name: "Adams, Terry"}, {Name: "Weiss, Charlotte"}, } pets := []Pet{ {Name: "Barley", Age: 8, Owner: owners[1]}, {Name: "Boots", Age: 4, Owner: owners[1]}, {Name: "Whiskers", Age: 1, Owner: owners[2]}, {Name: "Daisy", Age: 4, Owner: owners[0]}, } res, err := linq.FromSlice(owners).Join(linq.FromSlice(pets), func(v linq.T) linq.T { return v.(Person).Name }, func(v linq.T) linq.T { return v.(Pet).Owner.Name }, func(v1, v2 linq.T) linq.T { return fmt.Sprintf("{%v - %v}", v1.(Person).Name, v2.(Pet).Name) }, nil).ToSlice() if err != nil { fmt.Println(err) return } fmt.Println(res) // Output: // [{Hedlund, Magnus - Daisy} {Adams, Terry - Barley} {Adams, Terry - Boots} {Weiss, Charlotte - Whiskers}] } func ExampleEnumerable_LastOrDefault() { e := linq.FromSequence(1, 2, 3, 4, 5) res, err := e.LastOrDefault(func(v linq.T) bool { return v.(int) < 5 }, -1) if err != nil { fmt.Println(err) return } fmt.Println(res) res, err = e.LastOrDefault(func(v linq.T) bool { return v.(int) > 7 }, -1) if err != nil { fmt.Println(err) return } fmt.Println(res) // Output: // 4 // -1 } func ExampleEnumerable_OrderBy() { res, err := linq.FromSequence(5, 4, 1, 3, 2).OrderBy(func(v linq.T) linq.T { return v.(int) }, func(v1, v2 linq.T) bool { return v1.(int) < v2.(int) }).ToSlice() if err != nil { fmt.Println(err) return } fmt.Println(res) // Output: // [1 2 3 4 5] } func ExampleEnumerable_Reverse() { res, err := linq.FromSequence(5, 4, 3, 2, 1).Where(func(v linq.T) bool { return v.(int) < 4 }).Reverse().ToSlice() if err != nil { fmt.Println(err) return } fmt.Println(res) // Output: // [1 2 3] } func ExampleEnumerable_Select() { res, err := linq.FromSequence(1, 2, 3, 4, 5).Select(func(v linq.T) linq.T { return v.(int) * 10 }).ToSlice() if err != nil { fmt.Println(err) return } fmt.Println(res) // Output: // [10 20 30 40 50] } func ExampleEnumerable_SelectMany() { res, err := linq.FromSequence(1, 2, 3).SelectMany(func(v linq.T) linq.Enumerable { i := v.(int) return linq.FromSequence(i, i*10, i*100) }).ToSlice() if err != nil { fmt.Println(err) return } fmt.Println(res) // Output: // [1 10 100 2 20 200 3 30 300] } func ExampleEnumerable_SequenceEqual() { e := linq.FromSequence(1, 2, 3, 4, 5) res, err := e.SequenceEqual(linq.FromSequence(1, 2, 3, 4, 5), nil) if err != nil { fmt.Println(err) return } fmt.Println(res) res, err = e.SequenceEqual(linq.FromSequence(1, 3, 1, 4, 5), nil) if err != nil { fmt.Println(err) return } fmt.Println(res) res, err = e.SequenceEqual(e, nil) if err != nil { fmt.Println(err) return } fmt.Println(res) // Output: // true // false // true } func ExampleEnumerable_SkipWhile() { res, err := linq.FromSequence(1, 2, 3, 4, 5).SkipWhile(func(v linq.T) bool { return v.(int) < 3 }).ToSlice() if err != nil { fmt.Println(err) return } fmt.Println(res) // Output: // [3 4 5] } func ExampleEnumerable_TakeWhile() { res, err := linq.FromSequence(1, 2, 3, 4, 5).TakeWhile(func(v linq.T) bool { return v.(int) < 3 }).ToSlice() if err != nil { fmt.Println(err) return } fmt.Println(res) // Output: // [1 2] } func ExampleEnumerable_ToSlice() { res, err := linq.FromSequence(1, 2, 3, 4, 5).ToSlice() if err != nil { fmt.Println(err) return } fmt.Println(res) // Output: // [1 2 3 4 5] } func ExampleEnumerable_ToMap() { abc := []byte("abcdefghijklmnopqrstuvwxyz") res, err := linq.FromSlice(abc).ToMap(func(v linq.T) linq.T { return bytes.IndexByte(abc, v.(byte)) }) if err != nil { fmt.Println(err) return } for _, v := range []int{7, 4, 11, 11, 14} { fmt.Printf("%c", res[v]) } // Output: // hello } func ExampleEnumerable_Union() { res, err := linq.FromSequence(3, 9, 7, 9).Union(linq.FromSequence(3, 6, 4, 4, 9), nil).ToSlice() if err != nil { fmt.Println(err) return } fmt.Println(res) // Output: // [3 9 7 6 4] } func ExampleEnumerable_Where() { res, err := linq.FromSequence(0, 1, 2, 3, 4, 5).Where(func(v linq.T) bool { i := v.(int) return i > 1 && i < 4 }).ToSlice() if err != nil { fmt.Println(err) return } fmt.Println(res) // Output: // [2 3] } func ExampleEnumerable_Zip() { res, err := linq.FromSequence(1, 2, 3, 4).Zip(linq.FromSequence("one", "two", "three"), func(v1, v2 linq.T) linq.T { return fmt.Sprintf("%v:%v", v1, v2) }).ToSlice() if err != nil { fmt.Println(err) return } fmt.Println(res) // Output: // [1:one 2:two 3:three] }
package main import ( "fmt" ) func main() { fmt.Println(suggestedProducts([]string{ "mobile", "mouse", "moneypot", "monitor", "mousepad", }, "mouse")) } func suggestedProducts(products []string, searchWord string) [][]string { t := Constructor() for _, p := range products { t.Insert(p) } var ans [][]string for i := range searchWord { ans = append(ans, t.Search(searchWord[:i+1])) } return ans } type Trie struct { end bool next [26]*Trie } func Constructor() *Trie { return &Trie{} } // 常规写法 func (this *Trie) Insert(word string) { node := this for _, v := range word { v -= 'a' if node.next[v] == nil { node.next[v] = new(Trie) } node = node.next[v] } node.end = true } func (this *Trie) Search(word string) []string { node := this.searchNode(word) // 找到word的结尾 if node == nil { // 没找到 return nil } var ans []string var dfs func(node *Trie, arr []byte) dfs = func(node *Trie, arr []byte) { if len(ans) == 3 { // 找齐了,不需要继续去找 return } if node.end { // 当前是一个字符串的结尾,那就加进来 ans = append(ans, string(arr)) } for i, v := range node.next { if v != nil { // 当前字符不为空,那就根据当前字符索引继续搜 dfs(v, append(arr, 'a'+byte(i))) } } } dfs(node, []byte(word)) // 当前路由的前缀加上,,开始搜 return ans } func (this *Trie) searchNode(word string) *Trie { node := this for _, v := range word { v -= 'a' if node.next[v] == nil { return nil } node = node.next[v] } return node }
package main import ( "fmt" "myGo/genereate/shell/types" ) func main() { var pl types.PersonList pl = append(pl, &types.Person{Name: "Jane", Age: 32}) pl = append(pl, &types.Person{Name: "Ed", Age: 27}) pl2 := pl.Filter(func(p *types.Person) bool { return p.Age > 30 }) for _, p := range pl2 { fmt.Println(p) } }
package visagoapi import ( "fmt" "sort" "strings" ) const ( // ColorsFeature is the value to enable the color features. ColorsFeature = "colors" // FacesFeature is the value to enable the face detection features. FacesFeature = "faces" // TagsFeature is the value to enable the tagging features. TagsFeature = "tags" ) var ( enableBlacklist = false enableWhitelist = false blacklist = make(map[string]interface{}) whitelist = make(map[string]interface{}) defaultFeatures = []string{ColorsFeature, FacesFeature, TagsFeature} ) // Plugin interface provides a way to query // different Visual AI backends. Plugins should // initialize themselves with a PluginConfig. type Plugin interface { Perform(*PluginConfig) (string, PluginResult, error) Setup() error Reset() RequestIDs() ([]string, error) } // PluginResult is an interface on returned objects // from the API. All result methods will require // a string containing the requestID returned from // Perform() and a minimum confidence score. Passing // in 0 gets you all tags. type PluginResult interface { Tags(string, float64) (map[string]map[string]*PluginTagResult, error) Faces(string) (map[string][]*PluginFaceResult, error) Colors(string) (map[string]map[string]*PluginColorResult, error) } // PluginTagResult are the attributes on a tag. The score // is a value from 0 and 1. type PluginTagResult struct { Name string `json:"name,omitempty"` Score float64 `json:"score,omitempty"` // Source should not be set directly by a plugin. Source string `json:"source,omitempty"` } // PluginColorResult are the attributes for a color. type PluginColorResult struct { Hex string `json:"hex,omitempty"` Score float64 `json:"score,omitempty"` PixelFraction float64 `json:"pixel_fraction,omitempty"` Red float64 `json:"red,omitempty"` Green float64 `json:"green,omitempty"` Blue float64 `json:"blue,omitempty"` Alpha float64 `json:"alpha,omitempty"` // Source should not be set directly by a plugin. Source string `json:"source,omitempty"` } // PluginFaceResult are the attributes on a face match. type PluginFaceResult struct { BoundingPoly *BoundingPoly `json:"bounding_poly,omitempty"` DetectionScore float64 `json:"detection_score,omitempty"` JoyLikelihood string `json:"joy_likelihood,omitempty"` SorrowLikelihood string `json:"sorrow_likelihood,omitempty"` AngerLikelihood string `json:"anger_likelihood,omitempty"` SurpriseLikelihood string `json:"surprise_likelihood,omitempty"` UnderExposedLikelihood string `json:"under_exposed_likelihood,omitempty"` BlurredLikelihood string `json:"blurred_likelihood,omitempty"` HeadwearLikelihood string `json:"headwear_likelihood,omitempty"` // Source should not be set directly by a plugin. Source string `json:"source,omitempty"` } // PluginConfig is used to pass configuration // data to plugins when they load. type PluginConfig struct { URLs []string `json:"urls"` Files []string `json:"files"` Verbose bool `json:"verbose"` TagScore float64 `json:"tag_score"` Features []string `json:"features"` } // EnabledFeature lets you check if a particular feature // is available. func (p *PluginConfig) EnabledFeature(f string) bool { features := p.Features if len(p.Features) == 0 { features = defaultFeatures } for _, feature := range features { if feature == f { return true } } return false } // Plugins tracks loaded plugins. var Plugins map[string]Plugin func init() { Plugins = make(map[string]Plugin) } // AddPlugin should be called within your plugin's init() func. // This will register the plugin so it can be used. func AddPlugin(name string, plugin Plugin) { Plugins[name] = plugin } // SetBlacklist filters out unneeded plugins. func SetBlacklist(b []string) { for _, v := range b { blacklist[v] = nil } if len(blacklist) > 0 { enableBlacklist = true } } // SetWhitelist sets an exact list of supported plugins. func SetWhitelist(w []string) { for _, v := range w { whitelist[v] = nil } if len(whitelist) > 0 { enableWhitelist = true } } // DisplayPlugins displays all the loaded plugins. func DisplayPlugins() string { names := PluginNames() return fmt.Sprintf("%s\n", strings.Join(names, "\n")) } // PluginNames returns a sorted slice of plugin names // applying both the whitelist and then the blacklist. func PluginNames() []string { names := []string{} for key := range Plugins { if enableWhitelist { _, ok := whitelist[key] if !ok { continue } } if enableBlacklist { _, ok := blacklist[key] if ok { continue } } names = append(names, key) } sort.Strings(names) return names }
package gorm_test import ( "fmt" gorm "github.com/jinzhu/gorm" _ "github.com/jinzhu/gorm/dialects/postgres" "log" "sync" "testing" "time" ) type ( PersonX struct { ID uint32 `gorm:"PRIMARY_KEY;AUTO_INCREMENT" json:"id"` Name string `gorm:"size:255;not null;unique" json:"Name"` Nickname string `gorm:"size:255" json:"nickname"` Email string `gorm:"size:255" json:"email"` Password string `gorm:"size:255" json:"password"` CreatedAt time.Time `gorm:"default:CURRENT_TIMESTAMP" json:"created_at"` } ) func (PersonX) TableName() string { return "person" } func NewDBCnt() *gorm.DB { connStr := fmt.Sprintf("host=%s user=%s dbname=%s sslmode=disable password=%s", "127.0.0.1", //viper.GetString("DB_HOST"), "root", //viper.GetString("DB_USER"), "test", //viper.GetString("DB_NAME"), "password", ///viper.GetString("DB_PASS"), ) db, err := gorm.Open("postgres", connStr) if err != nil { log.Println(err) } db.DB().SetMaxOpenConns(500) return db } func Test_cnt(t *testing.T) { bean := &PersonX{} db := NewDBCnt() log.Println("after cnt ") db.CreateTable(bean) db.AutoMigrate(bean) log.Println("create table okt ") } func Test_insert(t *testing.T) { db := NewDBCnt() h := 100000 var wg sync.WaitGroup wg.Add(h) for i := 0; i < h; i++ { j := i go func() { bean := &PersonX{ Name: fmt.Sprint("aaaaa", j, "55ssssss5", j), } if err := db.Save(bean).Error; err != nil { fmt.Println(err) } else { fmt.Println("append ok") } }() } wg.Wait() }
// Copyright 2020 PingCAP, Inc. Licensed under Apache-2.0. package utils import ( "context" "testing" "time" "github.com/stretchr/testify/require" ) type testWriter struct { fn func(string) } func (t *testWriter) Write(p []byte) (int, error) { t.fn(string(p)) return len(p), nil } func TestProgress(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) var p string pCh2 := make(chan string, 2) progress2 := NewProgressPrinter("test", 2, false) progress2.goPrintProgress(ctx, nil, &testWriter{ fn: func(p string) { pCh2 <- p }, }) progress2.Inc() time.Sleep(2 * time.Second) p = <-pCh2 require.Contains(t, p, `"P":"50.00%"`) progress2.Inc() time.Sleep(2 * time.Second) p = <-pCh2 require.Contains(t, p, `"P":"100.00%"`) progress2.Inc() time.Sleep(2 * time.Second) p = <-pCh2 require.Contains(t, p, `"P":"100.00%"`) progress2.Close() pCh4 := make(chan string, 4) progress4 := NewProgressPrinter("test", 4, false) progress4.goPrintProgress(ctx, nil, &testWriter{ fn: func(p string) { pCh4 <- p }, }) progress4.Inc() time.Sleep(2 * time.Second) p = <-pCh4 require.Contains(t, p, `"P":"25.00%"`) progress4.Inc() progress4.Close() time.Sleep(2 * time.Second) p = <-pCh4 require.Contains(t, p, `"P":"100.00%"`) pCh8 := make(chan string, 8) progress8 := NewProgressPrinter("test", 8, false) progress8.goPrintProgress(ctx, nil, &testWriter{ fn: func(p string) { pCh8 <- p }, }) progress8.Inc() progress8.Inc() time.Sleep(2 * time.Second) p = <-pCh8 require.Contains(t, p, `"P":"25.00%"`) // Cancel should stop progress at the current position. cancel() p = <-pCh8 require.Contains(t, p, `"P":"25.00%"`) progress8.Close() }
// Copyright 2017 Vector Creations Ltd // // 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 routing import ( "net/http" "time" "github.com/gorilla/mux" "github.com/matrix-org/dendrite/clientapi/producers" "github.com/matrix-org/dendrite/common/config" "github.com/matrix-org/dendrite/federationapi/readers" "github.com/matrix-org/dendrite/federationapi/writers" "github.com/matrix-org/dendrite/roomserver/api" "github.com/matrix-org/gomatrixserverlib" "github.com/matrix-org/util" "github.com/prometheus/client_golang/prometheus" ) const ( pathPrefixV2Keys = "/_matrix/key/v2" pathPrefixV1Federation = "/_matrix/federation/v1" ) // Setup registers HTTP handlers with the given ServeMux. func Setup( apiMux *mux.Router, cfg config.Dendrite, query api.RoomserverQueryAPI, producer *producers.RoomserverProducer, keys gomatrixserverlib.KeyRing, federation *gomatrixserverlib.FederationClient, ) { v2keysmux := apiMux.PathPrefix(pathPrefixV2Keys).Subrouter() v1fedmux := apiMux.PathPrefix(pathPrefixV1Federation).Subrouter() localKeys := makeAPI("localkeys", func(req *http.Request) util.JSONResponse { return readers.LocalKeys(req, cfg) }) // Ignore the {keyID} argument as we only have a single server key so we always // return that key. // Even if we had more than one server key, we would probably still ignore the // {keyID} argument and always return a response containing all of the keys. v2keysmux.Handle("/server/{keyID}", localKeys) v2keysmux.Handle("/server/", localKeys) v1fedmux.Handle("/send/{txnID}/", makeAPI("federation_send", func(req *http.Request) util.JSONResponse { vars := mux.Vars(req) return writers.Send( req, gomatrixserverlib.TransactionID(vars["txnID"]), time.Now(), cfg, query, producer, keys, federation, ) }, )) v1fedmux.Handle("/invite/{roomID}/{eventID}", makeAPI("federation_invite", func(req *http.Request) util.JSONResponse { vars := mux.Vars(req) return writers.Invite( req, vars["roomID"], vars["eventID"], time.Now(), cfg, producer, keys, ) }, )) } func makeAPI(metricsName string, f func(*http.Request) util.JSONResponse) http.Handler { h := util.NewJSONRequestHandler(f) return prometheus.InstrumentHandler(metricsName, util.MakeJSONAPI(h)) }
package sdl type SDL_TouchID int64 type SDL_FingerID int64 type SDL_Finger struct { Id SDL_FingerID X float32 Y float32 Pressure float32 }
package game import ( "fmt" "math/rand" ) // GeneratePlayers generate players func GeneratePlayers() []Player { var roles = basicConfiguration() roles = shuffle(roles) players := make([]Player, len(roles)) for i, r := range roles { players[i].role = r players[i].id = i + 1 } for _, v := range players { fmt.Println(v) } return players } // shuffle role list func shuffle(src []Role) []Role { dest := make([]Role, len(src)) perm := rand.Perm(len(src)) for i, v := range perm { dest[v] = src[i] } return dest } // basicConfiguration baisc twelve people configuration func basicConfiguration() []Role { roles := make([]Role, 0) wolf := Role{"wolf"} villager := Role{"villager"} seer := Role{"seer"} witch := Role{"witch"} hunter := Role{"hunter"} idiom := Role{"idiom"} for i := 0; i < 4; i++ { roles = append(roles, wolf) } for i := 0; i < 4; i++ { roles = append(roles, villager) } roles = append(roles, seer) roles = append(roles, witch) roles = append(roles, hunter) roles = append(roles, idiom) return roles }
package main import ( "../lib/libocit" "encoding/json" "fmt" "os" "path" "time" ) type ServerConfig struct { TSurl string CPurl string Debug bool } //public variable var pub_config ServerConfig var pub_casedir string //TODO the following container function should move the the container service func apply_container(req libocit.Require) { var files []string for index := 0; index < len(req.Files); index++ { files = append(files, path.Join(pub_casedir, req.Files[index])) } tar_url := libocit.TarFilelist(files, pub_casedir, req.Class) post_url := pub_config.CPurl + "/upload" var params map[string]string libocit.SendFile(post_url, tar_url, params) apiurl := pub_config.CPurl + "/build" b, jerr := json.Marshal(req) if jerr != nil { fmt.Println("Failed to marshal json:", jerr) return } libocit.SendCommand(apiurl, []byte(b)) } func setContainerClass(deploys []libocit.Deploy, req libocit.Require) { for index := 0; index < len(deploys); index++ { deploy := deploys[index] for c_index := 0; c_index < len(deploy.Containers); c_index++ { if deploy.Containers[c_index].Class == req.Class { deploy.Containers[c_index].Distribution = req.Distribution deploy.Containers[c_index].Version = req.Version } } } } //Usage: ./scheduler ./demo.tar.gz func main() { var case_file string config_content := libocit.ReadFile("./scheduler.conf") json.Unmarshal([]byte(config_content), &pub_config) arg_num := len(os.Args) if arg_num < 2 { case_file = "./democase.tar.gz" } else { case_file = os.Args[1] } post_url := pub_config.TSurl + "/task" fmt.Println(post_url) var params map[string]string params = make(map[string]string) //TODO: use system time as the id now id := fmt.Sprintf("%d", time.Now().Unix()) params["id"] = id ret := libocit.SendFile(post_url, case_file, params) fmt.Println(ret) return }
package mat import ( "fmt" "github.com/stretchr/testify/assert" "math" "testing" ) func TestRotateX(t *testing.T) { point := NewPoint(0, 1, 0) halfQuarterRotation := RotateX(math.Pi / 4) fullQuarterRotation := RotateX(math.Pi / 2) p2 := MultiplyByTuple(halfQuarterRotation, point) assert.Equal(t, 0.0, p2.Get(0)) assert.InEpsilon(t, math.Sqrt(2.0)/2.0, p2.Get(1), Epsilon, fmt.Sprintf("expected %v, got %v", math.Sqrt(2.0)/2.0, p2.Get(1))) assert.InEpsilon(t, math.Sqrt(2.0)/2.0, p2.Get(2), Epsilon, fmt.Sprintf("expected %v, got %v", math.Sqrt(2.0)/2.0, p2.Get(2))) p3 := MultiplyByTuple(fullQuarterRotation, point) assert.Equal(t, 0.0, p3.Get(0)) assert.True(t, Eq(0.0, p3.Get(1))) assert.Equal(t, 1.0, p3.Get(2)) } func TestRotateXInverse(t *testing.T) { point := NewPoint(0, 1, 0) halfQuarterRotation := RotateX(math.Pi / 4) inverseHQ := Inverse(halfQuarterRotation) p2 := MultiplyByTuple(inverseHQ, point) assert.Equal(t, 0.0, p2.Get(0)) assert.InEpsilon(t, math.Sqrt(2.0)/2.0, p2.Get(1), Epsilon) assert.InEpsilon(t, -math.Sqrt(2.0)/2.0, p2.Get(2), Epsilon) } func TestRotateY(t *testing.T) { point := NewPoint(0, 0, 1) halfQuarterRotation := RotateY(math.Pi / 4) fullQuarterRotation := RotateY(math.Pi / 2) p2 := MultiplyByTuple(halfQuarterRotation, point) assert.InEpsilon(t, math.Sqrt(2.0)/2.0, p2.Get(0), Epsilon, fmt.Sprintf("expected %v, got %v", math.Sqrt(2.0)/2.0, p2.Get(0))) assert.Equal(t, 0.0, p2.Get(1)) assert.InEpsilon(t, math.Sqrt(2.0)/2.0, p2.Get(2), Epsilon, fmt.Sprintf("expected %v, got %v", math.Sqrt(2.0)/2.0, p2.Get(2))) p3 := MultiplyByTuple(fullQuarterRotation, point) assert.Equal(t, 1.0, p3.Get(0)) assert.True(t, Eq(0.0, p3.Get(1))) assert.True(t, Eq(0.0, p3.Get(2))) } func TestRotateZ(t *testing.T) { point := NewPoint(0, 1, 0) halfQuarterRotation := RotateZ(math.Pi / 4) fullQuarterRotation := RotateZ(math.Pi / 2) p2 := MultiplyByTuple(halfQuarterRotation, point) assert.InEpsilon(t, -math.Sqrt(2.0)/2.0, p2.Get(0), Epsilon, fmt.Sprintf("expected %v, got %v", math.Sqrt(2.0)/2.0, p2.Get(0))) assert.InEpsilon(t, math.Sqrt(2.0)/2.0, p2.Get(1), Epsilon, fmt.Sprintf("expected %v, got %v", math.Sqrt(2.0)/2.0, p2.Get(1))) assert.Equal(t, 0.0, p2.Get(2)) p3 := MultiplyByTuple(fullQuarterRotation, point) assert.Equal(t, -1.0, p3.Get(0)) assert.True(t, Eq(0.0, p3.Get(1))) assert.True(t, Eq(0.0, p3.Get(2))) }
package todo import ( "context" "fmt" ) type SessionRepo interface { NextID(context.Context) (SessionID, error) Pull(context.Context) (*Session, error) Push(context.Context, *Session) error Delete(context.Context) error } func NewSession(id SessionID, userID UserID) (*Session, error) { s := new(Session) if err := s.setID(id); err != nil { return nil, err } if err := s.setUserID(userID); err != nil { return nil, err } return s, nil } func RecoverSession(id SessionID, userID UserID) *Session { return &Session{ id: id, userID: userID, } } type Session struct { id SessionID userID UserID } func (s *Session) ID() SessionID { return s.id } func (s *Session) setID(id SessionID) error { if id == "" { return fmt.Errorf("empty id") } s.id = id return nil } func (s *Session) UserID() UserID { return s.userID } func (s *Session) setUserID(id UserID) error { if id == "" { return fmt.Errorf("empty user id") } s.userID = id return nil } type SessionID string
package configs import ( "fmt" "github.com/gomodule/redigo/redis" "os" ) var ( redisConn redis.Conn redisErr error ) func InitRedis() { var port = os.Getenv("REDIS_PORT") redisConn, redisErr = redis.Dial("tcp", "localhost:"+port) if redisErr != nil { fmt.Println("Redis Connection Error:", err.Error()) return } } func GetRedis() redis.Conn { return redisConn } func GetRedisDb() string { return os.Getenv("REDIS_DB") }
package websocket import ( "fmt" "log" "net/http" "github.com/gorilla/websocket" ) var upgrader = websocket.Upgrader{ ReadBufferSize: 1024, WriteBufferSize: 1024, CheckOrigin: func(r *http.Request) bool { return true }, } func upgrade(w http.ResponseWriter, r *http.Request) (*websocket.Conn, error) { conn, err := upgrader.Upgrade(w, r, nil) if err != nil { log.Println(err) return nil, err } return conn, nil } // ServeWs defines our WebSocket endpoint func ServeWs(wsServer *WsServer, w http.ResponseWriter, r *http.Request) { conn, err := upgrade(w, r) if err != nil { fmt.Fprintf(w, "%+V\n", err) } client := newClient(conn, wsServer) // Allow connection of memory referenced by the caller by doing // all work in new goroutines. go client.writePump() go client.readPump() wsServer.register <- client }
/* Copyright 2019 Packet 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 v1alpha1 import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" ) // EDIT THIS FILE! THIS IS SCAFFOLDING FOR YOU TO OWN! // NOTE: json tags are required. Any new fields you add must have json tags for the fields to be serialized. // +genclient // +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object // PacketClusterProviderSpec is the Schema for the packetclusterproviderspecs API // +k8s:openapi-gen=true type PacketClusterProviderSpec struct { metav1.TypeMeta `json:",inline"` metav1.ObjectMeta `json:"metadata,omitempty"` ProjectID string `json:"projectID"` // CAKeyPair is the key pair for ca certs. CAKeyPair KeyPair `json:"caKeyPair,omitempty"` } // KeyPair is how operators can supply custom keypairs for kubeadm to use. type KeyPair struct { // base64 encoded cert and key Cert []byte `json:"cert"` Key []byte `json:"key"` } // +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object // PacketClusterProviderSpecList contains a list of PacketClusterProviderSpec type PacketClusterProviderSpecList struct { metav1.TypeMeta `json:",inline"` metav1.ListMeta `json:"metadata,omitempty"` Items []PacketClusterProviderSpec `json:"items"` } func init() { SchemeBuilder.Register(&PacketClusterProviderSpec{}, &PacketClusterProviderSpecList{}) }
// Copyright 2023 Google LLC. All Rights Reserved. // // 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 monitoring import ( "context" "fmt" "github.com/GoogleCloudPlatform/declarative-resource-client-library/dcl" dclService "github.com/GoogleCloudPlatform/declarative-resource-client-library/services/google/monitoring/beta" "github.com/GoogleCloudPlatform/declarative-resource-client-library/unstructured" ) type NotificationChannel struct{} func NotificationChannelToUnstructured(r *dclService.NotificationChannel) *unstructured.Resource { u := &unstructured.Resource{ STV: unstructured.ServiceTypeVersion{ Service: "monitoring", Version: "beta", Type: "NotificationChannel", }, Object: make(map[string]interface{}), } if r.Description != nil { u.Object["description"] = *r.Description } if r.DisplayName != nil { u.Object["displayName"] = *r.DisplayName } if r.Enabled != nil { u.Object["enabled"] = *r.Enabled } if r.Labels != nil { rLabels := make(map[string]interface{}) for k, v := range r.Labels { rLabels[k] = v } u.Object["labels"] = rLabels } if r.Name != nil { u.Object["name"] = *r.Name } if r.Project != nil { u.Object["project"] = *r.Project } if r.Type != nil { u.Object["type"] = *r.Type } if r.UserLabels != nil { rUserLabels := make(map[string]interface{}) for k, v := range r.UserLabels { rUserLabels[k] = v } u.Object["userLabels"] = rUserLabels } if r.VerificationStatus != nil { u.Object["verificationStatus"] = string(*r.VerificationStatus) } return u } func UnstructuredToNotificationChannel(u *unstructured.Resource) (*dclService.NotificationChannel, error) { r := &dclService.NotificationChannel{} if _, ok := u.Object["description"]; ok { if s, ok := u.Object["description"].(string); ok { r.Description = dcl.String(s) } else { return nil, fmt.Errorf("r.Description: expected string") } } if _, ok := u.Object["displayName"]; ok { if s, ok := u.Object["displayName"].(string); ok { r.DisplayName = dcl.String(s) } else { return nil, fmt.Errorf("r.DisplayName: expected string") } } if _, ok := u.Object["enabled"]; ok { if b, ok := u.Object["enabled"].(bool); ok { r.Enabled = dcl.Bool(b) } else { return nil, fmt.Errorf("r.Enabled: expected bool") } } if _, ok := u.Object["labels"]; ok { if rLabels, ok := u.Object["labels"].(map[string]interface{}); ok { m := make(map[string]string) for k, v := range rLabels { if s, ok := v.(string); ok { m[k] = s } } r.Labels = m } else { return nil, fmt.Errorf("r.Labels: expected map[string]interface{}") } } if _, ok := u.Object["name"]; ok { if s, ok := u.Object["name"].(string); ok { r.Name = dcl.String(s) } else { return nil, fmt.Errorf("r.Name: expected string") } } if _, ok := u.Object["project"]; ok { if s, ok := u.Object["project"].(string); ok { r.Project = dcl.String(s) } else { return nil, fmt.Errorf("r.Project: expected string") } } if _, ok := u.Object["type"]; ok { if s, ok := u.Object["type"].(string); ok { r.Type = dcl.String(s) } else { return nil, fmt.Errorf("r.Type: expected string") } } if _, ok := u.Object["userLabels"]; ok { if rUserLabels, ok := u.Object["userLabels"].(map[string]interface{}); ok { m := make(map[string]string) for k, v := range rUserLabels { if s, ok := v.(string); ok { m[k] = s } } r.UserLabels = m } else { return nil, fmt.Errorf("r.UserLabels: expected map[string]interface{}") } } if _, ok := u.Object["verificationStatus"]; ok { if s, ok := u.Object["verificationStatus"].(string); ok { r.VerificationStatus = dclService.NotificationChannelVerificationStatusEnumRef(s) } else { return nil, fmt.Errorf("r.VerificationStatus: expected string") } } return r, nil } func GetNotificationChannel(ctx context.Context, config *dcl.Config, u *unstructured.Resource) (*unstructured.Resource, error) { c := dclService.NewClient(config) r, err := UnstructuredToNotificationChannel(u) if err != nil { return nil, err } r, err = c.GetNotificationChannel(ctx, r) if err != nil { return nil, err } return NotificationChannelToUnstructured(r), nil } func ListNotificationChannel(ctx context.Context, config *dcl.Config, project string) ([]*unstructured.Resource, error) { c := dclService.NewClient(config) l, err := c.ListNotificationChannel(ctx, project) if err != nil { return nil, err } var resources []*unstructured.Resource for { for _, r := range l.Items { resources = append(resources, NotificationChannelToUnstructured(r)) } if !l.HasNext() { break } if err := l.Next(ctx, c); err != nil { return nil, err } } return resources, nil } func ApplyNotificationChannel(ctx context.Context, config *dcl.Config, u *unstructured.Resource, opts ...dcl.ApplyOption) (*unstructured.Resource, error) { c := dclService.NewClient(config) r, err := UnstructuredToNotificationChannel(u) if err != nil { return nil, err } if ush := unstructured.FetchStateHint(opts); ush != nil { sh, err := UnstructuredToNotificationChannel(ush) if err != nil { return nil, err } opts = append(opts, dcl.WithStateHint(sh)) } r, err = c.ApplyNotificationChannel(ctx, r, opts...) if err != nil { return nil, err } return NotificationChannelToUnstructured(r), nil } func NotificationChannelHasDiff(ctx context.Context, config *dcl.Config, u *unstructured.Resource, opts ...dcl.ApplyOption) (bool, error) { c := dclService.NewClient(config) r, err := UnstructuredToNotificationChannel(u) if err != nil { return false, err } if ush := unstructured.FetchStateHint(opts); ush != nil { sh, err := UnstructuredToNotificationChannel(ush) if err != nil { return false, err } opts = append(opts, dcl.WithStateHint(sh)) } opts = append(opts, dcl.WithLifecycleParam(dcl.BlockDestruction), dcl.WithLifecycleParam(dcl.BlockCreation), dcl.WithLifecycleParam(dcl.BlockModification)) _, err = c.ApplyNotificationChannel(ctx, r, opts...) if err != nil { if _, ok := err.(dcl.ApplyInfeasibleError); ok { return true, nil } return false, err } return false, nil } func DeleteNotificationChannel(ctx context.Context, config *dcl.Config, u *unstructured.Resource) error { c := dclService.NewClient(config) r, err := UnstructuredToNotificationChannel(u) if err != nil { return err } return c.DeleteNotificationChannel(ctx, r) } func NotificationChannelID(u *unstructured.Resource) (string, error) { r, err := UnstructuredToNotificationChannel(u) if err != nil { return "", err } return r.ID() } func (r *NotificationChannel) STV() unstructured.ServiceTypeVersion { return unstructured.ServiceTypeVersion{ "monitoring", "NotificationChannel", "beta", } } func (r *NotificationChannel) SetPolicyMember(ctx context.Context, config *dcl.Config, resource *unstructured.Resource, member *unstructured.Resource) (*unstructured.Resource, error) { return nil, unstructured.ErrNoSuchMethod } func (r *NotificationChannel) GetPolicyMember(ctx context.Context, config *dcl.Config, resource *unstructured.Resource, role, member string) (*unstructured.Resource, error) { return nil, unstructured.ErrNoSuchMethod } func (r *NotificationChannel) DeletePolicyMember(ctx context.Context, config *dcl.Config, resource *unstructured.Resource, member *unstructured.Resource) error { return unstructured.ErrNoSuchMethod } func (r *NotificationChannel) SetPolicy(ctx context.Context, config *dcl.Config, resource *unstructured.Resource, policy *unstructured.Resource) (*unstructured.Resource, error) { return nil, unstructured.ErrNoSuchMethod } func (r *NotificationChannel) SetPolicyWithEtag(ctx context.Context, config *dcl.Config, resource *unstructured.Resource, policy *unstructured.Resource) (*unstructured.Resource, error) { return nil, unstructured.ErrNoSuchMethod } func (r *NotificationChannel) GetPolicy(ctx context.Context, config *dcl.Config, resource *unstructured.Resource) (*unstructured.Resource, error) { return nil, unstructured.ErrNoSuchMethod } func (r *NotificationChannel) Get(ctx context.Context, config *dcl.Config, resource *unstructured.Resource) (*unstructured.Resource, error) { return GetNotificationChannel(ctx, config, resource) } func (r *NotificationChannel) Apply(ctx context.Context, config *dcl.Config, resource *unstructured.Resource, opts ...dcl.ApplyOption) (*unstructured.Resource, error) { return ApplyNotificationChannel(ctx, config, resource, opts...) } func (r *NotificationChannel) HasDiff(ctx context.Context, config *dcl.Config, resource *unstructured.Resource, opts ...dcl.ApplyOption) (bool, error) { return NotificationChannelHasDiff(ctx, config, resource, opts...) } func (r *NotificationChannel) Delete(ctx context.Context, config *dcl.Config, resource *unstructured.Resource) error { return DeleteNotificationChannel(ctx, config, resource) } func (r *NotificationChannel) ID(resource *unstructured.Resource) (string, error) { return NotificationChannelID(resource) } func init() { unstructured.Register(&NotificationChannel{}) }
package main import ( //"io/ioutil" "log" "net/http" "net/url" ) func main() { //Get方法 resp, err := http.Get("http://localhost:8000/") if err != nil { log.Fatal(err) } defer resp.Body.Close() //body, err := ioutil.ReadAll(resp.Body) //_, err = http.PostForm("http://localhost:8000/PostForm", //url.Values{"key": {"Value"},"id": {"123"}}) var vs url.Values vs = make(url.Values) vs.Add("key", "Rust") vs.Add("id", "go") _, err = http.PostForm("http://localhost:8000/PostForm", vs) }
package main import ( "fmt" ) /** * Definition for singly-linked list. * type ListNode struct { * Val int * Next *ListNode * } */ type ListNode struct { Val int Next *ListNode } func mergeTwoLists(l1 *ListNode, l2 *ListNode) *ListNode { var head, tmpNode, nextNode *ListNode for ;l1 != nil && l2 !=nil; { if l1.Val <= l2.Val { tmpNode = l1 l1 = l1.Next } else { tmpNode = l2 l2 = l2.Next } if head == nil { head = tmpNode nextNode = head } else { nextNode.Next = tmpNode nextNode = tmpNode } } tmpNode = nil if l1 != nil { tmpNode = l1 } else if l2 != nil { tmpNode = l2 } if nextNode == nil { head = tmpNode } else { nextNode.Next = tmpNode } return head } func main() { head1 := &ListNode{Val:1} head1.Next = &ListNode{Val:2} head1.Next.Next = &ListNode{Val:4} head2 := &ListNode{Val:1} head2.Next = &ListNode{Val:3} head2.Next.Next = &ListNode{Val:4} result := mergeTwoLists(head1, head2) for ;result != nil; { fmt.Printf("%d->", result.Val) result = result.Next } }
package main import ( "io" "io/ioutil" "net/http" ) type RawTransactionResponse struct { Success bool `json:"success"` ErrMsg string `json:"errmsg"` } func sendRawTransaction(tx io.Reader) (resp RawTransactionResponse, err error) { for _, endpoint := range esploras() { w, errW := http.Post(endpoint+"/tx", "text/plain", tx) defer w.Body.Close() if errW != nil { err = errW continue } if w.StatusCode >= 300 { msg, _ := ioutil.ReadAll(w.Body) return RawTransactionResponse{false, string(msg)}, nil } return RawTransactionResponse{true, ""}, nil } return resp, err }
package main import ( "fmt" "github.com/bitmaelum/bitmaelum-suite/internal" "github.com/bitmaelum/bitmaelum-suite/internal/config" "github.com/bitmaelum/bitmaelum-suite/internal/container" "github.com/bitmaelum/bitmaelum-suite/pkg/address" "github.com/sirupsen/logrus" ) type options struct { Config string `short:"c" long:"config" description:"Path to your configuration file"` Address string `short:"a" long:"address" description:"Address to resolve"` } var opts options func main() { internal.ParseOptions(&opts) config.LoadClientConfig(opts.Config) addr, err := address.NewHash(opts.Address) if err != nil { logrus.Fatal(err) } svc := container.GetResolveService() info, err := svc.Resolve(*addr) if err != nil { logrus.Fatal(err) } fmt.Printf("BitMaelum address '%s' resolves to %s\n", opts.Address, info.Server) fmt.Printf("Hash: %s\n", info.Hash) fmt.Printf("Public key:\n%s\n", info.PublicKey.String()) }
// generated by stringer -type=ZookeeperError; DO NOT EDIT package gozoo import "fmt" const _ZookeeperError_name = "ZooOkZooSystemErrorZooRuntimeInconsistencyErrorZooDataInconsistencyErrorZooConnectionLossErrorZooMarshallingErrorZooUnimplementedErrorZooOperationTimeoutErrorZooBadArgumentsErrorZooInvalidStateErrorZooApiErrorZooNoNodeErrorZooNoAuthErrorZooBadVersionErrorZooNoChildrenForEphemeralsErrorZooNodeExistsErrorZooNotEmptyErrorZooSessionExpiredErrorZooInvalidCallbackErrorZooInvalidAclErrorZooAuthFailedErrorZooClosingErrorZooNothingErrorZooSessionMovedErrorZooUnknownError" var _ZookeeperError_index = [...]uint16{0, 5, 19, 47, 72, 94, 113, 134, 158, 178, 198, 209, 223, 237, 255, 286, 304, 320, 342, 365, 383, 401, 416, 431, 451, 466} func (i ZookeeperError) String() string { if i < 0 || i+1 >= ZookeeperError(len(_ZookeeperError_index)) { return fmt.Sprintf("ZookeeperError(%d)", i) } return _ZookeeperError_name[_ZookeeperError_index[i]:_ZookeeperError_index[i+1]] }
package main import ( "fmt" "log" "os" "os/exec" "strconv" "syscall" "time" ) func main() { var cmdstr string var sampletime int if len(os.Args) >= 2 { fmt.Println(os.Args[1]) cmdstr = os.Args[1] } else { fmt.Println("/usr/bin/yes") cmdstr = "/usr/bin/yes" } if len(os.Args) >= 3 { var err error sampletime, err = strconv.Atoi(os.Args[2]) fmt.Println(sampletime) if err != nil { fmt.Println(err) } } else { sampletime = 2 } //cmdstr := "/usr/bin/yes" done := make(chan bool) cmd := exec.Command(cmdstr) go func() { cmd.Run() mem := cmd.ProcessState.SysUsage().(*syscall.Rusage).Maxrss cpuuser := cmd.ProcessState.SysUsage().(*syscall.Rusage).Utime cpusys := cmd.ProcessState.SysUsage().(*syscall.Rusage).Stime // cpupercent := float64((int64(cpu.Usec) / 1000)) / float64((int64(sampletime) * 1000)) * 100 log.Printf("Memory: %vkB CPU: %v ms (user) %v ms (sys)", mem/1000, cpuuser.Usec/1000, cpusys.Usec/1000) done <- true }() for { select { case <-time.After(time.Duration(sampletime) * time.Second): log.Printf("Sampling completed, stopping process %v\n", cmdstr) err := cmd.Process.Signal(os.Interrupt) if err != nil { log.Fatalf("Can't stop process: %v\n", err) } case <-done: return } } }
package peach import ( "fmt" ) var ( drivers = make(map[string]Driver) ) //RegistDriver regist driver func RegistDriver(name string, driver Driver) { if nil == driver { panic("driver is nil") } drivers[name] = driver } //GetDriver return Driver by DriverName func GetDriver(name string) (Driver, error) { driver, ok := drivers[name] if !ok { return nil, fmt.Errorf("paladin: unknown driver %q (forgotten register?)", name) } return driver, nil }
package main import ( "fmt" _ "github.com/go-sql-driver/mysql" "github.com/gofiber/fiber" "github.com/jinzhu/gorm" "os" ) import "github.com/superDeano/media-directory/media" import "github.com/superDeano/media-directory/dao" func main() { app := fiber.New() setUpAppRoutes(app) setUpDatabase() defer closeDbConnection() err := app.Listen(os.Getenv("SERVER_PORT")) if err != nil { panic(err.Error()) } } func setUpAppRoutes(app *fiber.App) { app.Get("mediaDirectory/getMedias/:accId", media.GetMedias) app.Get("mediaDirectory/health", media.GetAppHealth) app.Get("mediaDirectory/insertMedia/:accId/:name", media.InsertMedia) app.Get("mediaDirectory/nameExists/:name", media.NameExists) app.Get("mediaDirectory/deleteMedia/:name", media.DeleteMedia) app.Get("mediaDirectory/deleteMedias/:accId", media.DeleteMedias) } func setUpDatabase() { var err error var connectionString = os.Getenv("MYSQLDB") dao.Db, err = gorm.Open("mysql", connectionString) if err != nil { panic(err.Error()) } fmt.Println("Successfully connected to Database") dao.Db.AutoMigrate(&media.Media{}) } func closeDbConnection() { err := dao.Db.Close() if err != nil { panic("Could not close db connection properly") } fmt.Println("Successfully close db connection") }
package main import "fmt" func main() { var price = map[string]int{"chicken_nugget": 2000, "sate": 3000} fmt.Println("Sate ayam ", price["sate"]) }
package events import ( "encoding/json" "fmt" ) var validProjectEventActions = map[string]string{ ProjectAdded: ProjectAdded, VersionAdded: VersionAdded, VulnerabilityAdded: VulnerabilityAdded, } // ProjectEventAction represents possible actions related to a project event type ProjectEventAction string // UnmarshalJSON is a custom unmarshaller for enforcing a project event action is // a valid value and returns an error if the value is invalid func (a *ProjectEventAction) UnmarshalJSON(b []byte) error { var aStr string err := json.Unmarshal(b, &aStr) if err != nil { return err } _, ok := validProjectEventActions[aStr] if !ok { return fmt.Errorf("invalid project event action") } *a = ProjectEventAction(validProjectEventActions[aStr]) return nil } // ProjectEvent represents a project within an Event within Ion Channel type ProjectEvent struct { Action ProjectEventAction `json:"action"` Project string `json:"project"` Org string `json:"org"` Versions []string `json:"versions"` URL string `json:"url"` }
package runner // This file contains the implementation of functions related to AWS. // // Especially functions related to the credentials file handling import ( "bufio" "fmt" "os" "path/filepath" "strings" "github.com/aws/aws-sdk-go/aws/credentials" "github.com/go-stack/stack" "github.com/karlmutch/errors" ) type AWSCred struct { Project string Region string Creds *credentials.Credentials } func AWSExtractCreds(filenames []string) (cred *AWSCred, err errors.Error) { cred = &AWSCred{ Project: fmt.Sprintf("aws_%s", filepath.Base(filepath.Dir(filenames[0]))), } credsDone := false // AWS Does not read the region automatically from the config so lets read it here for _, aFile := range filenames { wasConfig := func() bool { f, err := os.Open(aFile) if err != nil { return false } if len(cred.Region) == 0 { scan := bufio.NewScanner(f) for scan.Scan() { line := scan.Text() if strings.HasPrefix(strings.ToLower(line), "region=") { tokens := strings.SplitN(line, "=", 2) cred.Region = tokens[1] return true } } } f.Close() return false }() if !credsDone && !wasConfig { cred.Creds = credentials.NewSharedCredentials(aFile, "default") credsDone = true } } if len(cred.Region) == 0 { return nil, errors.New("none of the supplied files defined a region").With("stack", stack.Trace().TrimRuntime()).With("files", filenames) } if !credsDone { return nil, errors.New("credentials never loaded").With("stack", stack.Trace().TrimRuntime()).With("files", filenames) } return cred, nil }
package main //func main() { // res := time.Now() //fmt.Println(res) //fmt.Println(res.Year()) //fmt.Println(int(res.Month())) //fmt.Println(int(res.Weekday())) //fmt.Println(res.Hour()) //fmt.Println(res.Minute()) //fmt.Println(res.Second()) //格式化日志或者时间 //fmt.Printf("%02d/%02d/%02d %02d:%02d:%02d\n",res.Year(),res.Month(), res.Day(),res.Hour(),res.Minute(),res.Second()) //date := fmt.Sprintf("%02d/%02d/%02d %02d:%02d:%02d",res.Year(),res.Month(), res.Day(),res.Hour(),res.Minute(),res.Second()) //fmt.Println(date) //const ( // Nanosecond Duration = 1 // Microsecond = 1000 * Nanosecond // Millisecond = 1000 * Microsecond // Second = 1000 * Millisecond // Minute = 60 * Second // Hour = 60 * Minute //) //fmt.Println(res.Unix(),res.UnixNano()) //} //func test(){ // str := "" // for i := 0;i<100000;i++{ // str += "hello" + strconv.Itoa(i) // } //} //func main() { // start := time.Now().Unix() // test() // end := time.Now().Unix() // fmt.Println(end-start) //}
package oauth2 import "crypto/rsa" // Grant type interface. type GrantTypeInterface interface { // Return the grant identifier that can be used in matching up requests. GetIdentifier() GrantType // TODO Respond to an incoming request. RespondToAccessTokenRequest(request *RequestWapper, responseType ResponseTypeInterface) error /** * TODO AuthorizationRequest * If the grant can respond to an authorization request this method should be called to validate the parameters of * the request. * * If the validation is successful an AuthorizationRequest object will be returned. This object can be safely * serialized in a user's session, and can be used during user authentication and authorization. */ ValidateAuthorizationRequest(request *RequestWapper) (*AuthorizationRequest, error) /** * Once a user has authenticated and authorized the client the grant can complete the authorization request. * The AuthorizationRequest object's $userId property must be set to the authenticated user and the * authorizationApproved property must reflect their desire to authorize or deny the client. * */ CompleteAuthorizationRequest(authorizationRequest *AuthorizationRequest) (*RedirectTypeResponse, error) // The grant type should return true if it is able to response to an token request CanRespondToAccessTokenRequest(request *RequestWapper) error // The grant type should return true if it is able to response to an authorization request CanRespondToAuthorizationRequest(request *RequestWapper) error // Set the client repository. SetClientRepository(clientRepository ClientRepositoryInterface) // Set the access token repository. SetAccessTokenRepository(accessTokenRepository AccessTokenRepositoryInterface) // Set the scope repository. SetScopeRepository(scopeRepository ScopeRepositoryInterface) // Set the path to the private key SetPrivateKey(privateKey *rsa.PrivateKey) // Set the encryption key SetEncryptionKey(key []byte) // Get the encryption key GetEncryptionKey() []byte // Get the path to the private key GetPrivateKey() *rsa.PrivateKey }
package domain // Neighbor is the format that represents a neighbor in FAISS type Neighbor struct { ID uint64 `json:"id"` Score float32 `json:"score"` } // Neighbors represents a list of Neighbor type Neighbors []Neighbor
//+build ignore package main import ( "flag" "fmt" "log" "math" "math/big" "os" "text/template" "github.com/pkg/errors" ) func main() { var out string flag.StringVar(&out, "o", "extra_test.go", "test cases output path") flag.Parse() if err := dumpTest(out); err != nil { log.Fatalf("%+v", err) } } func dumpTest(path string) error { f, err := os.Create(path) if err != nil { return errors.WithStack(err) } defer f.Close() t, err := template.ParseFiles("extra_test.tmpl") if err != nil { return errors.WithStack(err) } data := map[string][]string{ "normalized": getNormalized(), "denormalized": getDenormalized(), } if err := t.Execute(f, data); err != nil { return errors.WithStack(err) } return nil } // exponent bias. const bias = 15 func getNormalized() []string { var ns []string // normalized // // exponent bits: 0b00001 - 0b11110 // // (-1)^signbit * 2^(exp-15) * 1.mant_2 const lead = 1 for signbit := 0; signbit <= 1; signbit++ { for exp := 1; exp <= 0x1E; exp++ { // mantissa bits: 0b0000000000 - 0b1111111111 for mant := 0; mant <= 0x3FF; mant++ { s := fmt.Sprintf("%s0b%d.%010bp0", "+", lead, mant) m, _, err := big.ParseFloat(s, 0, 53, big.ToNearestEven) if err != nil { panic(err) } mantissa, acc := m.Float64() if acc != big.Exact { panic("not exact") } want := math.Pow(-1, float64(signbit)) * math.Pow(2, float64(exp)-bias) * mantissa bits := uint16(signbit) << 15 bits |= uint16(exp) << 10 bits |= uint16(mant) n := fmt.Sprintf("{bits: 0x%04X, want: %v}, // %s", bits, want, s) ns = append(ns, n) } } } return ns } func getDenormalized() []string { var ds []string // denormalized // // exponent bits: 0b00000 // // (-1)^signbit * 2^(-14) * 0.mant_2 const lead = 0 for signbit := 0; signbit <= 1; signbit++ { // mantissa bits: 0b0000000000 - 0b1111111111 const exp = 0 for mant := 0; mant <= 0x3FF; mant++ { s := fmt.Sprintf("%s0b%d.%010bp0", "+", lead, mant) m, _, err := big.ParseFloat(s, 0, 53, big.ToNearestEven) if err != nil { panic(err) } mantissa, acc := m.Float64() if acc != big.Exact { panic("not exact") } want := math.Pow(-1, float64(signbit)) * math.Pow(2, exp-bias+1) * mantissa bits := uint16(signbit) << 15 bits |= uint16(exp) << 10 bits |= uint16(mant) if bits == 0x8000 { // -zero d := fmt.Sprintf("{bits: 0x%04X, want: math.Copysign(0, -1)}, // %s", bits, s) ds = append(ds, d) } else { d := fmt.Sprintf("{bits: 0x%04X, want: %v}, // %s", bits, want, s) ds = append(ds, d) } } } return ds }
package cloudflare import ( "context" "encoding/json" "fmt" "net/http" "time" ) // AccessOrganization represents an Access organization. type AccessOrganization struct { CreatedAt *time.Time `json:"created_at"` UpdatedAt *time.Time `json:"updated_at"` Name string `json:"name"` AuthDomain string `json:"auth_domain"` LoginDesign AccessOrganizationLoginDesign `json:"login_design"` IsUIReadOnly *bool `json:"is_ui_read_only,omitempty"` UIReadOnlyToggleReason string `json:"ui_read_only_toggle_reason,omitempty"` UserSeatExpirationInactiveTime string `json:"user_seat_expiration_inactive_time,omitempty"` AutoRedirectToIdentity *bool `json:"auto_redirect_to_identity,omitempty"` } // AccessOrganizationLoginDesign represents the login design options. type AccessOrganizationLoginDesign struct { BackgroundColor string `json:"background_color"` LogoPath string `json:"logo_path"` TextColor string `json:"text_color"` HeaderText string `json:"header_text"` FooterText string `json:"footer_text"` } // AccessOrganizationListResponse represents the response from the list // access organization endpoint. type AccessOrganizationListResponse struct { Result AccessOrganization `json:"result"` Response ResultInfo `json:"result_info"` } // AccessOrganizationDetailResponse is the API response, containing a // single access organization. type AccessOrganizationDetailResponse struct { Success bool `json:"success"` Errors []string `json:"errors"` Messages []string `json:"messages"` Result AccessOrganization `json:"result"` } type GetAccessOrganizationParams struct{} type CreateAccessOrganizationParams struct { Name string `json:"name"` AuthDomain string `json:"auth_domain"` LoginDesign AccessOrganizationLoginDesign `json:"login_design"` IsUIReadOnly *bool `json:"is_ui_read_only,omitempty"` UIReadOnlyToggleReason string `json:"ui_read_only_toggle_reason,omitempty"` UserSeatExpirationInactiveTime string `json:"user_seat_expiration_inactive_time,omitempty"` AutoRedirectToIdentity *bool `json:"auto_redirect_to_identity,omitempty"` } type UpdateAccessOrganizationParams struct { Name string `json:"name"` AuthDomain string `json:"auth_domain"` LoginDesign AccessOrganizationLoginDesign `json:"login_design"` IsUIReadOnly *bool `json:"is_ui_read_only,omitempty"` UIReadOnlyToggleReason string `json:"ui_read_only_toggle_reason,omitempty"` UserSeatExpirationInactiveTime string `json:"user_seat_expiration_inactive_time,omitempty"` AutoRedirectToIdentity *bool `json:"auto_redirect_to_identity,omitempty"` } func (api *API) GetAccessOrganization(ctx context.Context, rc *ResourceContainer, params GetAccessOrganizationParams) (AccessOrganization, ResultInfo, error) { uri := fmt.Sprintf("/%s/%s/access/organizations", rc.Level, rc.Identifier) res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) if err != nil { return AccessOrganization{}, ResultInfo{}, err } var accessOrganizationListResponse AccessOrganizationListResponse err = json.Unmarshal(res, &accessOrganizationListResponse) if err != nil { return AccessOrganization{}, ResultInfo{}, fmt.Errorf("%s: %w", errUnmarshalError, err) } return accessOrganizationListResponse.Result, accessOrganizationListResponse.ResultInfo, nil } func (api *API) CreateAccessOrganization(ctx context.Context, rc *ResourceContainer, params CreateAccessOrganizationParams) (AccessOrganization, error) { uri := fmt.Sprintf("/%s/%s/access/organizations", rc.Level, rc.Identifier) res, err := api.makeRequestContext(ctx, http.MethodPost, uri, params) if err != nil { return AccessOrganization{}, err } var accessOrganizationDetailResponse AccessOrganizationDetailResponse err = json.Unmarshal(res, &accessOrganizationDetailResponse) if err != nil { return AccessOrganization{}, fmt.Errorf("%s: %w", errUnmarshalError, err) } return accessOrganizationDetailResponse.Result, nil } // UpdateAccessOrganization updates the Access organisation details. // // Account API reference: https://api.cloudflare.com/#access-organizations-update-access-organization // Zone API reference: https://api.cloudflare.com/#zone-level-access-organizations-update-access-organization func (api *API) UpdateAccessOrganization(ctx context.Context, rc *ResourceContainer, params UpdateAccessOrganizationParams) (AccessOrganization, error) { uri := fmt.Sprintf("/%s/%s/access/organizations", rc.Level, rc.Identifier) res, err := api.makeRequestContext(ctx, http.MethodPut, uri, params) if err != nil { return AccessOrganization{}, err } var accessOrganizationDetailResponse AccessOrganizationDetailResponse err = json.Unmarshal(res, &accessOrganizationDetailResponse) if err != nil { return AccessOrganization{}, fmt.Errorf("%s: %w", errUnmarshalError, err) } return accessOrganizationDetailResponse.Result, nil }
package main import ( "fmt" "os" ) func main() { fmt.Printf("Starting program\n") var files []*os.File var fileNames []string for { n := len(fileNames) name := fmt.Sprintf("%d.test.txt", n) os.Remove(name) f, err := os.Create(name) if err != nil { fmt.Printf("opening file %s failed with %s\n", name, err) break } fileNames = append(fileNames, name) files = append(files, f) } fmt.Printf("Limit on number of opened files: %d\n", len(fileNames)) for i := range fileNames { files[i].Close() os.Remove(fileNames[i]) } }
/* Challenge Given a positive integer n, count the number of n×n binary matrices (i.e. whose entries are 0 or 1) with exactly two 1's in each rows and two 1's in each column. Here are a few examples of valid matrices for n=4: 1100 1100 1100 1100 0011 0110 0011 1100 0011 0011 0011 1001 And here are a few invalid matrices: 1100 0011 0111 <-- three 1's in this row 1100 ^ `--- three 1's in this column 1111 <-- four 1's in this row 0011 1100 0000 <-- zero 1's in this row This sequence is catalogued on OEIS as A001499. Here are a few non-bruteforce ways to compute it (an denotes the number of valid n×n binary matrices). The recursive formula a[n] = n for 0 <= n < 2 a[n] = (n + 1) * n * (a[n-1] + (n*a[n-2])/2) The explicit formula a(n) = 4^(-n) * n!^2 * Sum_{i=0..n} (-2)^i * (2*n - 2*i)! / (i!*(n-i)!^2) You may find other ways to compute this sequence on the OEIS page linked above. To be clear, bruteforcing is a perfectly valid way of solving this challenge. Rules As usual in sequence challenges, your task is to write a program/function which does one of the following (consistently across different inputs). Take a positive integer n as input and return an as output. Because of the combinatorial interpretation of this sequence, it has to be 1-indexed (i.e. you are not allowed to take n and return an+1). If you choose this option, you are not required to handle the input n=0. Take a positive integer n as input and return the list [a1,a2,…,an] as output. Optionally, you may instead choose to return [a0,a1,…,an−1] or [a0,a1,…,an], where a0=1 (consistent with the combinatorial interpretation). The choice has to be consistent across different inputs. Take no input and return the infinite list/generator [a1,a2,a3,…]. Optionally, you may instead choose to return [a0,a1,a2,…], where a0=1. Your program/function must theoretically work for arbitrarily large inputs, assuming infinite time, memory and integer/floating point precision. In practice, it's ok if if fails because of integer overflow and/or floating point errors. Scoring This is code-golf, so the shortest code in bytes wins. Testcases Input Output 1 0 2 1 3 6 4 90 5 2040 6 67950 7 3110940 8 187530840 9 14398171200 10 1371785398200 11 158815387962000 12 21959547410077200 13 3574340599104475200 14 676508133623135814000 15 147320988741542099484000 */ package main import "math/big" func main() { tab := []string{ "0", "1", "6", "90", "2040", "67950", "3110940", "187530840", "14398171200", "1371785398200", "158815387962000", "21959547410077200", "3574340599104475200", "676508133623135814000", "147320988741542099484000", "36574751938491748341360000", "10268902998771351157327104000", } for i := range tab { v := count(int64(i)) assert(v.String() == tab[i]) } } func assert(x bool) { if !x { panic("assertion failed") } } // https://oeis.org/A001499 func count(n int64) *big.Int { r := recurse(n) return r.Num() } func recurse(n int64) *big.Rat { if n < 1 { return big.NewRat(0, 1) } if n < 2 { return big.NewRat(n, 1) } x := big.NewRat(n+1, 1) y := big.NewRat(n, 1) z := recurse(n - 1) w := recurse(n - 2) w.Mul(w, big.NewRat(n, 1)) w.Quo(w, big.NewRat(2, 1)) z.Add(z, w) r := x r.Mul(r, y) r.Mul(r, z) return r }
/* * Copyright © 2018-2022 Software AG, Darmstadt, Germany and/or its licensors * * SPDX-License-Identifier: Apache-2.0 * * 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 adatypes import ( "bytes" "encoding/binary" "testing" "github.com/stretchr/testify/assert" ) func TestStringNil(t *testing.T) { adaValue := newStringValue(nil) assert.Nil(t, adaValue) } func TestStringValue(t *testing.T) { err := initLogWithFile("string_value.log") if !assert.NoError(t, err) { return } typ := NewType(FieldTypeString, "XX") typ.length = 0 adaValue := newStringValue(typ) assert.NotNil(t, adaValue) v := []byte{} assert.Equal(t, v, adaValue.Value()) assert.Equal(t, "", adaValue.String()) adaValue.SetValue("ABC") v = []byte{0x41, 0x42, 0x43} assert.Equal(t, v, adaValue.Value()) assert.Equal(t, "ABC", adaValue.String()) } func TestStringTruncate(t *testing.T) { err := initLogWithFile("string_value.log") if !assert.NoError(t, err) { return } typ := NewType(FieldTypeString, "XX") typ.length = 2 adaValue := newStringValue(typ) assert.NotNil(t, adaValue) v := []byte{0x20, 0x20} assert.Equal(t, v, adaValue.Value()) assert.Equal(t, " ", adaValue.String()) adaValue.SetValue("AB") v = []byte{0x41, 0x42} assert.Equal(t, v, adaValue.Value()) assert.Equal(t, "AB", adaValue.String()) err = adaValue.SetValue("ABCD") if !assert.Error(t, err) { return } err = adaValue.SetValue("AB") if !assert.NoError(t, err) { return } assert.Equal(t, v, adaValue.Value()) assert.Equal(t, "AB", adaValue.String()) v = []byte{0x41, 0x42, 0x43} err = adaValue.SetValue(v) if !assert.NoError(t, err) { return } v = []byte{0x41, 0x42} assert.Equal(t, v, adaValue.Value()) assert.Equal(t, "AB", adaValue.String()) } func TestStringSpaces(t *testing.T) { err := initLogWithFile("string_value.log") if !assert.NoError(t, err) { return } typ := NewType(FieldTypeString, "XX") typ.length = 10 adaValue := newStringValue(typ) assert.NotNil(t, adaValue) v := []byte{0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20} assert.Equal(t, v, adaValue.Value()) assert.Equal(t, " ", adaValue.String()) assert.Equal(t, v, adaValue.Bytes()) assert.NoError(t, adaValue.SetValue("ABC")) v = []byte{0x41, 0x42, 0x43, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20} assert.Equal(t, v, adaValue.Value()) assert.Equal(t, "ABC ", adaValue.String()) assert.NoError(t, adaValue.SetValue("äöüß")) v = []byte{0xc3, 0xa4, 0xc3, 0xb6, 0xc3, 0xbc, 0xc3, 0x9f, 0x20, 0x20} assert.Equal(t, v, adaValue.Value()) assert.Equal(t, "äöüß ", adaValue.String()) assert.Equal(t, v, adaValue.Bytes()) assert.Equal(t, byte(0xc3), adaValue.ByteValue()) v = []byte{0x41, 0x42, 0x43} assert.NoError(t, adaValue.SetValue(v)) v = []byte{0x41, 0x42, 0x43, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20} assert.Equal(t, v, adaValue.Value()) assert.Equal(t, "ABC ", adaValue.String()) adaValue.SetStringValue("ANCDX") v = []byte{0x41, 0x4e, 0x43, 0x44, 0x58, 0x20, 0x20, 0x20, 0x20, 0x20} assert.Equal(t, v, adaValue.Value()) assert.Equal(t, "ANCDX ", adaValue.String()) } func TestStringInvalid(t *testing.T) { err := initLogWithFile("string_value.log") if !assert.NoError(t, err) { return } typ := NewType(FieldTypeString, "XX") typ.length = 10 adaValue := newStringValue(typ) i32, err := adaValue.Int32() assert.Equal(t, int32(0), i32) assert.Error(t, err) ui32, uierr := adaValue.UInt32() assert.Equal(t, uint32(0), ui32) assert.Error(t, uierr) i64, i64err := adaValue.Int64() assert.Equal(t, int64(0), i64) assert.Error(t, i64err) ui64, ui64err := adaValue.UInt64() assert.Equal(t, uint64(0), ui64) assert.Error(t, ui64err) fl, flerr := adaValue.Float() assert.Equal(t, 0.0, fl) assert.Error(t, flerr) } func TestStringFormatBuffer(t *testing.T) { err := initLogWithFile("string_value.log") if !assert.NoError(t, err) { return } typ := NewType(FieldTypeString, "XX") typ.length = 10 adaValue := newStringValue(typ) assert.NotNil(t, adaValue) option := &BufferOption{} var buffer bytes.Buffer len := adaValue.FormatBuffer(&buffer, option) assert.Equal(t, "XX,10,A", buffer.String()) assert.Equal(t, uint32(10), len) } func TestStringFormatBufferVariable(t *testing.T) { err := initLogWithFile("string_value.log") if !assert.NoError(t, err) { return } typ := NewType(FieldTypeString, "XX") typ.length = 0 adaValue := newStringValue(typ) assert.NotNil(t, adaValue) option := &BufferOption{} var buffer bytes.Buffer len := adaValue.FormatBuffer(&buffer, option) assert.Equal(t, "XX,0,A", buffer.String()) assert.Equal(t, uint32(253), len) } func TestStringLBFormatBufferVariable(t *testing.T) { err := initLogWithFile("string_value.log") if !assert.NoError(t, err) { return } typ := NewType(FieldTypeLBString, "XX") typ.length = 0 adaValue := newStringValue(typ) assert.NotNil(t, adaValue) option := &BufferOption{} var buffer bytes.Buffer len := adaValue.FormatBuffer(&buffer, option) assert.Equal(t, "XXL,4,XX(1,4096)", buffer.String()) assert.Equal(t, uint32(4100), len) } func TestStringStoreBuffer(t *testing.T) { err := initLogWithFile("string_value.log") if !assert.NoError(t, err) { return } typ := NewType(FieldTypeString, "XX") typ.length = 10 adaValue := newStringValue(typ) assert.NotNil(t, adaValue) adaValue.SetValue("äöüß") helper := &BufferHelper{} option := &BufferOption{} err = adaValue.StoreBuffer(helper, option) if !assert.NoError(t, err) { return } v := []byte{0xc3, 0xa4, 0xc3, 0xb6, 0xc3, 0xbc, 0xc3, 0x9f, 0x20, 0x20} assert.Equal(t, v, helper.Buffer()) adaValue.SetValue("ABC") helper = &BufferHelper{} err = adaValue.StoreBuffer(helper, option) if !assert.NoError(t, err) { return } v = []byte{0x41, 0x42, 0x43, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20} assert.Equal(t, v, helper.Buffer()) } func TestStringStoreBufferVariable(t *testing.T) { err := initLogWithFile("string_value.log") if !assert.NoError(t, err) { return } typ := NewType(FieldTypeString, "XX") typ.length = 0 adaValue := newStringValue(typ) assert.NotNil(t, adaValue) adaValue.SetValue("äöüß") helper := &BufferHelper{} option := &BufferOption{} err = adaValue.StoreBuffer(helper, option) if !assert.NoError(t, err) { return } v := []byte{0xc3, 0xa4, 0xc3, 0xb6, 0xc3, 0xbc, 0xc3, 0x9f} assert.Equal(t, v, helper.Buffer()) adaValue.SetValue("ABC") helper = &BufferHelper{} err = adaValue.StoreBuffer(helper, option) if !assert.NoError(t, err) { return } v = []byte{0x41, 0x42, 0x43} assert.Equal(t, v, helper.Buffer()) } func TestStringParseBufferVariable(t *testing.T) { err := initLogWithFile("string_value.log") if !assert.NoError(t, err) { return } typ := NewType(FieldTypeString, "XX") typ.length = 0 adaValue := newStringValue(typ) assert.NotNil(t, adaValue) option := &BufferOption{} helper := &BufferHelper{order: binary.LittleEndian, buffer: []byte{0x9, 0xc3, 0xa4, 0xc3, 0xb6, 0xc3, 0xbc, 0xc3, 0x9f}} var res TraverseResult res, err = adaValue.parseBuffer(helper, option) if !assert.NoError(t, err) { return } assert.Equal(t, TraverseResult(0), res) v := []byte{0xc3, 0xa4, 0xc3, 0xb6, 0xc3, 0xbc, 0xc3, 0x9f} assert.Equal(t, v, adaValue.Value()) helper = &BufferHelper{order: binary.LittleEndian, buffer: []byte{0x4, 0x41, 0x42, 0x43}} res, err = adaValue.parseBuffer(helper, option) if !assert.NoError(t, err) { return } assert.Equal(t, TraverseResult(0), res) v = []byte{0x41, 0x42, 0x43} assert.Equal(t, v, adaValue.Value()) } func TestStringLBParseBufferVariable(t *testing.T) { err := initLogWithFile("string_value.log") if !assert.NoError(t, err) { return } typ := NewType(FieldTypeLBString, "LB") typ.length = 0 adaValue := newStringValue(typ) assert.NotNil(t, adaValue) option := &BufferOption{} var buffer bytes.Buffer checkInfo := []byte{0xc3, 0xa4, 0xc3, 0xb6, 0xc3, 0xbc, 0xc3, 0x9f, 0x0, 0x0, 0x0, 0x0} buffer.Write([]byte{0xc, 0x0, 0x0, 0x0}) buffer.Write(checkInfo) gs := 4100 - buffer.Len() buffer.Write(make([]byte, gs)) assert.Equal(t, 4100, len(buffer.Bytes())) // helper := &BufferHelper{order: binary.LittleEndian, buffer: []byte{0xc, 0x0, 0x0, 0x0, 0xc3, 0xa4, 0xc3, 0xb6, 0xc3, 0xbc, 0xc3, 0x9f}} helper := &BufferHelper{order: binary.LittleEndian, buffer: buffer.Bytes()} var res TraverseResult res, err = adaValue.parseBuffer(helper, option) if !assert.NoError(t, err) { return } assert.Equal(t, TraverseResult(0), res) assert.Equal(t, checkInfo, adaValue.Value()) buffer.Reset() v := []byte{0x41, 0x42, 0x43, 0x0, 0x0, 0x0, 0x0} buffer.Write([]byte{0x7, 0x0, 0x0, 0x0}) buffer.Write(v) gs = 4100 - buffer.Len() buffer.Write(make([]byte, gs)) assert.Equal(t, 4100, len(buffer.Bytes())) helper = &BufferHelper{order: binary.LittleEndian, buffer: buffer.Bytes()} res, err = adaValue.parseBuffer(helper, option) if !assert.NoError(t, err) { return } assert.Equal(t, TraverseResult(0), res) assert.Equal(t, v, adaValue.Value()) } func TestStringConverter(t *testing.T) { err := initLogWithFile("string_value.log") if !assert.NoError(t, err) { return } typ := NewType(FieldTypeString, "XX") typ.SetCharset("ISO-8859-15") typ.length = 13 adaValue := newStringValue(typ) assert.Equal(t, " ", adaValue.String()) err = adaValue.SetValue([]byte{97, 98, 99, 36, 164, 252, 228, 246, 40, 41, 33, 43, 35}) assert.NoError(t, err) assert.Equal(t, "abc$€üäö()!+#", adaValue.String()) typ.SetCharset("windows-1251") err = adaValue.SetValue([]byte{207, 238, 234, 243, 239, 224, 242, 229, 235, 232}) assert.NoError(t, err) assert.Equal(t, "Покупатели ", adaValue.String()) }
package s3seek_test import ( "bufio" "testing" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/session" "github.com/aws/aws-sdk-go/service/s3" "github.com/brentp/go-athenaeum/s3seek" ) func TestRead(t *testing.T) { sess := session.Must(session.NewSession()) svc := s3.New(sess, aws.NewConfig().WithRegion("us-east-1")) s, err := s3seek.New(svc, "s3://1000genomes/20131219.populations.tsv", nil) if err != nil { t.Fatal(err) } r := bufio.NewReader(s) l1, err := r.ReadString('\n') if err != nil { t.Fatal(err) } l2, err := r.ReadString('\n') if err != nil { t.Fatal(err) } _, err = r.ReadString('\n') if err != nil { t.Fatal(err) } _, err = s.Seek(int64(len(l1)), 0) if err != nil { t.Fatal(err) } r = bufio.NewReader(s) l22, err := r.ReadString('\n') if err != nil { t.Fatal(err) } if l2 != l22 { t.Fatal("error seeking. expected line 2 from test file") } } /* func TestBam(t *testing.T) { sess := session.Must(session.NewSession()) svc := s3.New(sess, aws.NewConfig().WithRegion("us-east-1")) s, err := s3seek.New(svc, "s3://1000genomes/phase3/data/NA12878/high_coverage_alignment/NA12878.mapped.ILLUMINA.bwa.CEU.high_coverage_pcr_free.20130906.bam.bai", nil) if err != nil { t.Fatal(err) } idx, err := bam.ReadIndex(s) if err != nil { t.Fatal(err) } s.Close() s, err = s3seek.New(svc, "s3://1000genomes/phase3/data/NA12878/high_coverage_alignment/NA12878.mapped.ILLUMINA.bwa.CEU.high_coverage_pcr_free.20130906.bam", nil) if err != nil { t.Fatal(err) } defer s.Close() b, err := bam.NewReader(s, 1) if err != nil { t.Fatal(err) } defer b.Close() ref := b.Header().Refs()[4] chunks, err := idx.Chunks(ref, 45000000, 45000100) if err != nil { t.Fatal(err) } bi, err := bam.NewIterator(b, chunks) for bi.Next() { rec := bi.Record() fmt.Println(rec.Ref.Name(), rec.Start()) } if err = bi.Error(); err != nil { t.Fatal(err) } } */
package store type Type string const ( Type_Devices Type = "devices" Type_Device Type = "device" Type_Resource Type = "resource" ) type Subscription struct { SubscriptionID string Type Type LinkedAccountID string DeviceID string Href string SigningSecret string }
package db import ( "sync" "github.com/go-redis/redis/v8" ) var ( rdb *redis.Client once sync.Once ) func ConnectRedis() { once.Do(func() { rdb = redis.NewClient(&redis.Options{ Addr: "localhost:6379", Password: "", // no password set DB: 0, // use default DB }) }) } func PoolRDB() *redis.Client { return rdb }
package account import ( "errors" ) type Account struct { Username string Balance float64 Transactions []Transaction } func (a *Account) Transfer(to string, amt float64) error { return a.Withdraw(amt) } func (a *Account) Withdraw(amt float64) error { if a.Balance < amt { return errors.New("not enough balance") } a.Balance -= amt a.Transactions = append(a.Transactions, Transaction{WITHDRAW, amt}) return nil } func (a *Account) Deposit(amt float64) { a.Balance += amt a.Transactions = append(a.Transactions, Transaction{DEPOSIT, amt}) } func (a *Account) TransactionsRange(from, to int) []Transaction { return a.Transactions[from : to] }
package main import ( "fmt" "math/big" "os" "strconv" "time" ) var t0, t1 time.Time var fib_number string func fibonacci(n int) []*big.Int { var fib_arr []*big.Int if n == 0 { fib_arr = append(fib_arr, big.NewInt(0)) } else { fib_arr = append(fib_arr, big.NewInt(0), big.NewInt(1)) sum := big.NewInt(0) for i := 0; i < n-1; i++ { sum.Add(fib_arr[i], fib_arr[i+1]) fib_arr = append(fib_arr, sum) sum = big.NewInt(0) } } return (fib_arr) } func main() { if len(os.Args) < 2 { fmt.Print(` Вы можете передать порядковый номер числа Фибоначчи как аргумент при запуске этой программы. При вычислении чисел с порядковыми номерами более 100000 возможны зависания ПК. Введите порядковый номер числа из последовательности Фибоначчи:`) fmt.Scanln(&fib_number) } else { fib_number = (os.Args[1]) } n, err := strconv.Atoi(fib_number) if err != nil { fmt.Println(err) os.Exit(2) } else { t0 = time.Now() fibonacci_array := fibonacci(n) t1 = time.Now() fmt.Printf("%v-й член последовательности Фибоначчи - это: %v\n", n, fibonacci_array[n]) if n <= 100 { // не печатаем всю последовательность, если она длиннее 100 fmt.Printf("Вся последовательность до %v-го члена:\n", n) fmt.Println(fibonacci_array) } fmt.Printf("Время вычисления составило %v.\n", t1.Sub(t0)) } }
package main import ( "code.google.com/p/go.crypto/bcrypt" "crypto/rand" "fmt" "github.com/johnnylee/ttlib" "log" "os" ) func printUsage() { fmt.Println("") fmt.Printf("Usage: %v <directory> <user_name>\n", os.Args[0]) fmt.Println("") fmt.Println("directory:") fmt.Println(" The directory in which to store the configuration.") fmt.Println("") fmt.Println("user_name:") fmt.Println(" The user's unique username.") fmt.Println("") } func main() { if len(os.Args) != 3 { printUsage() return } baseDir := os.Args[1] user := os.Args[2] // Load server configuration. fmt.Println("Loading server configuration...") serverConfig, err := ttlib.LoadServerConfig(baseDir) if err != nil { log.Fatalln("Error:", err) } // Create and write client configuration. fmt.Println("Creating client configuration file...") cc := new(ttlib.ClientConfig) cc.Host = serverConfig.PublicAddr cc.User = user cc.Pwd = make([]byte, 48) if _, err = rand.Read(cc.Pwd); err != nil { log.Fatalln("Error:", err) } _, cc.CaCert, err = ttlib.LoadKeyAndCert(baseDir) if err != nil { log.Fatalln("Error:", err) } if err = cc.Save(ttlib.ClientConfigFile(baseDir, user)); err != nil { log.Fatalln("Error:", err) } // Create and write the client password file. fmt.Println("Creating password file for client...") pf := new(ttlib.PwdFile) pf.PwdHash, err = bcrypt.GenerateFromPassword(cc.Pwd, bcrypt.DefaultCost) if err != nil { log.Fatalln("Error:", err) } if err = pf.Save(baseDir, user); err != nil { log.Fatalln("Error:", err) } }
package lessorio const ( GroupName = "lessor.io" )
package adventutilities import ( "io/ioutil" "strconv" "strings" "log" ) func Check(e error) { if e != nil { panic(e) } } func CheckResult(testName string, actual int, expected int)(success bool){ if(actual == expected){ log.Println("Test:", testName, "successful, actual",actual,"== expected",expected) return true }else{ log.Println("Test:", testName, "failed, expected", expected, "got",actual) return false } } func ReadStringsFromFile(fileName string) (lines []string, err error) { data, err := ioutil.ReadFile(fileName) Check(err) lines = strings.Split(string(data), "\n") return lines, nil } func ReadNumbersFromFile(fileName string) (nums []int, err error) { data, err := ioutil.ReadFile(fileName) Check(err) lines := strings.Split(string(data), "\n") // Assign cap to avoid resize on every append. nums = make([]int, 0, len(lines)) var val int = 0 for _, s := range lines { val, err = strconv.Atoi(s) if err != nil { return nil, err } nums = append(nums, val) } return nums, nil }
package main import ( "fmt" ) type TreeNode struct { Val int Left *TreeNode Right *TreeNode } func max2(a, b int) int { if a > b { return a } return b } func min2(a, b int) int { if a < b { return a } return b } func bstSum(root *TreeNode, maxBSTSize *int) (bool, int, int, int) { if root.Left == nil && root.Right == nil { *maxBSTSize = max2(*maxBSTSize, 1) return true, 1, root.Val, root.Val } isTreeBST := false treeMin, treeMax := 0, 0 treeSize := 0 if root.Left != nil && root.Right != nil { isLSubTreeBST, lSubTreeSize, lSubTreeMin, lSubTreeMax := bstSum(root.Left, maxBSTSize) isRSubTreeBST, rSubTreeSize, rSubTreeMin, rSubTreeMax := bstSum(root.Right, maxBSTSize) isTreeBST = isLSubTreeBST && isRSubTreeBST && (root.Val > lSubTreeMax) && (root.Val < rSubTreeMin) treeSize = 1 + lSubTreeSize + rSubTreeSize treeMin, treeMax = min2(root.Val, min2(lSubTreeMin, rSubTreeMin)), max2(root.Val, max2(lSubTreeMax, rSubTreeMax)) } else if root.Left == nil { isRSubTreeBST, rSubTreeSize, rSubTreeMin, rSubTreeMax := bstSum(root.Right, maxBSTSize) isTreeBST = isRSubTreeBST && (root.Val < rSubTreeMin) treeSize = 1 + rSubTreeSize treeMin, treeMax = min2(root.Val, rSubTreeMin), max2(root.Val, rSubTreeMax) } else { isLSubTreeBST, lSubTreeSize, lSubTreeMin, lSubTreeMax := bstSum(root.Left, maxBSTSize) isTreeBST = isLSubTreeBST && (root.Val > lSubTreeMax) treeSize = 1 + lSubTreeSize treeMin, treeMax = min2(root.Val, lSubTreeMin), max2(root.Val, lSubTreeMax) } if root.Val == -2 { fmt.Printf("treeMin: %v, treeMax: %v\n", treeMin, treeMax) } if isTreeBST { *maxBSTSize = max2(*maxBSTSize, treeSize) } return isTreeBST, treeSize, treeMin, treeMax } func largestBSTSubtree(root *TreeNode) int { if root == nil { return 0 } maxBSTSum := 0 bstSum(root, &maxBSTSum) return maxBSTSum } func test1() { nodeM1 := TreeNode{Val: -1} nodeM2 := TreeNode{Val: -2} nodeM2.Right = &nodeM1 result := largestBSTSubtree(&nodeM2) fmt.Printf("result: %d\n", result) } func main() { test1() }
package routes import ( "fmt" "io/ioutil" "net/http" "github.com/davelaursen/idealogue-go/Godeps/_workspace/src/github.com/gorilla/mux" "github.com/davelaursen/idealogue-go/services" ) // RegisterIdeaRoutes registers the /ideas endpoints with the router. func RegisterIdeaRoutes(r *mux.Router, enc Encoder, ideaSvc services.IdeaSvc) { u := util{} r.HandleFunc("/api/ideas", func(w http.ResponseWriter, r *http.Request) { if u.checkAccess(w, r) { GetIdeas(w, r, enc, ideaSvc) } }).Methods("GET") r.HandleFunc("/api/ideas/{id}", func(w http.ResponseWriter, r *http.Request) { if u.checkAccess(w, r) { GetIdea(w, enc, ideaSvc, mux.Vars(r)) } }).Methods("GET") r.HandleFunc("/api/ideas/{id}", func(w http.ResponseWriter, r *http.Request) { if u.checkAccess(w, r) { PutIdea(w, r, enc, ideaSvc, mux.Vars(r)) } }).Methods("PUT") r.HandleFunc("/api/ideas", func(w http.ResponseWriter, r *http.Request) { if u.checkAccess(w, r) { PostIdea(w, r, enc, ideaSvc) } }).Methods("POST") r.HandleFunc("/api/ideas/{id}", func(w http.ResponseWriter, r *http.Request) { if u.checkAccess(w, r) { DeleteIdea(w, enc, ideaSvc, mux.Vars(r)) } }).Methods("DELETE") } // GetIdeas returns a list of ideas. func GetIdeas(w http.ResponseWriter, r *http.Request, enc Encoder, svc services.IdeaSvc) { search := r.URL.Query().Get("search") ideas := services.Ideas{} if search != "" { //TODO: implement full text search // i, err := svc.Search(search) i, err := svc.GetAll() if err != nil { panic(err) } ideas = i } else { i, err := svc.GetAll() if err != nil { panic(err) } ideas = i } util{}.writeResponse(w, http.StatusOK, enc.EncodeMulti(ideas.ToInterfaces()...)) } // GetIdea returns the requested idea. func GetIdea(w http.ResponseWriter, enc Encoder, svc services.IdeaSvc, params Params) { id := params["id"] u, err := svc.GetByID(id) if err != nil { panic(err) } if u == nil { util{}.notFound(w, enc, fmt.Sprintf("the idea with id '%s' does not exist", id)) return } util{}.writeResponse(w, http.StatusOK, enc.Encode(*u)) } // PostIdea creates a idea. func PostIdea(w http.ResponseWriter, r *http.Request, enc Encoder, svc services.IdeaSvc) { idea := &services.Idea{} e := loadIdeaFromRequest(w, r, enc, idea) if e != nil { util{}.badRequest(w, enc, "the idea data is invalid") return } err := svc.Insert(idea) if err != nil { switch err.Type { case services.ErrBadData: util{}.badRequest(w, enc, err.Error()) return default: panic(err) } } util{}.writeResponse(w, http.StatusCreated, enc.Encode(idea)) } // PutIdea updates a idea. func PutIdea(w http.ResponseWriter, r *http.Request, enc Encoder, svc services.IdeaSvc, params Params) { id := params["id"] idea, err := svc.GetByID(id) if err != nil { panic(err) } if idea == nil { util{}.notFound(w, enc, fmt.Sprintf("the idea with id %s does not exist", id)) return } e := loadIdeaFromRequest(w, r, enc, idea) if e != nil { util{}.badRequest(w, enc, "the idea data is invalid") return } err = svc.Update(idea) if err != nil { switch err.Type { case services.ErrBadData: util{}.badRequest(w, enc, err.Error()) return default: panic(err) } } util{}.writeResponse(w, http.StatusOK, enc.Encode(idea)) } // DeleteIdea removes a idea. func DeleteIdea(w http.ResponseWriter, enc Encoder, svc services.IdeaSvc, params Params) { id := params["id"] err := svc.Delete(id) if err != nil { switch err.Type { case services.ErrNotFound: util{}.notFound(w, enc, fmt.Sprintf("the idea with id %s does not exist", id)) return default: panic(err) } } util{}.writeResponse(w, http.StatusNoContent, "") } // parse request body into a Idea instance func loadIdeaFromRequest(w http.ResponseWriter, r *http.Request, enc Encoder, idea *services.Idea) *services.ErrorResponse { body, err := ioutil.ReadAll(http.MaxBytesReader(w, r.Body, maxRequestBodySize)) if err != nil { if err.Error() == "http: request body too large" { return services.NewErrorResponse(http.StatusBadRequest, err.Error()) } panic(err) } err = enc.Decode(body, idea) if err != nil { fmt.Printf("%s\n", err) return services.NewErrorResponse(http.StatusBadRequest, fmt.Sprintf("the idea data is not valid")) } return nil }
package template import "encoding/json" const TemplateTypeButton TemplateType = "button" // ButtonTemplate is a template type ButtonTemplate struct { TemplateBase Text string `json:"text,omitempty"` Buttons []Button `json:"buttons,omitempty"` } func (ButtonTemplate) Type() TemplateType { return TemplateTypeButton } func (ButtonTemplate) SupportsButtons() bool { return true } func (b ButtonTemplate) Validate() error { if len(b.Buttons) > ButtonTemplateButtonsLimit { return ErrButtonsLimitExceeded } return nil } func (b *ButtonTemplate) AddButton(bt ...Button) { b.Buttons = append(b.Buttons, bt...) } func (b *ButtonTemplate) Decode(d json.RawMessage) error { t := ButtonTemplate{} err := json.Unmarshal(d, &t) if err == nil { b.Text = t.Text b.Buttons = t.Buttons b.TemplateBase.Type = t.TemplateBase.Type } return err }
package conversion import ( "encoding/json" "strconv" "strings" "time" ) const ( DATE_TIME_FORMAT_STRING string = "2006-01-02 15:04:05" ) /* ToString 获取变量的字符串值 浮点型 3.0将会转换成字符串3, "3" 非数值或字符类型的变量将会被转换成JSON格式字符串 */ func ToString(value interface{}) string { if value == nil { return "" } switch value.(type) { case float64: ft := value.(float64) return strconv.FormatFloat(ft, 'f', -1, 64) case float32: ft := value.(float32) return strconv.FormatFloat(float64(ft), 'f', -1, 64) case int: it := value.(int) return strconv.Itoa(it) case uint: it := value.(uint) return strconv.Itoa(int(it)) case int8: it := value.(int8) return strconv.Itoa(int(it)) case uint8: it := value.(uint8) return strconv.Itoa(int(it)) case int16: it := value.(int16) return strconv.Itoa(int(it)) case uint16: it := value.(uint16) return strconv.Itoa(int(it)) case int32: it := value.(int32) return strconv.Itoa(int(it)) case uint32: it := value.(uint32) return strconv.Itoa(int(it)) case int64: it := value.(int64) return strconv.FormatInt(it, 10) case uint64: it := value.(uint64) return strconv.FormatUint(it, 10) case string: return value.(string) case time.Time: it := value.(time.Time) return it.Format(DATE_TIME_FORMAT_STRING) case []byte: return string(value.([]byte)) default: newValue, _ := json.Marshal(value) return string(newValue) } } //将任意数组转换成 string 以指定字符进行分割 func ArrayToString(array []interface{}, sep string) (result string) { if len(array) <= 0 { return result } for i := 0; i < len(array); i++ { if i == 0 { result += ToString(array[i]) } else { result += sep + ToString(array[i]) } } return } /** 下划线转大驼峰 */ func UnderscoreToBigHump(name string) string { name = strings.Replace(name, "_", " ", -1) name = strings.Title(name) return strings.Replace(name, " ", "", -1) } /** 下划线转小驼峰 */ func UnderscoreToSmallHump(name string) string { if len(name) < 2 { return name } result := UnderscoreToBigHump(name) index := result[:1] return strings.ToLower(index) + result[1:] } /** 驼峰转下划线 */ func HumpToUnderscore(name string) string { newName := "" for index, item := range name { if index > 0 && (item >= 'A' && item <= 'Z') && (index < len(name)) { newName += "_" } newName += name[index : index+1] } return strings.ToLower(newName) }
package testdata import ( "io/ioutil" "path/filepath" "testing" ) // LoadExampleAnalyseRequest reads the example request from exampleAnalyseRequest.json func LoadExampleAnalyseRequest(t *testing.T) []byte { return loadTestdata(t, "exampleAnalyseRequest.json") } // LoadExampleRequest reads the example request from exampleRequest.json func LoadExampleRequest(t *testing.T) []byte { return loadTestdata(t, "exampleRequest.json") } func loadTestdata(t *testing.T, name string) []byte { path := filepath.Join("../testdata", name) // relative path bytes, err := ioutil.ReadFile(path) if err != nil { t.Fatal(err) } return bytes }
//go:build !js // Package checkbox provides a checkbox connected to a query parameter. package checkbox import ( "fmt" "html/template" "net/url" "strconv" "github.com/shurcooL/htmlg" "golang.org/x/net/html" "golang.org/x/net/html/atom" ) // New creates the HTML for a checkbox instance. Its checked value is directly connected // to the presence of queryParameter. // Changing either the presence of queryParameter, or checking/unchecking the checkbox // will result in the other updating to match. func New(defaultValue bool, query url.Values, queryParameter string) template.HTML { inputElement := &html.Node{ Type: html.ElementNode, Data: "input", Attr: []html.Attribute{{Key: atom.Type.String(), Val: "checkbox"}}, } var selectedValue = defaultValue if _, set := query[queryParameter]; set { selectedValue = !selectedValue } if selectedValue { inputElement.Attr = append(inputElement.Attr, html.Attribute{Key: "checked"}) } inputElement.Attr = append(inputElement.Attr, html.Attribute{ Key: "onchange", // HACK: Don't use Sprintf, properly encode (as json at this time). Val: fmt.Sprintf(`CheckboxOnChange(event, this, %v, %q);`, defaultValue, strconv.Quote(queryParameter)), }) return template.HTML(htmlg.Render(inputElement)) }
package main import ( "fmt" "time" ) func main() { var no = 10 switch { case no < 0: fmt.Println(no, " is negative") default: fmt.Println(no, " is positive") } no = -11 switch no % 2 { case 1: fmt.Println(no, " is odd") case 0: fmt.Println(no, " is even") default: fmt.Println(no, " is negative and odd") } var currentTime = time.Now() fmt.Println("\ncurrent time is ", currentTime.Hour()) switch { case currentTime.Hour() > 10 && currentTime.Hour() < 18: fmt.Println("that means you are working") default: fmt.Println("that means you are not working") } }
package main import ( "fmt" "os" ) func main() { word := os.Args[1] greet := "greetings" switch l := len(word); word { case "hi": fmt.Println("Very formal") fallthrough case "hello": fmt.Println("Hi, yourself") case "farewell": case greet: fmt.Println("Salutations!") case "goodbye", "bye": fmt.Println("So long!") default: fmt.Println("I don't know what you said", l, "letters") } switch l := len(word); { case l == 5: fmt.Println("its 5 charaters") default: fmt.Println("I don't know what you said", l, "letters") } }
package diamond import ( "errors" "strings" ) const testVersion = 1 // Given a letter, print a diamond like this: // Diamond for letter 'C': // ··A·· 2 0 2 C - A = 2 // ·B·B· 1 1 1 // C···C 0 3 0 // ·B·B· 1 1 1 // ··A·· 2 0 2 func Gen(char byte) (string, error) { if char < 'A' || char > 'Z' { return "", errors.New("Input should be in [A-Z]") } cnt := int(char - 'A') sideLen := int(cnt)*2 + 1 strs := []string{} for i := 0; i <= cnt; i++ { byteArr := make([]byte, sideLen) for inx, _ := range byteArr { byteArr[inx] = ' ' } alphabet := byte('A' + i) byteArr[cnt-i] = alphabet byteArr[sideLen-1-cnt+i] = alphabet strs = append(strs, string(byteArr)) } for i := cnt - 1; i >= 0; i-- { strs = append(strs, strs[i]) } // it needs a trailing \n to pass, since the test case checks // len(row) >= 2 return strings.Join(strs, "\n") + "\n", nil }
package main import ( "encoding/json" "fmt" "strings" "time" "github.com/lxc/lxd/shared" ) // Loader functions func containerKVMCreate(d *Daemon, args containerArgs) (container, error) { fmt.Println("Creating KVM container...") // Create the container struct c := &containerKVM{ &containerLXC{ daemon: d, id: args.Id, name: args.Name, ephemeral: args.Ephemeral, architecture: args.Architecture, cType: args.Ctype, stateful: args.Stateful, creationDate: args.CreationDate, lastUsedDate: args.LastUsedDate, profiles: args.Profiles, localConfig: args.Config, localDevices: args.Devices, }, } // No need to detect storage here, its a new container. c.storage = d.Storage // Load the config err := c.init() if err != nil { c.Delete() return nil, err } // Look for a rootfs entry rootfs := false for _, name := range c.expandedDevices.DeviceNames() { m := c.expandedDevices[name] if m["type"] == "disk" && m["path"] == "/" { rootfs = true break } } if !rootfs { deviceName := "root" for { if c.expandedDevices[deviceName] == nil { break } deviceName += "_" } c.localDevices[deviceName] = shared.Device{"type": "disk", "path": "/"} updateArgs := containerArgs{ Architecture: c.architecture, Config: c.localConfig, Devices: c.localDevices, Ephemeral: c.ephemeral, Profiles: c.profiles, } err = c.Update(updateArgs, false) if err != nil { c.Delete() return nil, err } } // Validate expanded config err = containerValidConfig(d, c.expandedConfig, false, true) if err != nil { c.Delete() return nil, err } err = containerValidDevices(c.expandedDevices, false, true) if err != nil { c.Delete() return nil, err } // Setup initial idmap config idmap := c.IdmapSet() var jsonIdmap string if idmap != nil { idmapBytes, err := json.Marshal(idmap.Idmap) if err != nil { c.Delete() return nil, err } jsonIdmap = string(idmapBytes) } else { jsonIdmap = "[]" } err = c.ConfigKeySet("volatile.last_state.idmap", jsonIdmap) if err != nil { c.Delete() return nil, err } // Update lease files networkUpdateStatic(d) return c, nil } func containerKVMLoad(d *Daemon, args containerArgs) (container, error) { fmt.Println("Loading KVM container...") // Create the container struct c := &containerKVM{ &containerLXC{ daemon: d, id: args.Id, name: args.Name, ephemeral: args.Ephemeral, architecture: args.Architecture, cType: args.Ctype, creationDate: args.CreationDate, lastUsedDate: args.LastUsedDate, profiles: args.Profiles, localConfig: args.Config, localDevices: args.Devices, stateful: args.Stateful, }, } // Detect the storage backend s, err := storageForFilename(d, shared.VarPath("containers", strings.Split(c.name, "/")[0])) if err != nil { return nil, err } c.storage = s // Load the config err = c.init() if err != nil { return nil, err } return c, nil } // The KVM container driver type containerKVM struct { *containerLXC } func (c *containerKVM) Start(stateful bool) error { fmt.Println("Hello, KVM here!") return c.containerLXC.Start(stateful) } func (c *containerKVM) Stop(stateful bool) error { fmt.Println("Stopping, KVM here!") return c.containerLXC.Stop(stateful) } func (c *containerKVM) Shutdown(timeout time.Duration) error { fmt.Println("Shutdown, KVM here!") return c.containerLXC.Shutdown(timeout) }
package thorf import ( "bytes" "strings" "testing" ) // These tests were borrowed from the excellent exercism.io "forth" exercise: // https://github.com/exercism/go/tree/5446524b6/exercises/forth func runTest(input string) (string, error) { var buf bytes.Buffer m := NewMachine(&buf) err := m.Eval(strings.NewReader(input)) if err != nil { return "", err } return buf.String(), nil } func TestMachine(t *testing.T) { for _, tg := range testGroups { for _, tc := range tg.tests { t.Run(tg.group+"--"+tc.description, func(t *testing.T) { output, err := runTest(tc.input) if err != nil { if !tc.err { t.Fatalf("runTest(%#v) expected %q, got an error: %q", tc.input, tc.expected, err) } return } if tc.err { t.Fatalf("runTest(%#v) expected an error, got %q", tc.input, output) } if output != tc.expected { t.Fatalf("runTest(%#v) expected %q, got %q", tc.input, tc.expected, output) } }) } } } func BenchmarkMachine(b *testing.B) { for i := 0; i < b.N; i++ { for _, tg := range testGroups { for _, tc := range tg.tests { _, err := runTest(tc.input) if !tc.err && err != nil { b.Fatal(err) } } } } } type testGroup struct { group string tests []testCase } type testCase struct { description string input string expected string err bool } var testGroups = []testGroup{ { group: "parsing and numbers", tests: []testCase{ { "numbers just get pushed onto the stack", "1 2 3 4 5 .s", "1 2 3 4 5 ", false, }, }, }, { group: "addition", tests: []testCase{ { "can add two numbers", "1 2 + .s", "3 ", false, }, { "errors if there is nothing on the stack", "+", "", true, }, { "errors if there is only one value on the stack", "1 +", "", true, }, }, }, { group: "subtraction", tests: []testCase{ { "can subtract two numbers", "3 4 - .s", "-1 ", false, }, { "errors if there is nothing on the stack", "-", "", true, }, { "errors if there is only one value on the stack", "1 -", "", true, }, }, }, { group: "multiplication", tests: []testCase{ { "can multiply two numbers", "2 4 * .s", "8 ", false, }, { "errors if there is nothing on the stack", "*", "", true, }, { "errors if there is only one value on the stack", "1 *", "", true, }, }, }, { group: "division", tests: []testCase{ { "can divide two numbers", "12 3 / .s", "4 ", false, }, { "performs integer division", "8 3 / .s", "2 ", false, }, { "errors if dividing by zero", "4 0 /", "", true, }, { "errors if there is nothing on the stack", "/", "", true, }, { "errors if there is only one value on the stack", "1 /", "", true, }, }, }, { group: "combined arithmetic", tests: []testCase{ { "addition and subtraction", "1 2 + 4 - .s", "-1 ", false, }, { "multiplication and division", "2 4 * 3 / .s", "2 ", false, }, }, }, { group: "dup", tests: []testCase{ { "copies a value on the stack", "1 dup .s", "1 1 ", false, }, { "copies the top value on the stack", "1 2 dup .s", "1 2 2 ", false, }, { "errors if there is nothing on the stack", "dup", "", true, }, }, }, { group: "drop", tests: []testCase{ { "removes the top value on the stack if it is the only one", "1 drop .s", "", false, }, { "removes the top value on the stack if it is not the only one", "1 2 drop .s", "1 ", false, }, { "errors if there is nothing on the stack", "drop", "", true, }, }, }, { group: "swap", tests: []testCase{ { "swaps the top two values on the stack if they are the only ones", "1 2 swap .s", "2 1 ", false, }, { "swaps the top two values on the stack if they are not the only ones", "1 2 3 swap .s", "1 3 2 ", false, }, { "errors if there is nothing on the stack", "swap", "", true, }, { "errors if there is only one value on the stack", "1 swap", "", true, }, }, }, { group: "over", tests: []testCase{ { "copies the second element if there are only two", "1 2 over .s", "1 2 1 ", false, }, { "copies the second element if there are more than two", "1 2 3 over .s", "1 2 3 2 ", false, }, { "errors if there is nothing on the stack", "over", "", true, }, { "errors if there is only one value on the stack", "1 over", "", true, }, }, }, { group: "user-defined words", tests: []testCase{ { "can consist of built-in words", ": dup-twice dup dup ; 1 dup-twice .s", "1 1 1 ", false, }, { "execute in the right order", ": countup 1 2 3 ; countup .s", "1 2 3 ", false, }, { "can override other user-defined words", ": foo dup ; : foo dup dup ; 1 foo .s", "1 1 1 ", false, }, { "can override built-in words", ": swap dup ; 1 swap .s", "1 1 ", false, }, { "can override built-in operators", ": + * ; 3 4 + .s", "12 ", false, }, { "can use different words with the same name", ": foo 5 ; : bar foo ; : foo 6 ; bar foo .s", "5 6 ", false, }, { "can define word that uses word with the same name", ": foo 10 ; : foo foo 1 + ; foo .s", "11 ", false, }, { "cannot redefine numbers", ": 1 2 ;", "", true, }, { "errors if executing a non-existent word", "foo", "", true, }, }, }, { group: "case-insensitivity", tests: []testCase{ { "DUP is case-insensitive", "1 DUP Dup dup .s", "1 1 1 1 ", false, }, { "DROP is case-insensitive", "1 2 3 4 DROP Drop drop .s", "1 ", false, }, { "SWAP is case-insensitive", "1 2 SWAP 3 Swap 4 swap .s", "2 3 4 1 ", false, }, { "OVER is case-insensitive", "1 2 OVER Over over .s", "1 2 1 2 1 ", false, }, { "user-defined words are case-insensitive", ": foo dup ; 1 FOO Foo foo .s", "1 1 1 1 ", false, }, { "definitions are case-insensitive", ": SWAP DUP Dup dup ; 1 swap .s", "1 1 1 1 ", false, }, }, }, { group: "output", tests: []testCase{ { ". prints the value as a number", "1 .", "1 ", false, }, { ". prints only the last value as a number", "1 2 3 .", "3 ", false, }, { ". consumes the value", "1 2 3 . .s", "3 1 2 ", false, }, { ".s prints the whole stack", "1 2 3 .s", "1 2 3 ", false, }, { ".s does not consume the stack", "1 .s .", "1 1 ", false, }, { "EMIT prints one ASCII character", "42 EMIT", "*", false, }, { "EMIT consumes the value", "42 EMIT .s", "*", false, }, { ". errors if there is nothing on the stack", ".", "", true, }, { ".s can print an empty stack", ".s", "", false, }, { "EMIT errors if there is nothing on the stack", "EMIT", "", true, }, }, }, }
package main import ( "CCServer.com/cccompress" "CCServer.com/ccconvert" "flag" "fmt" "image" "image/jpeg" "image/png" "log" "os" "time" ) var ( bConvert bool iQuality int sSrc string sDst string bCompress bool bDecompress bool bOverWrite bool iMode int iWorkerNum int sTarget string sExt string sKey string ) func init() { flag.BoolVar(&bConvert, "convert", false, "Convert PNG/JPG/JPEG to JPG with custom image quality default:false") flag.IntVar(&iQuality, "q", 80, "Convert image with given quality [1,100] default:80") flag.StringVar(&sSrc, "src", "", "source images path") flag.StringVar(&sDst, "dst", "", "dest images path") flag.BoolVar(&bCompress, "c", false, "Compress") flag.BoolVar(&bDecompress, "d", false, "Decompress") flag.BoolVar(&bOverWrite, "w", false, "Overwrite origin files,otherwise rename origin files to .bak") flag.IntVar(&iMode, "m", cccompress.Uncompressed, "Compress/Decompress mode") flag.IntVar(&iWorkerNum, "n", 10, "Number of workers when compress/decompress folders") flag.StringVar(&sTarget, "t", "", "Target path") flag.StringVar(&sExt, "e", "", "Ext") flag.StringVar(&sKey, "k", "", "Obfuscation key") flag.Usage = useAge } // useAge . func useAge() { cmdStr := "\n*****************************************\n" cmdStr += "Usage:\n" cmdStr += "*****************************************\n" log.Printf(cmdStr) flag.PrintDefaults() } func main() { flag.Parse() // check test mode params := os.Args if len(params) == 1 { useAge() return } var total int64 var fi os.FileInfo var err error s := time.Now() // Convert PNG/JPG/JPEG to JPG with custom image quality if bConvert { if iQuality < 1 || iQuality > 100 { useAge() return } if len(sSrc) == 0 || len(sDst) == 0 { useAge() return } ext := "" err = ccconvert.Convert(sSrc, sDst, nil, func(file *os.File, _ext string) (image.Image, error) { ext = _ext switch ext { case "image/png": return png.Decode(file) case "image/jpeg": return jpeg.Decode(file) default: return nil, nil } }, func(file *os.File, rgba *image.RGBA, options *jpeg.Options) error { switch ext { case "image/png", "image/jpeg": options.Quality = iQuality return jpeg.Encode(file, rgba, options) } return nil }) if err != nil { fmt.Println(err) } goto Finished } fi, err = os.Stat(sTarget) if err != nil { useAge() return } if fi.IsDir() { if bCompress { total, err = cccompress.CompressFolders(sTarget, sExt, sKey, iMode, bOverWrite, iWorkerNum) } else { total, err = cccompress.DecompressFolders(sTarget, sExt, sKey, iMode, bOverWrite, iWorkerNum) } } else { if bCompress { total, err = cccompress.CompressFile(sTarget, sKey, iMode, bOverWrite) } else { total, err = cccompress.DecompressFile(sTarget, sKey, iMode, bOverWrite) } } Finished: cost := time.Now().Unix() - s.Unix() log.Printf("Total[%v].finished!...cost[%v s].err[%v]", total, cost, err) return }
/* Copyright © 2023 SUSE LLC 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 cmd implements the rdctl commands package cmd import ( "fmt" "github.com/spf13/cobra" ) var uninstallCmd = &cobra.Command{ Use: "uninstall", Short: "Uninstall an RDX extension", Long: `rdctl extension uninstall <image-id> The <image-id> is an image reference, e.g. splatform/epinio-docker-desktop:latest (the tag is optional).`, Args: cobra.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error { cmd.SilenceUsage = true return uninstallExtension(args) }, } func init() { extensionCmd.AddCommand(uninstallCmd) } func uninstallExtension(args []string) error { imageID := args[0] endpoint := fmt.Sprintf("/%s/extensions/uninstall?id=%s", apiVersion, imageID) result, errorPacket, err := processRequestForAPI(doRequest("POST", endpoint)) if errorPacket != nil || err != nil { return displayAPICallResult(result, errorPacket, err) } msg := "no output from server" if result != nil { msg = string(result) } fmt.Printf("Uninstalling image %s: %s\n", imageID, msg) return nil }
package initialize import ( "github.com/gin-gonic/gin/binding" ut "github.com/go-playground/universal-translator" "github.com/go-playground/validator/v10" "shop-web/user-api/global" customValidator "shop-web/user-api/validator" ) func BindingValidate() { if v, ok := binding.Validator.Engine().(*validator.Validate); ok { _ = v.RegisterValidation("email", customValidator.ValidateEmail) _ = v.RegisterTranslation("email", global.Trans, func(ut ut.Translator) error { return ut.Add("email", "{0} 非法的邮箱", true) }, func(ut ut.Translator, fe validator.FieldError) string { tag, _ := ut.T("email", fe.Field()) return tag }) } }
package main import ( "fmt" ) func main() { // const norm1 = 2 // const norm3 = 4 // const norm2 string = "asd"; // var area int // area = norm1 * norm3 // fmt.Printf("面积是 : %d", area) // const( // read = 1 // face = 2 // less = 3 // ) // const ( // a = 1 // b = 2 // c = 3 // ) // fmt.Println(a,b,c) const( ali = iota tencent = iota other = "我的" baidu = iota ) fmt.Println(ali, tencent, other, baidu) // const ( // a = iota //0 // b //1 // c //2 // d = "ha" //独立值,iota += 1 // e //"ha" iota += 1 // f = 100 //iota +=1 // g //100 iota +=1 // h = iota //7,恢复计数 // i //8 // ) // fmt.Println(a,b,c,d,e,f,g,h,i) const( q = 2 w t y ) fmt.Println(q) fmt.Println(q) fmt.Println(t) fmt.Println(y) }
package compute import ( "encoding/json" "fmt" "net/http" "net/url" ) // NATRule represents a Network Address Translation (NAT) rule. // NAT rules are used to forward IPv4 traffic from a public IP address to a server's private IP address. type NATRule struct { ID string `json:"id"` NetworkDomainID string `json:"networkDomainId"` InternalIPAddress string `json:"internalIp"` ExternalIPAddress string `json:"externalIp"` CreateTime string `json:"createTime"` State string `json:"state"` DataCenterID string `json:"datacenterId"` } // NATRules represents a page of NATRule results. type NATRules struct { Rules []NATRule `json:"natRule"` PagedResult } // Request body for adding a NAT rule. type createNATRule struct { NetworkDomainID string `json:"networkDomainId"` InternalIPAddress string `json:"internalIp"` ExternalIPAddress *string `json:"externalIp,omitempty"` } // Request body for deleting a NAT rule. type deleteNATRule struct { RuleID string `json:"id"` } // GetNATRule retrieves the NAT rule with the specified Id. // Returns nil if no NAT rule is found with the specified Id. func (client *Client) GetNATRule(id string) (rule *NATRule, err error) { organizationID, err := client.getOrganizationID() if err != nil { return nil, err } requestURI := fmt.Sprintf("%s/network/natRule/%s", url.QueryEscape(organizationID), url.QueryEscape(id), ) request, err := client.newRequestV29(requestURI, http.MethodGet, nil) if err != nil { return nil, err } responseBody, statusCode, err := client.executeRequest(request) if err != nil { return nil, err } if statusCode != http.StatusOK { var apiResponse *APIResponseV2 apiResponse, err = readAPIResponseAsJSON(responseBody, statusCode) if err != nil { return nil, err } if apiResponse.ResponseCode == ResponseCodeResourceNotFound { return nil, nil // Not an error, but was not found. } return nil, apiResponse.ToError("Request to retrieve NAT rule failed with status code %d (%s): %s", statusCode, apiResponse.ResponseCode, apiResponse.Message) } rule = &NATRule{} err = json.Unmarshal(responseBody, rule) if err != nil { return nil, err } return rule, nil } // ListNATRules retrieves all NAT rules defined for the specified network domain. func (client *Client) ListNATRules(networkDomainID string, paging *Paging) (rules *NATRules, err error) { organizationID, err := client.getOrganizationID() if err != nil { return nil, err } requestURI := fmt.Sprintf("%s/network/natRule?networkDomainId=%s&%s", url.QueryEscape(organizationID), url.QueryEscape(networkDomainID), paging.EnsurePaging().toQueryParameters(), ) request, err := client.newRequestV22(requestURI, http.MethodGet, nil) if err != nil { return nil, err } responseBody, statusCode, err := client.executeRequest(request) if err != nil { return nil, err } if statusCode != http.StatusOK { var apiResponse *APIResponseV2 apiResponse, err = readAPIResponseAsJSON(responseBody, statusCode) if err != nil { return nil, err } return nil, apiResponse.ToError("Request to list NAT rules for network domain '%s' failed with status code %d (%s): %s", networkDomainID, statusCode, apiResponse.ResponseCode, apiResponse.Message) } rules = &NATRules{} err = json.Unmarshal(responseBody, rules) return rules, err } // AddNATRule creates a new NAT rule to forward traffic from the specified external IPv4 address to the specified internal IPv4 address. // If externalIPAddress is not specified, an unallocated IPv4 address will be used (if available). // // This operation is synchronous. func (client *Client) AddNATRule(networkDomainID string, internalIPAddress string, externalIPAddress *string) (natRuleID string, err error) { organizationID, err := client.getOrganizationID() if err != nil { return "", err } requestURI := fmt.Sprintf("%s/network/createNatRule", url.QueryEscape(organizationID), ) request, err := client.newRequestV213(requestURI, http.MethodPost, &createNATRule{ NetworkDomainID: networkDomainID, InternalIPAddress: internalIPAddress, ExternalIPAddress: externalIPAddress, }) responseBody, statusCode, err := client.executeRequest(request) if err != nil { return "", err } apiResponse, err := readAPIResponseAsJSON(responseBody, statusCode) if err != nil { return "", err } if apiResponse.ResponseCode != ResponseCodeOK { return "", apiResponse.ToError("Request to create NAT rule in network domain '%s' failed with unexpected status code %d (%s): %s", networkDomainID, statusCode, apiResponse.ResponseCode, apiResponse.Message) } // Expected: "info" { "name": "natRuleId", "value": "the-Id-of-the-new-NAT-rule" } if len(apiResponse.FieldMessages) != 1 || apiResponse.FieldMessages[0].FieldName != "natRuleId" { return "", apiResponse.ToError("Received an unexpected response (missing 'natRuleId') with status code %d (%s): %s", statusCode, apiResponse.ResponseCode, apiResponse.Message) } return apiResponse.FieldMessages[0].Message, nil } // DeleteNATRule deletes the specified NAT rule. // This operation is synchronous. func (client *Client) DeleteNATRule(id string) error { organizationID, err := client.getOrganizationID() if err != nil { return err } requestURI := fmt.Sprintf("%s/network/deleteNatRule", url.QueryEscape(organizationID), ) request, err := client.newRequestV22(requestURI, http.MethodPost, &deleteNATRule{id}, ) responseBody, statusCode, err := client.executeRequest(request) if err != nil { return err } apiResponse, err := readAPIResponseAsJSON(responseBody, statusCode) if err != nil { return err } if apiResponse.ResponseCode != ResponseCodeOK { return apiResponse.ToError("Request to delete NAT rule '%s' failed with unexpected status code %d (%s): %s", id, statusCode, apiResponse.ResponseCode, apiResponse.Message) } return nil }
package sgs import ( "io/ioutil" "net/http" "strconv" ) type authSrvPrx interface { setServerURI(string) vclient(clientID int, token string) bool enableTestClients(bool) } type sgasPrx struct { serverURI string testEnabled bool } func (me *sgasPrx) enableTestClients(enabled bool) { me.testEnabled = enabled } func (me *sgasPrx) vclient(clientID int, token string) bool { //clientIDs started with 0x40000000 are test client IDs if me.testEnabled && clientID > 0x40000000 { return true } requestURI := me.serverURI + "/vclient" + "?client=" + strconv.Itoa(clientID) + "&token=" + token client := http.Client{} request, _ := http.NewRequest("POST", requestURI, nil) response, err := client.Do(request) if err != nil { _log.Ntf("Invalid clientID or token %v %v", clientID, token) return false } registered, _ := ioutil.ReadAll(response.Body) return string(registered) != "" } func (me *sgasPrx) setServerURI(serverURI string) { me.serverURI = serverURI } func createSgasPrx() *sgasPrx { return &sgasPrx{} }
package model // Image model. type Image struct { File string `json:"file" bson:"file" binding:"required"` AssignedCategories []string `json:"assignedCategories" bson:"assignedCategories"` ProposedCategories []string `json:"proposedCategories" bson:"proposedCategories"` StarredCategory *string `json:"starredCategory" bson:"starredCategory"` }
package leaflet import ( "sync" "github.com/gowasm/gopherwasm/js" ) // NewCoordinate creates a new coordinate func NewCoordinate(lat, lng float64) *Coordinate { return &Coordinate{ lat: lat, lng: lng, } } func (c *Coordinate) JSValue() js.Value { c.valueOnce.Do(func() { v := gL.Call("latLng", c.lat, c.lng) c.v = &v }) return *c.v } // NewCoordinates creates a set of coordinates with alternating lats and longs // If the number of values passed in isn't even it won't create the last coordinate func NewCoordinates(latLngs ...float64) []*Coordinate { var coords []*Coordinate isLat := true var lat float64 for _, ll := range latLngs { if isLat { lat = ll isLat = false } else { coords = append(coords, NewCoordinate(lat, ll)) isLat = true } } return coords } type Coordinate struct { v *js.Value valueOnce sync.Once lat float64 lng float64 } func (c *Coordinate) Lat() float64 { return c.lat } func (c *Coordinate) Lng() float64 { return c.lng }
package common import ( "errors" "os" "path/filepath" "strings" "unicode/utf8" "github.com/joho/godotenv" ) const ( // EmailSuffix is the accepted email suffix. EmailSuffix = "@mastersny.org" // MaxRecipients is the maximum amount of recipients on one post. MaxRecipients = 10 // MaxImages is the maximum amount of images on one post. MaxImages = 5 // MaxMessageLength is the maximum amount of characters in a post message. MaxMessageLength = 2000 // MaxEmailLength is the maximum amount of characters in an email. MaxEmailLength = 255 // LogsDir is the location where all log files are stored. LogsDir = "./data/logs" // APIPort represents the default api server port APIPort = 8081 // envFile is the path to the file containing needed environment variables. envFile = "./.env" // Email notification info NotifEmail = "mastersseniors2020.com@gmail.com" NotifProvider = "smtp.gmail.com" NotifPort = 587 ) var ( // DatabaseName is the name of the Postgres database. DatabaseName = GetEnv("DATABASE_NAME") // NotifPassword is the password for the gmail account that sends notifications. NotifPassword = GetEnv("NOTIF_PASSWORD") // NotifsEnabled turns email notifications on or off. NotifsEnabled = false ) // CreateDirIfDoesNotExist creates a directory if it does not already exist. func CreateDirIfDoesNotExist(dir string) error { dir = filepath.FromSlash(dir) if _, err := os.Stat(dir); os.IsNotExist(err) { err = os.MkdirAll(dir, 0755) if err != nil { return err } } return nil } // GetEnv gets an environment variable func GetEnv(key string) string { // Load .env file every time err := godotenv.Load(envFile) if err != nil { panic(errors.New("could not load .env file")) } return os.Getenv(key) } // StringToArray returns an array given a string. func StringToArray(s string) []string { s = strings.TrimSuffix(s, "]") s = trimFirstRune(s) s = strings.ReplaceAll(s, "\"", "") return strings.Split(s, ", ") } func trimFirstRune(s string) string { _, i := utf8.DecodeRuneInString(s) return s[i:] }
package main import ( "fmt" "github.com/gofiber/fiber/v2" ) func main() { app := fiber.New() app.Get("/", func(c *fiber.Ctx) error { return c.SendString("Hello, World 👋!") }) app.Get("/:name", func(c *fiber.Ctx) error { return c.JSON(&fiber.Map{ "Message": fmt.Sprintf("Hello %s", c.Params("name")), }) }) app.Listen(":3000") }
package main import ( "context" "fmt" "log" "time" "golang.org/x/sync/errgroup" ) func main() { // 1つのサブタスクでエラーが発生したときに他の全てのサブタスクをキャンセルできる // withcontext使わない場合はGroup()を使う eg, ctx := errgroup.WithContext(context.Background()) ps := []string{"tom", "jhon", "yam"} for _, p := range ps { eg.Go(func() error { return workerWithContext(ctx, p) }) time.Sleep(2 * time.Second) } if err := eg.Wait(); err != nil { log.Fatal(err.Error()) } fmt.Println("done!") } func workerWithContext(ctx context.Context, s string) error { time.Sleep(2 * time.Second) fmt.Printf("my name is %s\n", s) return nil }
// Copyright 2021 PingCAP, 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 plugin_test import ( "context" "fmt" "strconv" "strings" "testing" "github.com/pingcap/tidb/kv" "github.com/pingcap/tidb/parser/mysql" "github.com/pingcap/tidb/plugin" "github.com/pingcap/tidb/server" "github.com/pingcap/tidb/session" "github.com/pingcap/tidb/sessionctx/variable" "github.com/pingcap/tidb/testkit" "github.com/stretchr/testify/require" ) // Audit tests cannot run in parallel. func TestAuditLogNormal(t *testing.T) { store := testkit.CreateMockStore(t) sv := server.CreateMockServer(t, store) defer sv.Close() conn := server.CreateMockConn(t, sv) defer conn.Close() session.DisableStats4Test() session.SetSchemaLease(0) type normalTest struct { sql string text string rows uint64 stmtType string dbs string tables string cmd string event plugin.GeneralEvent resCnt int } tests := []normalTest{ { sql: "CREATE DATABASE mynewdatabase", stmtType: "CreateDatabase", dbs: "mynewdatabase", }, { sql: "CREATE TABLE t1 (a INT NOT NULL)", stmtType: "CreateTable", dbs: "test", tables: "t1", }, { sql: "CREATE TABLE t2 LIKE t1", stmtType: "CreateTable", dbs: "test,test", tables: "t2,t1", }, { sql: "CREATE INDEX a ON t1 (a)", stmtType: "CreateIndex", dbs: "test", tables: "t1", }, { sql: "CREATE SEQUENCE seq", stmtType: "other", dbs: "test", tables: "seq", }, { sql: " create temporary table t3 (a int)", stmtType: "CreateTable", dbs: "test", tables: "t3", }, { sql: "create global temporary table t4 (a int) on commit delete rows", stmtType: "CreateTable", dbs: "test", tables: "t4", }, { sql: "CREATE VIEW v1 AS SELECT * FROM t1 WHERE a> 2", stmtType: "CreateView", dbs: "test,test", tables: "t1,v1", }, { sql: "USE test", stmtType: "Use", }, { sql: "DROP DATABASE mynewdatabase", stmtType: "DropDatabase", dbs: "mynewdatabase", }, { sql: "SHOW CREATE SEQUENCE seq", stmtType: "Show", dbs: "test", tables: "seq", }, { sql: "DROP SEQUENCE seq", stmtType: "other", dbs: "test", tables: "seq", }, { sql: "DROP TABLE t4", stmtType: "DropTable", dbs: "test", tables: "t4", }, { sql: "DROP VIEW v1", stmtType: "DropView", dbs: "test", tables: "v1", }, { sql: "ALTER TABLE t1 ADD COLUMN c1 INT NOT NULL", stmtType: "AlterTable", dbs: "test", tables: "t1", }, { sql: "ALTER TABLE t1 MODIFY c1 BIGINT", stmtType: "AlterTable", dbs: "test", tables: "t1", }, { sql: "ALTER TABLE t1 ADD INDEX (c1)", stmtType: "AlterTable", dbs: "test", tables: "t1", }, { sql: "ALTER TABLE t1 ALTER INDEX c1 INVISIBLE", stmtType: "AlterTable", dbs: "test", tables: "t1", }, { sql: "ALTER TABLE t1 RENAME INDEX c1 TO c2", stmtType: "AlterTable", dbs: "test", tables: "t1", }, { sql: "ALTER TABLE t1 DROP INDEX c2", stmtType: "AlterTable", dbs: "test", tables: "t1", }, { sql: "ALTER TABLE t1 CHANGE c1 c2 INT", stmtType: "AlterTable", dbs: "test", tables: "t1", }, { sql: "ALTER TABLE t1 DROP COLUMN c2", stmtType: "AlterTable", dbs: "test", tables: "t1", }, { sql: "CREATE SESSION BINDING FOR SELECT * FROM t1 WHERE a = 123 USING SELECT * FROM t1 IGNORE INDEX (a) WHERE a = 123", stmtType: "CreateBinding", }, { sql: "DROP SESSION BINDING FOR SELECT * FROM t1 WHERE a = 123", stmtType: "DropBinding", }, // { // sql: "LOAD STATS '/tmp/stats.json'", // stmtType: "other", // }, // { // sql: "DROP STATS t", // stmtType: "other", // }, { sql: "RENAME TABLE t2 TO t5", stmtType: "other", dbs: "test,test", tables: "t2,t5", }, { sql: "TRUNCATE t1", stmtType: "TruncateTable", dbs: "test", tables: "t1", }, // { // sql: "FLASHBACK TABLE t TO t1", // stmtType: "other", // dbs: "test", // tables: "t1", // }, // { // sql: "RECOVER TABLE t1", // stmtType: "other", // dbs: "test", // tables: "t1,t2", // }, { sql: "ALTER DATABASE test DEFAULT CHARACTER SET = utf8mb4", stmtType: "other", dbs: "test", }, { sql: "ADMIN RELOAD opt_rule_blacklist", stmtType: "other", }, // { // sql: "ADMIN PLUGINS ENABLE audit_test", // stmtType: "other", // }, { sql: "ADMIN FLUSH bindings", stmtType: "other", }, // { // sql: "ADMIN REPAIR TABLE t1 CREATE TABLE (id int)", // stmtType: "other", // dbs: "test", // tables: "t1", // }, { sql: "ADMIN SHOW SLOW RECENT 10", stmtType: "other", }, { sql: "ADMIN SHOW DDL JOBS", stmtType: "other", }, // { // sql: "ADMIN CANCEL DDL JOBS 1", // stmtType: "other", // }, { sql: "ADMIN CHECKSUM TABLE t1", stmtType: "other", // dbs: "test", // tables: "t1", }, { sql: "ADMIN CHECK TABLE t1", stmtType: "other", // dbs: "test", // tables: "t1", }, { sql: "ADMIN CHECK INDEX t1 a", stmtType: "other", // dbs: "test", // tables: "t1", }, { sql: "CREATE USER 'newuser' IDENTIFIED BY 'newuserpassword'", stmtType: "CreateUser", }, { sql: "ALTER USER 'newuser' IDENTIFIED BY 'newnewpassword'", stmtType: "other", }, { sql: "CREATE ROLE analyticsteam", stmtType: "CreateUser", }, { sql: "GRANT SELECT ON test.* TO analyticsteam", stmtType: "Grant", dbs: "test", }, { sql: "GRANT analyticsteam TO 'newuser'", stmtType: "other", }, { sql: "SET DEFAULT ROLE analyticsteam TO newuser;", stmtType: "other", }, { sql: "REVOKE SELECT ON test.* FROM 'analyticsteam'", stmtType: "Revoke", dbs: "test", }, { sql: "DROP ROLE analyticsteam", stmtType: "other", }, { sql: "FLUSH PRIVILEGES", stmtType: "other", }, { sql: "SET PASSWORD FOR 'newuser' = 'test'", stmtType: "Set", }, // { // sql: "SET ROLE ALL", // stmtType: "other", // }, { sql: "DROP USER 'newuser'", stmtType: "other", }, { sql: "analyze table t1", stmtType: "AnalyzeTable", dbs: "test", tables: "t1", }, { sql: "SPLIT TABLE t1 BETWEEN (0) AND (1000000000) REGIONS 16", stmtType: "other", // dbs: "test", // tables: "t1", }, // { // sql: "BACKUP DATABASE `test` TO '.'", // stmtType: "other", // dbs: "test", // }, // { // sql: "RESTORE DATABASE * FROM '.'", // stmtType: "other", // }, // { // sql: "CHANGE DRAINER TO NODE_STATE ='paused' FOR NODE_ID 'drainer1'", // stmtType: "other", // }, // { // sql: "CHANGE PUMP TO NODE_STATE ='paused' FOR NODE_ID 'pump1'", // stmtType: "other", // }, { sql: "BEGIN", stmtType: "Begin", }, { sql: "ROLLBACK", stmtType: "Rollback", }, { sql: "START TRANSACTION", stmtType: "Begin", }, { sql: "COMMIT", stmtType: "Commit", }, // { // sql: "SHOW DRAINER STATUS", // stmtType: "Show", // }, // { // sql: "SHOW PUMP STATUS", // stmtType: "Show", // }, // { // sql: "SHOW GRANTS", // stmtType: "Show", // }, { sql: "SHOW PROCESSLIST", stmtType: "Show", }, // { // sql: "SHOW BACKUPS", // stmtType: "Show", // }, // { // sql: "SHOW RESTORES", // stmtType: "Show", // }, { sql: "show analyze status", stmtType: "Show", }, { sql: "SHOW SESSION BINDINGS", stmtType: "Show", }, { sql: "SHOW BUILTINS", stmtType: "Show", }, { sql: "SHOW CHARACTER SET", stmtType: "Show", }, { sql: "SHOW COLLATION", stmtType: "Show", }, { sql: "show columns from t1", stmtType: "Show", }, { sql: "show fields from t1", stmtType: "Show", }, // { // sql: "SHOW CONFIG", // stmtType: "Show", // }, { sql: "SHOW CREATE TABLE t1", stmtType: "Show", dbs: "test", tables: "t1", }, { sql: "SHOW CREATE USER 'root'", stmtType: "Show", }, { sql: "SHOW DATABASES", stmtType: "Show", }, { sql: "SHOW ENGINES", stmtType: "Show", }, { sql: "SHOW ERRORS", stmtType: "Show", }, { sql: "SHOW INDEXES FROM t1", stmtType: "Show", }, { sql: "SHOW MASTER STATUS", stmtType: "Show", }, { sql: "SHOW PLUGINS", stmtType: "Show", }, { sql: "show privileges", stmtType: "Show", }, { sql: "SHOW PROFILES", stmtType: "Show", }, // { // sql: "SHOW PUMP STATUS", // stmtType: "Show", // }, { sql: "SHOW SCHEMAS", stmtType: "Show", }, { sql: "SHOW STATS_HEALTHY", stmtType: "Show", dbs: "mysql", }, { sql: "show stats_histograms", stmtType: "Show", dbs: "mysql", tables: "stats_histograms", }, { sql: "show stats_meta", stmtType: "Show", dbs: "mysql", tables: "stats_meta", }, { sql: "show status", stmtType: "Show", }, { sql: "show table t1 next_row_id", stmtType: "Show", dbs: "test", tables: "t1", }, { sql: "show table t1 regions", stmtType: "Show", }, { sql: "SHOW TABLE STATUS LIKE 't1'", stmtType: "Show", resCnt: 3, // Start + SHOW TABLE + Internal SELECT .. FROM IS.TABLES in current session }, { sql: "SHOW TABLES", stmtType: "Show", }, { sql: "SHOW VARIABLES", stmtType: "Show", }, { sql: "SHOW WARNINGS", stmtType: "Show", }, { sql: "SET @number = 5", stmtType: "Set", }, { sql: "SET NAMES utf8", stmtType: "Set", }, { sql: "SET CHARACTER SET utf8mb4", stmtType: "Set", }, { sql: "SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED", stmtType: "Set", }, { sql: "SET SESSION sql_mode = 'STRICT_TRANS_TABLES,NO_AUTO_CREATE_USER'", stmtType: "Set", }, { sql: "PREPARE mystmt FROM 'SELECT ? as num FROM DUAL'", stmtType: "Prepare", }, { sql: "EXECUTE mystmt USING @number", text: "SELECT ? as num FROM DUAL", stmtType: "Select", }, { sql: "DEALLOCATE PREPARE mystmt", stmtType: "Deallocate", }, { sql: "INSERT INTO t1 VALUES (1), (2)", stmtType: "Insert", dbs: "test", tables: "t1", rows: 2, }, { sql: "DELETE FROM t1 WHERE a = 2", stmtType: "Delete", dbs: "test", tables: "t1", rows: 1, }, { sql: "REPLACE INTO t1 VALUES(3)", stmtType: "Replace", dbs: "test", tables: "t1", rows: 1, }, { sql: "UPDATE t1 SET a=5 WHERE a=1", stmtType: "Update", dbs: "test", tables: "t1", rows: 1, }, { sql: "DO 1", stmtType: "other", }, // { // sql: "LOAD DATA LOCAL INFILE 'data.csv' INTO TABLE t1 FIELDS TERMINATED BY ',' ENCLOSED BY '\"' LINES TERMINATED BY '\r\n' IGNORE 1 LINES (id)", // stmtType: "LoadData", // dbs: "test", // tables: "t1", // }, { sql: "SELECT * FROM t1", stmtType: "Select", dbs: "test", tables: "t1", }, { sql: "SELECT 1", stmtType: "Select", }, { sql: "TABLE t1", stmtType: "Select", dbs: "test", tables: "t1", }, { sql: "EXPLAIN ANALYZE SELECT * FROM t1 WHERE a = 1", stmtType: "ExplainAnalyzeSQL", // dbs: "test", // tables: "t1", }, { sql: "EXPLAIN SELECT * FROM t1", stmtType: "ExplainSQL", // dbs: "test", // tables: "t1", }, { sql: "EXPLAIN SELECT * FROM t1 WHERE a = 1", stmtType: "ExplainSQL", // dbs: "test", // tables: "t1", }, { sql: "DESC SELECT * FROM t1 WHERE a = 1", stmtType: "ExplainSQL", // dbs: "test", // tables: "t1", }, { sql: "DESCRIBE SELECT * FROM t1 WHERE a = 1", stmtType: "ExplainSQL", // dbs: "test", // tables: "t1", }, { sql: "trace format='row' select * from t1", stmtType: "Trace", // dbs: "test", // tables: "t1", }, { sql: "flush status", stmtType: "other", }, { sql: "FLUSH TABLES", stmtType: "other", }, // { // sql: "KILL TIDB 2", // stmtType: "other", // }, // { // sql: "SHUTDOWN", // stmtType: "Shutdow", // }, // { // sql: "ALTER INSTANCE RELOAD TLS", // stmtType: "other", // }, } testResults := make([]normalTest, 0) dbNames := make([]string, 0) tableNames := make([]string, 0) onGeneralEvent := func(ctx context.Context, sctx *variable.SessionVars, event plugin.GeneralEvent, cmd string) { dbNames = dbNames[:0] tableNames = tableNames[:0] for _, value := range sctx.StmtCtx.Tables { dbNames = append(dbNames, value.DB) tableNames = append(tableNames, value.Table) } audit := normalTest{ text: sctx.StmtCtx.OriginalSQL, rows: sctx.StmtCtx.AffectedRows(), stmtType: sctx.StmtCtx.StmtType, dbs: strings.Join(dbNames, ","), tables: strings.Join(tableNames, ","), cmd: cmd, event: event, } testResults = append(testResults, audit) } loadPlugin(t, onGeneralEvent) defer plugin.Shutdown(context.Background()) require.NoError(t, conn.HandleQuery(context.Background(), "use test")) for _, test := range tests { testResults = testResults[:0] errMsg := fmt.Sprintf("statement: %s", test.sql) query := append([]byte{mysql.ComQuery}, []byte(test.sql)...) ctx := kv.WithInternalSourceType(context.Background(), kv.InternalTxnOthers) err := conn.Dispatch(ctx, query) require.NoError(t, err, errMsg) resultCount := test.resCnt if resultCount == 0 { resultCount = 2 } require.Equal(t, resultCount, len(testResults), errMsg) result := testResults[0] require.Equal(t, "Query", result.cmd, errMsg) require.Equal(t, plugin.Starting, result.event, errMsg) result = testResults[resultCount-1] require.Equal(t, "Query", result.cmd, errMsg) if test.text == "" { require.Equal(t, test.sql, result.text, errMsg) } else { require.Equal(t, test.text, result.text, errMsg) } require.Equal(t, test.rows, result.rows, errMsg) require.Equal(t, test.stmtType, result.stmtType, errMsg) require.Equal(t, test.dbs, result.dbs, errMsg) require.Equal(t, test.tables, result.tables, errMsg) require.Equal(t, "Query", result.cmd, errMsg) require.Equal(t, plugin.Completed, result.event, errMsg) for i := 1; i < resultCount-1; i++ { result = testResults[i] require.Equal(t, "Query", result.cmd, errMsg) require.Equal(t, plugin.Completed, result.event, errMsg) } } } func loadPlugin(t *testing.T, onGeneralEvent func(context.Context, *variable.SessionVars, plugin.GeneralEvent, string)) { ctx := context.Background() pluginName := "audit_test" pluginVersion := uint16(1) pluginSign := pluginName + "-" + strconv.Itoa(int(pluginVersion)) cfg := plugin.Config{ Plugins: []string{pluginSign}, PluginDir: "", EnvVersion: map[string]uint16{"go": 1112}, } validate := func(ctx context.Context, manifest *plugin.Manifest) error { return nil } onInit := func(ctx context.Context, manifest *plugin.Manifest) error { return nil } onShutdown := func(ctx context.Context, manifest *plugin.Manifest) error { return nil } onConnectionEvent := func(ctx context.Context, event plugin.ConnectionEvent, info *variable.ConnectionInfo) error { return nil } // setup load test hook. loadOne := func(p *plugin.Plugin, dir string, pluginID plugin.ID) (manifest func() *plugin.Manifest, err error) { return func() *plugin.Manifest { m := &plugin.AuditManifest{ Manifest: plugin.Manifest{ Kind: plugin.Audit, Name: pluginName, Version: pluginVersion, OnInit: onInit, OnShutdown: onShutdown, Validate: validate, }, OnGeneralEvent: onGeneralEvent, OnConnectionEvent: onConnectionEvent, } return plugin.ExportManifest(m) }, nil } plugin.SetTestHook(loadOne) // trigger load. err := plugin.Load(ctx, cfg) require.NoErrorf(t, err, "load plugin [%s] fail, error [%s]\n", pluginSign, err) err = plugin.Init(ctx, cfg) require.NoErrorf(t, err, "init plugin [%s] fail, error [%s]\n", pluginSign, err) }
// ----------------------------------------------------------------------------- // Web package used for encapsulating web controllers. // ----------------------------------------------------------------------------- package controller import ( "bytes" "encoding/gob" "godistributed-rabbitmq/common" "godistributed-rabbitmq/common/dto" "godistributed-rabbitmq/web/model" "log" "net/http" "sync" "github.com/gorilla/websocket" "github.com/streadway/amqp" ) // ----------------------------------------------------------------------------- // message - struct that encapsulates json transport object. // ----------------------------------------------------------------------------- type message struct { Type string `json:"type"` Data interface{} `json:"data"` } // ----------------------------------------------------------------------------- // SocketController - struct that encapsulates work with AMQP and Web sockets. // ----------------------------------------------------------------------------- type SocketController struct { connection *amqp.Connection channel *amqp.Channel sockets []*websocket.Conn mutex sync.Mutex upgrader websocket.Upgrader } // ----------------------------------------------------------------------------- // NewSocketController - creates new web socket controller. // ----------------------------------------------------------------------------- func NewSocketController() (controller *SocketController) { controller = new(SocketController) controller.connection, controller.channel = common.GetChannel(common.URL_GUEST) controller.upgrader = websocket.Upgrader{ ReadBufferSize: 1024, WriteBufferSize: 1024, } go controller.listenForSources() go controller.listenForMessages() return } // ----------------------------------------------------------------------------- // addSocket - adds new web socket to controller. // ----------------------------------------------------------------------------- func (controller *SocketController) addSocket(socket *websocket.Conn) { controller.mutex.Lock() log.Print("addSocket") controller.sockets = append(controller.sockets, socket) controller.mutex.Unlock() } // ----------------------------------------------------------------------------- // removeSocket - removes existing web socket from controller. // ----------------------------------------------------------------------------- func (controller *SocketController) removeSocket(socket *websocket.Conn) { controller.mutex.Lock() log.Print("removeSocket") socket.Close() for index := range controller.sockets { if controller.sockets[index] == socket { controller.sockets = append(controller.sockets[:index], controller.sockets[index+1:]...) } } controller.mutex.Unlock() } // ----------------------------------------------------------------------------- // handleMessage -handles incoming http request. // ----------------------------------------------------------------------------- func (controller *SocketController) handleMessage(writter http.ResponseWriter, request *http.Request) { log.Println(request.Header) connection, error := controller.upgrader.Upgrade(writter, request, request.Header) common.FailOnError(error, "Upgrader error") controller.addSocket(connection) go controller.listenForDiscoveryRequests(connection) } // ----------------------------------------------------------------------------- // listenForSources - // ----------------------------------------------------------------------------- func (controller *SocketController) listenForSources() { queue := common.GetQueue("", controller.channel, true) controller.channel.QueueBind(queue.Name, "", common.WEBAPP_SOURCE_EXCHANGE, false, nil) messages, _ := controller.channel.Consume(queue.Name, "", true, false, false, false, nil) for msg := range messages { sensor, error := model.GetSensorByName(string(msg.Body)) common.FailOnError(error, "Cannot get the sensor by name") log.Printf("Soket sensor: %s", sensor.Name) controller.sendMessage(message{ Type: "source", Data: sensor, }) } } // ----------------------------------------------------------------------------- // listenForMessages - // ----------------------------------------------------------------------------- func (controller *SocketController) listenForMessages() { queue := common.GetQueue("", controller.channel, true) controller.channel.QueueBind( queue.Name, //name string, "", //key string, common.WEBAPP_READINGS_EXCHANGE, //exchange string, false, //noWait bool, nil) //args amqp.Table) msgs, _ := controller.channel.Consume( queue.Name, //queue string, "", //consumer string, true, //autoAck bool, false, //exclusive bool, false, //noLocal bool, false, //noWait bool, nil) //args amqp.Table) log.Printf("Web Soket: Waiting for messages") for msg := range msgs { buffer := bytes.NewBuffer(msg.Body) decoder := gob.NewDecoder(buffer) readout := dto.Readout{} err := decoder.Decode(&readout) if err != nil { println(err.Error()) } log.Printf("Web Soket: Message received %v", readout) controller.sendMessage(message{ Type: "reading", Data: readout, }) } } // ----------------------------------------------------------------------------- // listenForDiscoveryRequests - // ----------------------------------------------------------------------------- func (controller *SocketController) listenForDiscoveryRequests(socket *websocket.Conn) { for { msg := message{} err := socket.ReadJSON(&msg) if err != nil { log.Printf("Socket Error! %v:", err) controller.removeSocket(socket) break } if msg.Type == "discover" { controller.channel.Publish( "", //exchange string, common.WEBAPP_DISCOVERY_EXCHANGE, //key string, false, //mandatory bool, false, //immediate bool, amqp.Publishing{}) //msg amqp.Publishing) } } } // ----------------------------------------------------------------------------- // sendMessage - // ----------------------------------------------------------------------------- func (controller *SocketController) sendMessage(msg message) { socketsToRemove := []*websocket.Conn{} log.Printf("Message sources: %v", controller.sockets) for _, socket := range controller.sockets { err := socket.WriteJSON(msg) if err != nil { socketsToRemove = append(socketsToRemove, socket) common.FailOnError(err, "Cannot Write JSON") } else { log.Printf("JSON: %v", msg) } } for _, socket := range socketsToRemove { controller.removeSocket(socket) } }
package file import "io" func SetOsCreate(f func(name string) (closer io.WriteCloser, err error)) { osCreate = f }
// Copyright 2021 Google LLC. All Rights Reserved. // // 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 server import ( "context" "github.com/GoogleCloudPlatform/declarative-resource-client-library/dcl" computepb "github.com/GoogleCloudPlatform/declarative-resource-client-library/python/proto/compute/compute_go_proto" emptypb "github.com/GoogleCloudPlatform/declarative-resource-client-library/python/proto/empty_go_proto" "github.com/GoogleCloudPlatform/declarative-resource-client-library/services/google/compute" ) // Server implements the gRPC interface for Interconnect. type InterconnectServer struct{} // ProtoToInterconnectLinkTypeEnum converts a InterconnectLinkTypeEnum enum from its proto representation. func ProtoToComputeInterconnectLinkTypeEnum(e computepb.ComputeInterconnectLinkTypeEnum) *compute.InterconnectLinkTypeEnum { if e == 0 { return nil } if n, ok := computepb.ComputeInterconnectLinkTypeEnum_name[int32(e)]; ok { e := compute.InterconnectLinkTypeEnum(n[len("ComputeInterconnectLinkTypeEnum"):]) return &e } return nil } // ProtoToInterconnectInterconnectTypeEnum converts a InterconnectInterconnectTypeEnum enum from its proto representation. func ProtoToComputeInterconnectInterconnectTypeEnum(e computepb.ComputeInterconnectInterconnectTypeEnum) *compute.InterconnectInterconnectTypeEnum { if e == 0 { return nil } if n, ok := computepb.ComputeInterconnectInterconnectTypeEnum_name[int32(e)]; ok { e := compute.InterconnectInterconnectTypeEnum(n[len("ComputeInterconnectInterconnectTypeEnum"):]) return &e } return nil } // ProtoToInterconnectOperationalStatusEnum converts a InterconnectOperationalStatusEnum enum from its proto representation. func ProtoToComputeInterconnectOperationalStatusEnum(e computepb.ComputeInterconnectOperationalStatusEnum) *compute.InterconnectOperationalStatusEnum { if e == 0 { return nil } if n, ok := computepb.ComputeInterconnectOperationalStatusEnum_name[int32(e)]; ok { e := compute.InterconnectOperationalStatusEnum(n[len("ComputeInterconnectOperationalStatusEnum"):]) return &e } return nil } // ProtoToInterconnectExpectedOutagesSourceEnum converts a InterconnectExpectedOutagesSourceEnum enum from its proto representation. func ProtoToComputeInterconnectExpectedOutagesSourceEnum(e computepb.ComputeInterconnectExpectedOutagesSourceEnum) *compute.InterconnectExpectedOutagesSourceEnum { if e == 0 { return nil } if n, ok := computepb.ComputeInterconnectExpectedOutagesSourceEnum_name[int32(e)]; ok { e := compute.InterconnectExpectedOutagesSourceEnum(n[len("ComputeInterconnectExpectedOutagesSourceEnum"):]) return &e } return nil } // ProtoToInterconnectExpectedOutagesStateEnum converts a InterconnectExpectedOutagesStateEnum enum from its proto representation. func ProtoToComputeInterconnectExpectedOutagesStateEnum(e computepb.ComputeInterconnectExpectedOutagesStateEnum) *compute.InterconnectExpectedOutagesStateEnum { if e == 0 { return nil } if n, ok := computepb.ComputeInterconnectExpectedOutagesStateEnum_name[int32(e)]; ok { e := compute.InterconnectExpectedOutagesStateEnum(n[len("ComputeInterconnectExpectedOutagesStateEnum"):]) return &e } return nil } // ProtoToInterconnectExpectedOutagesIssueTypeEnum converts a InterconnectExpectedOutagesIssueTypeEnum enum from its proto representation. func ProtoToComputeInterconnectExpectedOutagesIssueTypeEnum(e computepb.ComputeInterconnectExpectedOutagesIssueTypeEnum) *compute.InterconnectExpectedOutagesIssueTypeEnum { if e == 0 { return nil } if n, ok := computepb.ComputeInterconnectExpectedOutagesIssueTypeEnum_name[int32(e)]; ok { e := compute.InterconnectExpectedOutagesIssueTypeEnum(n[len("ComputeInterconnectExpectedOutagesIssueTypeEnum"):]) return &e } return nil } // ProtoToInterconnectStateEnum converts a InterconnectStateEnum enum from its proto representation. func ProtoToComputeInterconnectStateEnum(e computepb.ComputeInterconnectStateEnum) *compute.InterconnectStateEnum { if e == 0 { return nil } if n, ok := computepb.ComputeInterconnectStateEnum_name[int32(e)]; ok { e := compute.InterconnectStateEnum(n[len("ComputeInterconnectStateEnum"):]) return &e } return nil } // ProtoToInterconnectExpectedOutages converts a InterconnectExpectedOutages object from its proto representation. func ProtoToComputeInterconnectExpectedOutages(p *computepb.ComputeInterconnectExpectedOutages) *compute.InterconnectExpectedOutages { if p == nil { return nil } obj := &compute.InterconnectExpectedOutages{ Name: dcl.StringOrNil(p.GetName()), Description: dcl.StringOrNil(p.GetDescription()), Source: ProtoToComputeInterconnectExpectedOutagesSourceEnum(p.GetSource()), State: ProtoToComputeInterconnectExpectedOutagesStateEnum(p.GetState()), IssueType: ProtoToComputeInterconnectExpectedOutagesIssueTypeEnum(p.GetIssueType()), StartTime: dcl.Int64OrNil(p.GetStartTime()), EndTime: dcl.Int64OrNil(p.GetEndTime()), } for _, r := range p.GetAffectedCircuits() { obj.AffectedCircuits = append(obj.AffectedCircuits, r) } return obj } // ProtoToInterconnectCircuitInfos converts a InterconnectCircuitInfos object from its proto representation. func ProtoToComputeInterconnectCircuitInfos(p *computepb.ComputeInterconnectCircuitInfos) *compute.InterconnectCircuitInfos { if p == nil { return nil } obj := &compute.InterconnectCircuitInfos{ GoogleCircuitId: dcl.StringOrNil(p.GetGoogleCircuitId()), GoogleDemarcId: dcl.StringOrNil(p.GetGoogleDemarcId()), CustomerDemarcId: dcl.StringOrNil(p.GetCustomerDemarcId()), } return obj } // ProtoToInterconnect converts a Interconnect resource from its proto representation. func ProtoToInterconnect(p *computepb.ComputeInterconnect) *compute.Interconnect { obj := &compute.Interconnect{ Description: dcl.StringOrNil(p.GetDescription()), SelfLink: dcl.StringOrNil(p.GetSelfLink()), Id: dcl.Int64OrNil(p.GetId()), Name: dcl.StringOrNil(p.GetName()), Location: dcl.StringOrNil(p.GetLocation()), LinkType: ProtoToComputeInterconnectLinkTypeEnum(p.GetLinkType()), RequestedLinkCount: dcl.Int64OrNil(p.GetRequestedLinkCount()), InterconnectType: ProtoToComputeInterconnectInterconnectTypeEnum(p.GetInterconnectType()), AdminEnabled: dcl.Bool(p.GetAdminEnabled()), NocContactEmail: dcl.StringOrNil(p.GetNocContactEmail()), CustomerName: dcl.StringOrNil(p.GetCustomerName()), OperationalStatus: ProtoToComputeInterconnectOperationalStatusEnum(p.GetOperationalStatus()), ProvisionedLinkCount: dcl.Int64OrNil(p.GetProvisionedLinkCount()), PeerIPAddress: dcl.StringOrNil(p.GetPeerIpAddress()), GoogleIPAddress: dcl.StringOrNil(p.GetGoogleIpAddress()), GoogleReferenceId: dcl.StringOrNil(p.GetGoogleReferenceId()), State: ProtoToComputeInterconnectStateEnum(p.GetState()), Project: dcl.StringOrNil(p.GetProject()), } for _, r := range p.GetInterconnectAttachments() { obj.InterconnectAttachments = append(obj.InterconnectAttachments, r) } for _, r := range p.GetExpectedOutages() { obj.ExpectedOutages = append(obj.ExpectedOutages, *ProtoToComputeInterconnectExpectedOutages(r)) } for _, r := range p.GetCircuitInfos() { obj.CircuitInfos = append(obj.CircuitInfos, *ProtoToComputeInterconnectCircuitInfos(r)) } return obj } // InterconnectLinkTypeEnumToProto converts a InterconnectLinkTypeEnum enum to its proto representation. func ComputeInterconnectLinkTypeEnumToProto(e *compute.InterconnectLinkTypeEnum) computepb.ComputeInterconnectLinkTypeEnum { if e == nil { return computepb.ComputeInterconnectLinkTypeEnum(0) } if v, ok := computepb.ComputeInterconnectLinkTypeEnum_value["InterconnectLinkTypeEnum"+string(*e)]; ok { return computepb.ComputeInterconnectLinkTypeEnum(v) } return computepb.ComputeInterconnectLinkTypeEnum(0) } // InterconnectInterconnectTypeEnumToProto converts a InterconnectInterconnectTypeEnum enum to its proto representation. func ComputeInterconnectInterconnectTypeEnumToProto(e *compute.InterconnectInterconnectTypeEnum) computepb.ComputeInterconnectInterconnectTypeEnum { if e == nil { return computepb.ComputeInterconnectInterconnectTypeEnum(0) } if v, ok := computepb.ComputeInterconnectInterconnectTypeEnum_value["InterconnectInterconnectTypeEnum"+string(*e)]; ok { return computepb.ComputeInterconnectInterconnectTypeEnum(v) } return computepb.ComputeInterconnectInterconnectTypeEnum(0) } // InterconnectOperationalStatusEnumToProto converts a InterconnectOperationalStatusEnum enum to its proto representation. func ComputeInterconnectOperationalStatusEnumToProto(e *compute.InterconnectOperationalStatusEnum) computepb.ComputeInterconnectOperationalStatusEnum { if e == nil { return computepb.ComputeInterconnectOperationalStatusEnum(0) } if v, ok := computepb.ComputeInterconnectOperationalStatusEnum_value["InterconnectOperationalStatusEnum"+string(*e)]; ok { return computepb.ComputeInterconnectOperationalStatusEnum(v) } return computepb.ComputeInterconnectOperationalStatusEnum(0) } // InterconnectExpectedOutagesSourceEnumToProto converts a InterconnectExpectedOutagesSourceEnum enum to its proto representation. func ComputeInterconnectExpectedOutagesSourceEnumToProto(e *compute.InterconnectExpectedOutagesSourceEnum) computepb.ComputeInterconnectExpectedOutagesSourceEnum { if e == nil { return computepb.ComputeInterconnectExpectedOutagesSourceEnum(0) } if v, ok := computepb.ComputeInterconnectExpectedOutagesSourceEnum_value["InterconnectExpectedOutagesSourceEnum"+string(*e)]; ok { return computepb.ComputeInterconnectExpectedOutagesSourceEnum(v) } return computepb.ComputeInterconnectExpectedOutagesSourceEnum(0) } // InterconnectExpectedOutagesStateEnumToProto converts a InterconnectExpectedOutagesStateEnum enum to its proto representation. func ComputeInterconnectExpectedOutagesStateEnumToProto(e *compute.InterconnectExpectedOutagesStateEnum) computepb.ComputeInterconnectExpectedOutagesStateEnum { if e == nil { return computepb.ComputeInterconnectExpectedOutagesStateEnum(0) } if v, ok := computepb.ComputeInterconnectExpectedOutagesStateEnum_value["InterconnectExpectedOutagesStateEnum"+string(*e)]; ok { return computepb.ComputeInterconnectExpectedOutagesStateEnum(v) } return computepb.ComputeInterconnectExpectedOutagesStateEnum(0) } // InterconnectExpectedOutagesIssueTypeEnumToProto converts a InterconnectExpectedOutagesIssueTypeEnum enum to its proto representation. func ComputeInterconnectExpectedOutagesIssueTypeEnumToProto(e *compute.InterconnectExpectedOutagesIssueTypeEnum) computepb.ComputeInterconnectExpectedOutagesIssueTypeEnum { if e == nil { return computepb.ComputeInterconnectExpectedOutagesIssueTypeEnum(0) } if v, ok := computepb.ComputeInterconnectExpectedOutagesIssueTypeEnum_value["InterconnectExpectedOutagesIssueTypeEnum"+string(*e)]; ok { return computepb.ComputeInterconnectExpectedOutagesIssueTypeEnum(v) } return computepb.ComputeInterconnectExpectedOutagesIssueTypeEnum(0) } // InterconnectStateEnumToProto converts a InterconnectStateEnum enum to its proto representation. func ComputeInterconnectStateEnumToProto(e *compute.InterconnectStateEnum) computepb.ComputeInterconnectStateEnum { if e == nil { return computepb.ComputeInterconnectStateEnum(0) } if v, ok := computepb.ComputeInterconnectStateEnum_value["InterconnectStateEnum"+string(*e)]; ok { return computepb.ComputeInterconnectStateEnum(v) } return computepb.ComputeInterconnectStateEnum(0) } // InterconnectExpectedOutagesToProto converts a InterconnectExpectedOutages object to its proto representation. func ComputeInterconnectExpectedOutagesToProto(o *compute.InterconnectExpectedOutages) *computepb.ComputeInterconnectExpectedOutages { if o == nil { return nil } p := &computepb.ComputeInterconnectExpectedOutages{} p.SetName(dcl.ValueOrEmptyString(o.Name)) p.SetDescription(dcl.ValueOrEmptyString(o.Description)) p.SetSource(ComputeInterconnectExpectedOutagesSourceEnumToProto(o.Source)) p.SetState(ComputeInterconnectExpectedOutagesStateEnumToProto(o.State)) p.SetIssueType(ComputeInterconnectExpectedOutagesIssueTypeEnumToProto(o.IssueType)) p.SetStartTime(dcl.ValueOrEmptyInt64(o.StartTime)) p.SetEndTime(dcl.ValueOrEmptyInt64(o.EndTime)) sAffectedCircuits := make([]string, len(o.AffectedCircuits)) for i, r := range o.AffectedCircuits { sAffectedCircuits[i] = r } p.SetAffectedCircuits(sAffectedCircuits) return p } // InterconnectCircuitInfosToProto converts a InterconnectCircuitInfos object to its proto representation. func ComputeInterconnectCircuitInfosToProto(o *compute.InterconnectCircuitInfos) *computepb.ComputeInterconnectCircuitInfos { if o == nil { return nil } p := &computepb.ComputeInterconnectCircuitInfos{} p.SetGoogleCircuitId(dcl.ValueOrEmptyString(o.GoogleCircuitId)) p.SetGoogleDemarcId(dcl.ValueOrEmptyString(o.GoogleDemarcId)) p.SetCustomerDemarcId(dcl.ValueOrEmptyString(o.CustomerDemarcId)) return p } // InterconnectToProto converts a Interconnect resource to its proto representation. func InterconnectToProto(resource *compute.Interconnect) *computepb.ComputeInterconnect { p := &computepb.ComputeInterconnect{} p.SetDescription(dcl.ValueOrEmptyString(resource.Description)) p.SetSelfLink(dcl.ValueOrEmptyString(resource.SelfLink)) p.SetId(dcl.ValueOrEmptyInt64(resource.Id)) p.SetName(dcl.ValueOrEmptyString(resource.Name)) p.SetLocation(dcl.ValueOrEmptyString(resource.Location)) p.SetLinkType(ComputeInterconnectLinkTypeEnumToProto(resource.LinkType)) p.SetRequestedLinkCount(dcl.ValueOrEmptyInt64(resource.RequestedLinkCount)) p.SetInterconnectType(ComputeInterconnectInterconnectTypeEnumToProto(resource.InterconnectType)) p.SetAdminEnabled(dcl.ValueOrEmptyBool(resource.AdminEnabled)) p.SetNocContactEmail(dcl.ValueOrEmptyString(resource.NocContactEmail)) p.SetCustomerName(dcl.ValueOrEmptyString(resource.CustomerName)) p.SetOperationalStatus(ComputeInterconnectOperationalStatusEnumToProto(resource.OperationalStatus)) p.SetProvisionedLinkCount(dcl.ValueOrEmptyInt64(resource.ProvisionedLinkCount)) p.SetPeerIpAddress(dcl.ValueOrEmptyString(resource.PeerIPAddress)) p.SetGoogleIpAddress(dcl.ValueOrEmptyString(resource.GoogleIPAddress)) p.SetGoogleReferenceId(dcl.ValueOrEmptyString(resource.GoogleReferenceId)) p.SetState(ComputeInterconnectStateEnumToProto(resource.State)) p.SetProject(dcl.ValueOrEmptyString(resource.Project)) sInterconnectAttachments := make([]string, len(resource.InterconnectAttachments)) for i, r := range resource.InterconnectAttachments { sInterconnectAttachments[i] = r } p.SetInterconnectAttachments(sInterconnectAttachments) sExpectedOutages := make([]*computepb.ComputeInterconnectExpectedOutages, len(resource.ExpectedOutages)) for i, r := range resource.ExpectedOutages { sExpectedOutages[i] = ComputeInterconnectExpectedOutagesToProto(&r) } p.SetExpectedOutages(sExpectedOutages) sCircuitInfos := make([]*computepb.ComputeInterconnectCircuitInfos, len(resource.CircuitInfos)) for i, r := range resource.CircuitInfos { sCircuitInfos[i] = ComputeInterconnectCircuitInfosToProto(&r) } p.SetCircuitInfos(sCircuitInfos) return p } // applyInterconnect handles the gRPC request by passing it to the underlying Interconnect Apply() method. func (s *InterconnectServer) applyInterconnect(ctx context.Context, c *compute.Client, request *computepb.ApplyComputeInterconnectRequest) (*computepb.ComputeInterconnect, error) { p := ProtoToInterconnect(request.GetResource()) res, err := c.ApplyInterconnect(ctx, p) if err != nil { return nil, err } r := InterconnectToProto(res) return r, nil } // applyComputeInterconnect handles the gRPC request by passing it to the underlying Interconnect Apply() method. func (s *InterconnectServer) ApplyComputeInterconnect(ctx context.Context, request *computepb.ApplyComputeInterconnectRequest) (*computepb.ComputeInterconnect, error) { cl, err := createConfigInterconnect(ctx, request.GetServiceAccountFile()) if err != nil { return nil, err } return s.applyInterconnect(ctx, cl, request) } // DeleteInterconnect handles the gRPC request by passing it to the underlying Interconnect Delete() method. func (s *InterconnectServer) DeleteComputeInterconnect(ctx context.Context, request *computepb.DeleteComputeInterconnectRequest) (*emptypb.Empty, error) { cl, err := createConfigInterconnect(ctx, request.GetServiceAccountFile()) if err != nil { return nil, err } return &emptypb.Empty{}, cl.DeleteInterconnect(ctx, ProtoToInterconnect(request.GetResource())) } // ListComputeInterconnect handles the gRPC request by passing it to the underlying InterconnectList() method. func (s *InterconnectServer) ListComputeInterconnect(ctx context.Context, request *computepb.ListComputeInterconnectRequest) (*computepb.ListComputeInterconnectResponse, error) { cl, err := createConfigInterconnect(ctx, request.GetServiceAccountFile()) if err != nil { return nil, err } resources, err := cl.ListInterconnect(ctx, request.GetProject()) if err != nil { return nil, err } var protos []*computepb.ComputeInterconnect for _, r := range resources.Items { rp := InterconnectToProto(r) protos = append(protos, rp) } p := &computepb.ListComputeInterconnectResponse{} p.SetItems(protos) return p, nil } func createConfigInterconnect(ctx context.Context, service_account_file string) (*compute.Client, error) { conf := dcl.NewConfig(dcl.WithUserAgent("dcl-test"), dcl.WithCredentialsFile(service_account_file)) return compute.NewClient(conf), nil }
package libService import "io" type IFormatter interface { Format(name, version string) IFormatter WriteOut(writer io.Writer) error } // 格式化信息结构体 type FormatterStruct struct { PackageName string ImportList map[string]ImportItem Name string StructName string Version string FieldList []Field } // struct列信息结构体 type Field struct { Name string Type string StructTag string Comment string } type ImportItem struct { Alias string Package string }
package main import ( "encoding/json" "log" "net/http" "net/url" "text/template" ) var homeTemplate = template.Must(template.ParseFiles("home.html")) var searchURL = "http://elastic:9200/codecivil/article/_search" func main() { http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { homeTemplate.Execute(w, nil) }) http.HandleFunc("/search", search) http.ListenAndServe(":8080", nil) } type searchResults struct { Hits struct { Hits []hits } } type hits struct { Article struct { Section string Text string } `json:"_source"` } func search(w http.ResponseWriter, r *http.Request) { results := new(searchResults) query := r.URL.Query().Get("q") if len(query) < 4 { log.Printf("search term '%s' too short\n", query) json.NewEncoder(w).Encode(results) return } elasticurl := buildSearchUrl(query) log.Printf("Searching for %s\n", elasticurl) resp, err := http.Get(elasticurl) if err != nil { log.Printf("error searching for %s\n%s", elasticurl, err) http.Error(w, err.Error(), http.StatusInternalServerError) return } defer resp.Body.Close() json.NewDecoder(resp.Body).Decode(results) json.NewEncoder(w).Encode(results) } func buildSearchUrl(query string) string { u, _ := url.Parse(searchURL) parameters := url.Values{} parameters.Add("size", "100") parameters.Add("q", "Text:"+query) u.RawQuery = parameters.Encode() return u.String() }
package node import "go-neural_network/bookForm" type Book struct { Form } func CreateBook(entity DataEntity) (book FormInterface) { book = &Book{} book.Init(bookForm.CollectionProperties) for key, value := range entity.Properties { book.SetProperty(key, value) } book.SetResult(entity.Result) return } func (book *Book) AutoSetProperties() { book.setDefault(bookForm.AppointmentBookProperties, bookForm.FreeTimeSpending) book.setDefault(bookForm.LanguageBookProperties, bookForm.InRussianLanguage) book.setDefault(bookForm.WayOfSpeechOrganizationBookProperties, bookForm.Prose) book.setDefault(bookForm.ExistanceOfLoveLineBookProperties, bookForm.LoveLine) }
package routers import ( "github.com/barrydev/api-3h-shop/src/common/response" "github.com/barrydev/api-3h-shop/src/controllers" "github.com/gin-gonic/gin" ) func BindUser(router *gin.RouterGroup) { router.POST("/register", func(c *gin.Context) { handle := response.Handle{Context: c} handle.Try(controllers.RegisterUser).Then(response.SendSuccess).Catch(response.SendError) }) router.POST("/authenticate", func(c *gin.Context) { handle := response.Handle{Context: c} handle.Try(controllers.AuthenticateUser).Then(response.SendSuccess).Catch(response.SendError) }) } func BindUserAuth(router *gin.RouterGroup) { router.GET("", func(c *gin.Context) { handle := response.Handle{Context: c} handle.Try(controllers.GetListUser).Then(response.SendSuccess).Catch(response.SendError) }) router.GET("/:userId", func(c *gin.Context) { handle := response.Handle{Context: c} handle.Try(controllers.GetUserById).Then(response.SendSuccess).Catch(response.SendError) }) router.POST("/:userId/password/change", func(c *gin.Context) { handle := response.Handle{Context: c} handle.Try(controllers.ChangeUserPassword).Then(response.SendSuccess).Catch(response.SendError) }) router.POST("/:userId/update", func(c *gin.Context) { handle := response.Handle{Context: c} handle.Try(controllers.UpdateProfile).Then(response.SendSuccess).Catch(response.SendError) }) } func BindUserAdmin(router *gin.RouterGroup) { router.GET("", func(c *gin.Context) { handle := response.Handle{Context: c} handle.Try(controllers.GetListUser).Then(response.SendSuccess).Catch(response.SendError) }) router.GET("/:userId", func(c *gin.Context) { handle := response.Handle{Context: c} handle.Try(controllers.GetUserById).Then(response.SendSuccess).Catch(response.SendError) }) router.POST("", func(c *gin.Context) { handle := response.Handle{Context: c} handle.Try(controllers.InsertUser).Then(response.SendSuccess).Catch(response.SendError) }) router.POST("/:userId/update", func(c *gin.Context) { handle := response.Handle{Context: c} handle.Try(controllers.UpdateUser).Then(response.SendSuccess).Catch(response.SendError) }) // router.POST("/:userId/delete", func(c *gin.Context) { // handle := response.Handle{Context: c} // handle.Try(controllers.DeleteUser).Then(response.SendSuccess).Catch(response.SendError) // }) router.POST("/:userId/role/change", func(c *gin.Context) { handle := response.Handle{Context: c} handle.Try(controllers.ChangeUserRole).Then(response.SendSuccess).Catch(response.SendError) }) router.POST("/:userId/password/reset", func(c *gin.Context) { handle := response.Handle{Context: c} handle.Try(controllers.ResetUserPassword).Then(response.SendSuccess).Catch(response.SendError) }) }
package health import ( "github.com/square/p2/pkg/types" ) // Result stores the health state of a service. type Result struct { ID types.PodID Node types.NodeName Service string Status HealthState } // ResultList is a type alias that adds some extra methods that operate on the list. type ResultList []Result // MaxValue returns a pointer to a Result with the best health status in the list. If the // list is empty, returns nil. func (l ResultList) MaxValue() *Result { if len(l) == 0 { return nil } max := 0 for i := range l[1:] { if Compare(l[i+1].Status, l[max].Status) > 0 { max = i + 1 } } return &l[max] } // MaxResult is a shortcult that builds a ResultList from the inputs and calls // ResultList.MaxValue() on it. func MaxResult(r1 Result, rest ...Result) Result { l := make(ResultList, 1, 1+len(rest)) l[0] = r1 l = append(l, rest...) return *l.MaxValue() } // MinValue returns a pointer to a Result with the worst health status in the list. If the // list is empty, returns nil. func (l ResultList) MinValue() *Result { if len(l) == 0 { return nil } min := 0 for i := range l[1:] { if Compare(l[i+1].Status, l[min].Status) < 0 { min = i + 1 } } return &l[min] } // MinResult is a shortcut that builds a ResultList from the inputs and calls // ResultList.MinValue() on it. func MinResult(r1 Result, rest ...Result) Result { l := make(ResultList, 1, 1+len(rest)) l[0] = r1 l = append(l, rest...) return *l.MinValue() }
package transactions import ( "context" "fmt" "net/http" "strings" "github.com/flow-hydraulics/flow-wallet-api/configs" "github.com/flow-hydraulics/flow-wallet-api/datastore" "github.com/flow-hydraulics/flow-wallet-api/errors" "github.com/flow-hydraulics/flow-wallet-api/flow_helpers" "github.com/flow-hydraulics/flow-wallet-api/jobs" "github.com/flow-hydraulics/flow-wallet-api/keys" "github.com/flow-hydraulics/flow-wallet-api/templates" "github.com/onflow/cadence" "github.com/onflow/flow-go-sdk" "github.com/onflow/flow-go-sdk/client" ) // Service defines the API for transaction HTTP handlers. type Service struct { store Store km keys.Manager fc *client.Client wp *jobs.WorkerPool cfg *configs.Config } // NewService initiates a new transaction service. func NewService( cfg *configs.Config, store Store, km keys.Manager, fc *client.Client, wp *jobs.WorkerPool, ) *Service { // TODO(latenssi): safeguard against nil config? return &Service{store, km, fc, wp, cfg} } func (s *Service) Create(c context.Context, sync bool, proposerAddress string, raw templates.Raw, tType Type) (*jobs.Job, *Transaction, error) { transaction := &Transaction{} job, err := s.wp.AddJob(func() (string, error) { ctx := c if !sync { ctx = context.Background() } // Check if the input is a valid address proposerAddress, err := flow_helpers.ValidateAddress(proposerAddress, s.cfg.ChainID) if err != nil { return "", err } latestBlockId, err := flow_helpers.LatestBlockId(ctx, s.fc) if err != nil { return "", err } var ( payer keys.Authorizer proposer keys.Authorizer authorizers []keys.Authorizer ) // Admin should always be the payer of the transaction fees payer, err = s.km.AdminAuthorizer(ctx) if err != nil { return "", err } if proposerAddress == s.cfg.AdminAddress { proposer, err = s.km.AdminProposalKey(ctx) if err != nil { return "", err } } else { proposer, err = s.km.UserAuthorizer(ctx, flow.HexToAddress(proposerAddress)) if err != nil { return "", err } } // Check if we need to add proposer as an authorizer if strings.Contains(raw.Code, ": AuthAccount") { authorizers = append(authorizers, proposer) } builder, err := templates.NewBuilderFromRaw(raw) if err != nil { return "", err } if err := New(transaction, latestBlockId, builder, tType, proposer, payer, authorizers); err != nil { return transaction.TransactionId, err } // Send the transaction if err := transaction.Send(ctx, s.fc); err != nil { return transaction.TransactionId, err } // Insert to datastore if err := s.store.InsertTransaction(transaction); err != nil { return transaction.TransactionId, err } // Wait for the transaction to be sealed if err := transaction.Wait(ctx, s.fc, s.cfg.TransactionTimeout); err != nil { return transaction.TransactionId, err } // Update in datastore err = s.store.UpdateTransaction(transaction) return transaction.TransactionId, err }) if err != nil { _, isJErr := err.(*errors.JobQueueFull) if isJErr { err = &errors.RequestError{ StatusCode: http.StatusServiceUnavailable, Err: fmt.Errorf("max capacity reached, try again later"), } } return nil, nil, err } err = job.Wait(sync) return job, transaction, err } // List returns all transactions in the datastore for a given account. func (s *Service) List(tType Type, address string, limit, offset int) ([]Transaction, error) { // Check if the input is a valid address address, err := flow_helpers.ValidateAddress(address, s.cfg.ChainID) if err != nil { return []Transaction{}, err } o := datastore.ParseListOptions(limit, offset) return s.store.Transactions(tType, address, o) } // Details returns a specific transaction. func (s *Service) Details(tType Type, address, transactionId string) (result Transaction, err error) { // Check if the input is a valid address address, err = flow_helpers.ValidateAddress(address, s.cfg.ChainID) if err != nil { return } // Check if the input is a valid transaction id if err = flow_helpers.ValidateTransactionId(transactionId); err != nil { return } // Get from datastore result, err = s.store.Transaction(tType, address, transactionId) if err != nil && err.Error() == "record not found" { // Convert error to a 404 RequestError err = &errors.RequestError{ StatusCode: http.StatusNotFound, Err: fmt.Errorf("transaction not found"), } return } return } // Execute a script func (s *Service) ExecuteScript(ctx context.Context, raw templates.Raw) (cadence.Value, error) { return s.fc.ExecuteScriptAtLatestBlock( ctx, []byte(raw.Code), templates.MustDecodeArgs(raw.Arguments), ) } func (s *Service) UpdateTransaction(t *Transaction) error { return s.store.UpdateTransaction(t) } func (s *Service) GetOrCreateTransaction(transactionId string) *Transaction { return s.store.GetOrCreateTransaction(transactionId) }
package handler import ( "HumoAcademy/models" "github.com/gin-gonic/gin" "net/http" ) func (h *Handler) adminSignUp (c *gin.Context) { var input models.Admin if err := c.BindJSON(&input); err != nil { NewErrorResponse(c, http.StatusBadRequest, "bad","invalid input body") return } id, err := h.services.Admin.CreateAdmin(input) if err != nil { NewErrorResponse(c, http.StatusInternalServerError, "bad", err.Error()) return } c.JSON(http.StatusOK, map[string]interface{}{ "status": "ok", "id": id, }) } func (h *Handler) adminSignIn (c *gin.Context) { var input models.AdminSignInInput if err := c.BindJSON(&input); err != nil { NewErrorResponse(c, http.StatusBadRequest, "bad", err.Error()) return } token, err := h.services.GenerateToken(input.Username, input.Password) if err != nil { NewErrorResponse(c, http.StatusInternalServerError, "bad", err.Error()) return } c.JSON(http.StatusOK, map[string]interface{}{ "token": token, "status": "ok", }) }
package function import ( "net/http" "net/http/httptest" "testing" ) // //import ( // "bytes" // "github.com/buger/jsonparser" // "io/ioutil" // "log" // "net/http" // "net/http/httptest" // "testing" //) func TestGet(t *testing.T) { t.Log("testing GET....") } func TestPost(t *testing.T) { t.Log("testing POST....") // create a user req, err := http.NewRequest("POST", "/", nil) if err != nil { t.Fatal(err) } rr := httptest.NewRecorder() handler := http.HandlerFunc(User) handler.ServeHTTP(rr, req) if status := rr.Code; status != http.StatusCreated { t.Errorf("handler returned wrong status code: got %v want %v", status, http.StatusOK) } } //func TestGet(t *testing.T) { // // // create a user // req, err := http.NewRequest("POST", "/", nil) // if err != nil { // t.Fatal(err) // } // // rr := httptest.NewRecorder() // handler := http.HandlerFunc(TheFunction) // handler.ServeHTTP(rr, req) // // body, err := ioutil.ReadAll(rr.Body) // if err != nil { // t.Error(err) // } // // userID, _, _, err := jsonparser.Get(body, "id") // if err != nil { // t.Error(err) // } // log.Printf("Created user with id %s", userID) // // // req, err = http.NewRequest("GET", "?id="+string(userID), nil) // if err != nil { // t.Fatal(err) // } // rr = httptest.NewRecorder() // handler = TheFunction // handler.ServeHTTP(rr, req) // // if status := rr.Code; status != http.StatusOK { // t.Errorf("handler returned wrong status code: got %v want %v", // status, http.StatusOK) // } // // //finally delete the user // req, err = http.NewRequest("DELETE", "?id="+string(userID), nil) // if err != nil { // t.Fatal(err) // } // rr = httptest.NewRecorder() // handler = TheFunction // handler.ServeHTTP(rr, req) // // // testing without the id returns a bad request // req, err = http.NewRequest("GET", "/", nil) // if err != nil { // t.Fatal(err) // } // rr = httptest.NewRecorder() // handler = TheFunction // handler.ServeHTTP(rr, req) // // if status := rr.Code; status != http.StatusBadRequest { // t.Errorf("handler returned wrong status code: got %v want %v", // status, http.StatusBadRequest) // } // // // testing with a not found id results in not found // req, err = http.NewRequest("GET", "?id=XYZ", nil) // if err != nil { // t.Fatal(err) // } // rr = httptest.NewRecorder() // handler = TheFunction // handler.ServeHTTP(rr, req) // // if status := rr.Code; status != http.StatusNotFound { // t.Errorf("handler returned wrong status code: got %v want %v", // status, http.StatusNotFound) // } //} // // //func TestPost(t *testing.T) { // req, err := http.NewRequest("POST", "/", nil) // if err != nil { // t.Fatal(err) // } // // rr := httptest.NewRecorder() // handler := http.HandlerFunc(TheFunction) // handler.ServeHTTP(rr, req) // // if status := rr.Code; status != http.StatusCreated { // t.Errorf("handler returned wrong status code: got %v want %v", // status, http.StatusCreated) // } // // body, err := ioutil.ReadAll(rr.Body) // if err != nil { // t.Error(err) // } // // userID, _, _, err := jsonparser.Get(body, "id") // if err != nil { // t.Error(err) // } // log.Printf("Created user with id %s", userID) // // cleanup the user // req, err = http.NewRequest("DELETE", "?id="+string(userID), nil) // if err != nil { // t.Fatal(err) // } // rr = httptest.NewRecorder() // handler = http.HandlerFunc(TheFunction) // handler.ServeHTTP(rr, req) // log.Printf("User Deleted .... id %s", userID) //} // //func TestPut(t *testing.T) { // // // create a new user // req, err := http.NewRequest("POST", "/", nil) // if err != nil { // t.Fatal(err) // } // // rr := httptest.NewRecorder() // handler := http.HandlerFunc(TheFunction) // handler.ServeHTTP(rr, req) // // body, err := ioutil.ReadAll(rr.Body) // if err != nil { // t.Error(err) // } // // userID, _, _, err := jsonparser.Get(body, "id") // if err != nil { // t.Error(err) // } // log.Printf("Created user with id %s", userID) // // var jsonStr = []byte(`{"id":"`+string(userID)+`", "name": "Jon Snow"}`) // req, err = http.NewRequest("PUT", "/", bytes.NewBuffer(jsonStr)) // if err != nil { // t.Fatal(err) // } // // rr = httptest.NewRecorder() // handler = TheFunction // handler.ServeHTTP(rr, req) // // if status := rr.Code; status != http.StatusOK { // t.Errorf("handler returned wrong status code: got %v want %v", // status, http.StatusOK) // } // // // check to see if it updated ok // req, err = http.NewRequest("GET", "?id="+string(userID), nil) // if err != nil { // t.Fatal(err) // } // rr = httptest.NewRecorder() // handler = TheFunction // handler.ServeHTTP(rr, req) // // body, err = ioutil.ReadAll(rr.Body) // if err != nil { // t.Error(err) // } // // updatedName, _, _, err := jsonparser.Get(body, "name") // if err != nil { // t.Fatal(err) // } // // if string(updatedName) != "Jon Snow" { // t.Fatal("update failed!") // } // // req, err = http.NewRequest("DELETE", "?id="+string(userID), nil) // if err != nil { // t.Fatal(err) // } // // rr = httptest.NewRecorder() // handler = TheFunction // handler.ServeHTTP(rr, req) // // if status := rr.Code; status != http.StatusOK { // t.Errorf("handler returned wrong status code: got %v want %v", // status, http.StatusOK) // } // log.Printf("Deleting user with id %s", userID) //} // //func TestDelete(t *testing.T) { // // create a new user // req, err := http.NewRequest("POST", "/", nil) // if err != nil { // t.Fatal(err) // } // // rr := httptest.NewRecorder() // handler := http.HandlerFunc(TheFunction) // handler.ServeHTTP(rr, req) // // body, err := ioutil.ReadAll(rr.Body) // if err != nil { // t.Error(err) // } // // userID, _, _, err := jsonparser.Get(body, "id") // if err != nil { // t.Error(err) // } // log.Printf("Created user with id %s", userID) // // // req, err = http.NewRequest("DELETE", "?id="+string(userID), nil) // if err != nil { // t.Fatal(err) // } // // rr = httptest.NewRecorder() // handler = TheFunction // handler.ServeHTTP(rr, req) // // if status := rr.Code; status != http.StatusOK { // t.Errorf("handler returned wrong status code: got %v want %v", // status, http.StatusOK) // } // log.Printf("Deleting user with id %s", userID) //}
package query import ( "time" "github.com/gofrs/uuid" ) type FarmEventQuery interface { FindAllByID(farmUID uuid.UUID) <-chan QueryResult } type FarmReadQuery interface { FindByID(farmUID uuid.UUID) <-chan QueryResult FindAll() <-chan QueryResult } type ReservoirEventQuery interface { FindAllByID(reservoirUID uuid.UUID) <-chan QueryResult } type ReservoirReadQuery interface { FindByID(reservoirUID uuid.UUID) <-chan QueryResult FindAllByFarm(farmUID uuid.UUID) <-chan QueryResult } type AreaEventQuery interface { FindAllByID(areaUID uuid.UUID) <-chan QueryResult } type AreaReadQuery interface { FindByID(reservoirUID uuid.UUID) <-chan QueryResult FindAllByFarm(farmUID uuid.UUID) <-chan QueryResult FindByIDAndFarm(areaUID, farmUID uuid.UUID) <-chan QueryResult FindAreasByReservoirID(reservoirUID uuid.UUID) <-chan QueryResult CountAreas(farmUID uuid.UUID) <-chan QueryResult } type CropReadQuery interface { FindAllCropByArea(areaUID uuid.UUID) <-chan QueryResult CountCropsByArea(areaUID uuid.UUID) <-chan QueryResult } type MaterialEventQuery interface { FindAllByID(materialUID uuid.UUID) <-chan QueryResult } type MaterialReadQuery interface { FindAll(materialType, materialTypeDetail string, page, limit int) <-chan QueryResult CountAll(materialType, materialTypeDetail string) <-chan QueryResult FindByID(materialUID uuid.UUID) <-chan QueryResult } type QueryResult struct { Result interface{} Error error } type FarmReadQueryResult struct { UID uuid.UUID Name string Type string Latitude string Longitude string CountryCode string CityCode string CreatedDate time.Time } type ReservoirReadQueryResult struct { UID uuid.UUID Name string WaterSource WaterSource FarmUID uuid.UUID Notes []ReservoirNote CreatedDate time.Time } type WaterSource struct { Type string Capacity float32 } type ReservoirNote struct { UID uuid.UUID Content string CreatedDate time.Time } type CountAreaCropQueryResult struct { PlantQuantity int TotalCropBatch int } type AreaCropQueryResult struct { CropUID uuid.UUID `json:"uid"` BatchID string `json:"batch_id"` InitialArea InitialArea `json:"initial_area"` MovingDate time.Time `json:"moving_date"` CreatedDate time.Time `json:"created_date"` DaysSinceSeeding int `json:"days_since_seeding"` Inventory Inventory `json:"inventory"` Container Container `json:"container"` } type InitialArea struct { AreaUID uuid.UUID `json:"uid"` Name string `json:"name"` } type Inventory struct { UID uuid.UUID `json:"uid"` Name string `json:"name"` } type Container struct { Type ContainerType `json:"type"` Quantity int `json:"quantity"` } type ContainerType struct { Code string `json:"code"` Cell int `json:"cell"` }
package crypto import ( "crypto/aes" "crypto/cipher" ) func AESDecryptBytes(payload []byte) ([]byte, error) { iv, cipherText := payload[:16], payload[16:] block, err := aes.NewCipher([]byte("fx6v22kwCjm9oasmMnymhpVJa6H4Xpkc")) if err != nil { return []byte{}, err } aesgcm, err := cipher.NewGCMWithNonceSize(block, 16) if err != nil { return []byte{}, err } plaintext, err := aesgcm.Open(nil, iv, cipherText, nil) if err != nil { return []byte{}, err } return plaintext, nil } func AESEncryptBytes(payload []byte) ([]byte, error) { iv := []byte("BfVsfgErXsbfiA00") block, err := aes.NewCipher([]byte("fx6v22kwCjm9oasmMnymhpVJa6H4Xpkc")) if err != nil { return []byte{}, err } aesgcm, err := cipher.NewGCMWithNonceSize(block, 16) if err != nil { return []byte{}, err } ciphertext := aesgcm.Seal(nil, iv, payload, nil) return append(iv, ciphertext...), nil }
package statik //This just for fixing the error in importing empty github.com/ColorPlatform/color-sdk/client/lcd/statik
package kvdecoder import ( "fmt" "github.com/iotaledger/goshimmer/dapps/valuetransfers/packages/address" "github.com/iotaledger/goshimmer/dapps/valuetransfers/packages/balance" "github.com/iotaledger/wasp/packages/coretypes" "github.com/iotaledger/wasp/packages/hashing" "github.com/iotaledger/wasp/packages/kv" "github.com/iotaledger/wasp/packages/kv/codec" ) type decoder struct { kv kv.KVStoreReader log coretypes.LogInterface } func New(kv kv.KVStoreReader, log ...coretypes.LogInterface) decoder { var l coretypes.LogInterface if len(log) > 0 { l = log[0] } return decoder{kv, l} } func (p *decoder) panic(err error) { if p.log == nil { panic(err) } p.log.Panicf("%v", err) } func (p *decoder) GetInt64(key kv.Key, def ...int64) (int64, error) { v, exists, err := codec.DecodeInt64(p.kv.MustGet(key)) if err != nil { return 0, fmt.Errorf("GetInt64: decoding parameter '%s': %v", key, err) } if exists { return v, nil } if len(def) == 0 { return 0, fmt.Errorf("GetInt64: mandatory parameter '%s' does not exist", key) } return def[0], nil } func (p *decoder) MustGetInt64(key kv.Key, def ...int64) int64 { ret, err := p.GetInt64(key, def...) if err != nil { p.panic(err) } return ret } func (p *decoder) GetString(key kv.Key, def ...string) (string, error) { v, exists, err := codec.DecodeString(p.kv.MustGet(key)) if err != nil { return "", fmt.Errorf("GetString: decoding parameter '%s': %v", key, err) } if exists { return v, nil } if len(def) == 0 { return "", fmt.Errorf("GetString: mandatory parameter '%s' does not exist", key) } return def[0], nil } func (p *decoder) MustGetString(key kv.Key, def ...string) string { ret, err := p.GetString(key, def...) if err != nil { p.panic(err) } return ret } func (p *decoder) GetHname(key kv.Key, def ...coretypes.Hname) (coretypes.Hname, error) { v, exists, err := codec.DecodeHname(p.kv.MustGet(key)) if err != nil { return 0, fmt.Errorf("GetHname: decoding parameter '%s': %v", key, err) } if exists { return v, nil } if len(def) == 0 { return 0, fmt.Errorf("GetHname: mandatory parameter '%s' does not exist", key) } return def[0], nil } func (p *decoder) MustGetHname(key kv.Key, def ...coretypes.Hname) coretypes.Hname { ret, err := p.GetHname(key, def...) if err != nil { p.panic(err) } return ret } func (p *decoder) GetHashValue(key kv.Key, def ...hashing.HashValue) (hashing.HashValue, error) { v, exists, err := codec.DecodeHashValue(p.kv.MustGet(key)) if err != nil { return [32]byte{}, fmt.Errorf("GetHashValue: decoding parameter '%s': %v", key, err) } if exists { return *v, nil } if len(def) == 0 { return hashing.HashValue{}, fmt.Errorf("GetHashValue: mandatory parameter '%s' does not exist", key) } return def[0], nil } func (p *decoder) MustGetHashValue(key kv.Key, def ...hashing.HashValue) hashing.HashValue { ret, err := p.GetHashValue(key, def...) if err != nil { p.panic(err) } return ret } func (p *decoder) GetAddress(key kv.Key, def ...address.Address) (address.Address, error) { v, exists, err := codec.DecodeAddress(p.kv.MustGet(key)) if err != nil { return address.Address{}, fmt.Errorf("GetAddress: decoding parameter '%s': %v", key, err) } if exists { return v, nil } if len(def) == 0 { return address.Address{}, fmt.Errorf("GetAddress: mandatory parameter '%s' does not exist", key) } return def[0], nil } func (p *decoder) MustGetAddress(key kv.Key, def ...address.Address) address.Address { ret, err := p.GetAddress(key, def...) if err != nil { p.panic(err) } return ret } func (p *decoder) GetContractID(key kv.Key, def ...coretypes.ContractID) (coretypes.ContractID, error) { v, exists, err := codec.DecodeContractID(p.kv.MustGet(key)) if err != nil { return coretypes.ContractID{}, fmt.Errorf("GetContractID: decoding parameter '%s': %v", key, err) } if exists { return v, nil } if len(def) == 0 { return coretypes.ContractID{}, fmt.Errorf("GetContractID: mandatory parameter '%s' does not exist", key) } return def[0], nil } func (p *decoder) MustGetContractID(key kv.Key, def ...coretypes.ContractID) coretypes.ContractID { ret, err := p.GetContractID(key, def...) if err != nil { p.panic(err) } return ret } func (p *decoder) GetAgentID(key kv.Key, def ...coretypes.AgentID) (coretypes.AgentID, error) { v, exists, err := codec.DecodeAgentID(p.kv.MustGet(key)) if err != nil { return coretypes.AgentID{}, fmt.Errorf("GetAgentID: decoding parameter '%s': %v", key, err) } if exists { return v, nil } if len(def) == 0 { return coretypes.AgentID{}, fmt.Errorf("GetAgentID: mandatory parameter '%s' does not exist", key) } return def[0], nil } func (p *decoder) MustGetAgentID(key kv.Key, def ...coretypes.AgentID) coretypes.AgentID { ret, err := p.GetAgentID(key, def...) if err != nil { p.panic(err) } return ret } func (p *decoder) GetChainID(key kv.Key, def ...coretypes.ChainID) (coretypes.ChainID, error) { v, exists, err := codec.DecodeChainID(p.kv.MustGet(key)) if err != nil { return coretypes.ChainID{}, fmt.Errorf("GetChainID: decoding parameter '%s': %v", key, err) } if exists { return v, nil } if len(def) == 0 { return coretypes.ChainID{}, fmt.Errorf("GetChainID: mandatory parameter '%s' does not exist", key) } return def[0], nil } func (p *decoder) MustGetChainID(key kv.Key, def ...coretypes.ChainID) coretypes.ChainID { ret, err := p.GetChainID(key, def...) if err != nil { p.panic(err) } return ret } func (p *decoder) GetColor(key kv.Key, def ...balance.Color) (balance.Color, error) { v, exists, err := codec.DecodeColor(p.kv.MustGet(key)) if err != nil { return balance.Color{}, fmt.Errorf("GetColor: decoding parameter '%s': %v", key, err) } if exists { return v, nil } if len(def) == 0 { return balance.Color{}, fmt.Errorf("GetColor: mandatory parameter '%s' does not exist", key) } return def[0], nil } func (p *decoder) MustGetColor(key kv.Key, def ...balance.Color) balance.Color { ret, err := p.GetColor(key, def...) if err != nil { p.panic(err) } return ret } // nil means does not exist func (p *decoder) GetBytes(key kv.Key, def ...[]byte) ([]byte, error) { v := p.kv.MustGet(key) if v != nil { return v, nil } if len(def) == 0 { return nil, fmt.Errorf("MustGetBytes: mandatory parameter '%s' does not exist", key) } return def[0], nil } func (p *decoder) MustGetBytes(key kv.Key, def ...[]byte) []byte { ret, err := p.GetBytes(key, def...) if err != nil { p.panic(err) } return ret }
package tar import ( "archive/tar" "fmt" "io" "os" gopath "path" fp "path/filepath" "strings" ) type Extractor struct { Path string Progress func(int64) int64 } func (te *Extractor) Extract(reader io.Reader) error { tarReader := tar.NewReader(reader) // Check if the output path already exists, so we know whether we should // create our output with that name, or if we should put the output inside // a preexisting directory rootExists := true rootIsDir := false if stat, err := os.Stat(te.Path); err != nil && os.IsNotExist(err) { rootExists = false } else if err != nil { return err } else if stat.IsDir() { rootIsDir = true } // files come recursively in order (i == 0 is root directory) for i := 0; ; i++ { header, err := tarReader.Next() if err != nil && err != io.EOF { return err } if header == nil || err == io.EOF { break } switch header.Typeflag { case tar.TypeDir: if err := te.extractDir(header, i); err != nil { return err } case tar.TypeReg: if err := te.extractFile(header, tarReader, i, rootExists, rootIsDir); err != nil { return err } case tar.TypeSymlink: if err := te.extractSymlink(header); err != nil { return err } default: return fmt.Errorf("unrecognized tar header type: %d", header.Typeflag) } } return nil } // outputPath returns the path at whicht o place tarPath func (te *Extractor) outputPath(tarPath string) string { elems := strings.Split(tarPath, "/") // break into elems elems = elems[1:] // remove original root path := fp.Join(elems...) // join elems path = fp.Join(te.Path, path) // rebase on extractor root return path } func (te *Extractor) extractDir(h *tar.Header, depth int) error { path := te.outputPath(h.Name) if depth == 0 { // if this is the root root directory, use it as the output path for remaining files te.Path = path } return os.MkdirAll(path, 0755) } func (te *Extractor) extractSymlink(h *tar.Header) error { return os.Symlink(h.Linkname, te.outputPath(h.Name)) } func (te *Extractor) extractFile(h *tar.Header, r *tar.Reader, depth int, rootExists bool, rootIsDir bool) error { path := te.outputPath(h.Name) if depth == 0 { // if depth is 0, this is the only file (we aren't 'ipfs get'ing a directory) if rootExists && rootIsDir { // putting file inside of a root dir. fnameo := gopath.Base(h.Name) fnamen := fp.Base(path) // add back original name if lost. if fnameo != fnamen { path = fp.Join(path, fnameo) } } // else if old file exists, just overwrite it. } file, err := os.Create(path) if err != nil { return err } defer file.Close() return copyWithProgress(file, r, te.Progress) } func copyWithProgress(to io.Writer, from io.Reader, cb func(int64) int64) error { buf := make([]byte, 4096) for { n, err := from.Read(buf) if n != 0 { if cb != nil { cb(int64(n)) } _, err2 := to.Write(buf[:n]) if err2 != nil { return err2 } } if err != nil { if err == io.EOF { return nil } return err } } }
package main import ( "fmt" "net" "net/http" "net/http/fcgi" ) type FastCGIServer struct{} func (s FastCGIServer) ServeHTTP(w http.ResponseWriter, req *http.Request) { w.Header().Set("Content-Type", "text/html") str := fmt.Sprintf("<b>RequestURI</b>:%s<br />\n<b>User-Agent</b>:%s\n", req.URL.String(), req.UserAgent()) w.Write([]byte(str)) } func main() { s := new(FastCGIServer) l,_ := net.Listen("tcp", "127.0.0.1:9000") fcgi.Serve(l, s) }
package main import ( "fmt" "time" "github.com/docker/distribution/manifest/schema1" "github.com/docker/distribution/notifications" "gopkg.in/mgo.v2/bson" ) // ProcessEventPullOrPush returns a key->value map (bson.M) that can be // used to upsert (aka. insert or update) a statistics document about a // repository in a Mongo database. func ProcessEventPullOrPush(event *notifications.Event) (bson.M, error) { // Check that it's a pull or push event if event.Action != notifications.EventActionPush && event.Action != notifications.EventActionPull { return nil, fmt.Errorf("Wrong event.Action: %s", event.Action) } // Check that the mediatype equals: application/vnd.docker.distribution.manifest.v1+json // TODO: (kwk) The documentation says it can also be application/json // (see https://github.com/docker/distribution/blob/master/manifest/schema1/manifest.go#L15) if event.Target.MediaType != schema1.ManifestMediaType { return nil, fmt.Errorf("Wrong event.Target.MediaType: \"%s\". Expected: \"%s\"", event.Target.MediaType, schema1.ManifestMediaType) } maxs := make(bson.M) mins := make(bson.M) sets := make(bson.M) setOnInsert := make(bson.M) setOnInsert["numstars"] = 0 timeInFuture := time.Date(2099, time.January, 1, 0, 0, 0, 0, time.UTC) timeInPast := time.Date(1970, time.January, 1, 0, 0, 0, 0, time.UTC) pullIncrement := 0 pushIncrement := 0 if event.Action == notifications.EventActionPull { pullIncrement = 1 maxs["lastpulled"] = event.Timestamp mins["firstpulled"] = event.Timestamp setOnInsert["firstpushed"] = timeInFuture setOnInsert["lastpushed"] = timeInPast } if event.Action == notifications.EventActionPush { pushIncrement = 1 maxs["lastpushed"] = event.Timestamp mins["firstpushed"] = event.Timestamp setOnInsert["firstpulled"] = timeInFuture setOnInsert["lastpulled"] = timeInPast } sets["repositoryname"] = event.Target.Repository updateBson := bson.M{ "$set": sets, "$setOnInsert": setOnInsert, "$max": maxs, "$min": mins, "$addToSet": bson.M{"actors": event.Actor.Name}, "$inc": bson.M{ "numpushs": pushIncrement, "numpulls": pullIncrement, }, } return updateBson, nil }
package main import "fmt" type CPU struct{} type Memory struct{} type SolidStateDrive struct{} func (cpu CPU) freeze() { fmt.Println("Freezing processor") } func (cpu CPU) jump(position string) { fmt.Println("Jumping to:", position) } func (cpu CPU) execute() { fmt.Println("Executing") } func (memory Memory) load(position, data string) { fmt.Println("Loading from " + position + " data " + data) } func (ssd SolidStateDrive) read(lba, size string) string { return "Some data from sector " + lba + " with size " + size } type ComputerFacade struct { cpu CPU memory Memory ssd SolidStateDrive } func NewComputerFacade() ComputerFacade { computer := ComputerFacade{ CPU{}, Memory{}, SolidStateDrive{}, } return computer } func (computer ComputerFacade) start() { computer.cpu.freeze() computer.memory.load("0x00", computer.ssd.read("100", "1024")) computer.cpu.jump("0x00") computer.cpu.execute() } func main() { computer := NewComputerFacade() computer.start() // Freezing processor // Loading from 0x00 data Some data from sector 100 with size 1024 // Jumping to: 0x00 // Executing }
package queries import ( "github.com/graphql-go/graphql" "go_graphql/petstore/db" "go_graphql/petstore/types" "log" "strconv" ) //GetOwnerQuery queries and replies with single query func GetOwnerQuery() *graphql.Field { return &graphql.Field{ Type: types.OwnerType, Description: "Get single Owner", Args: graphql.FieldConfigArgument{ "id": &graphql.ArgumentConfig{ Type: graphql.String, }, }, Resolve: func(params graphql.ResolveParams) (interface{}, error) { idQuery, _ := params.Args["id"].(string) log.Println("Got request for Owner with id ", idQuery) owner := new(types.Owner) conn := db.Connect() defer db.Connect() id, _ := strconv.Atoi(idQuery) rows, err := conn.Query("SELECT id,first_name,last_name from OWNER WHERE id=$1", id) if err != nil { log.Fatal("Encountered error while fetching data", err) } for rows.Next() { err := rows.Scan(&owner.ID, &owner.FirstName, &owner.LastName) if err != nil { log.Fatal("Encountered error while looping data", err) } } return owner, nil }, } } //GetLastOwner returns last owner in our registry func GetLastOwner() *graphql.Field { return &graphql.Field{ Type: types.OwnerType, Description: "Get Single Last owner registered", Resolve: func(params graphql.ResolveParams) (interface{}, error) { conn := db.Connect() defer conn.Close() owner := new(types.Owner) rows, err := conn.Query("SELECT id,first_name,last_name from OWNER order by id DESC limit 1") if err != nil { log.Fatalln("Error while retrieving last owner", err) } for rows.Next() { err := rows.Scan(&owner.ID, &owner.FirstName, &owner.LastName) if err != nil { log.Fatal("Encountered error while looping data", err) } } log.Printf("%v", owner) return owner, nil }, } }
// nil. package main import "fmt" func main() { var ss []string fmt.Printf("ss==nil:%v\n", ss == nil) fmt.Println("len", len(ss)) fmt.Println(ss[:] == nil) }
package models // the request model for Comment Parsing type CommentParsingRequest struct { PackageName string // the package name to search for comments Tokens []string // the tokens/words to search for } // the result model for Comment Parsing type CommentParsingResult struct { PackageName string // the package name in which the matches were made BinaryOnly bool // true if the package was binary only Matches map[string][]MatchedComment // the matched comments } // result model for a single matched comment type MatchedComment struct { FileName string // the file name where the comment was found LineNumber int // the line number where the comment was found LineContent string // the content of the comment itself }
package zabbix import ( "encoding/json" "fmt" "net/http" "strings" ) var ( UserPostTemplate = `{ "jsonrpc": "2.0", "method": "user.create", "params": { "alias": "%v", "passwd": "%v", "usrgrps": [ { "usrgrpid": "%v" } ], "user_medias": [ { "mediatypeid": "1", "sendto": [ "%v" ], "active": 0, "severity": 63, "period": "1-7,00:00-24:00" } ] }, "auth": "%v", "id": %v }` UserGetTemplate = `{ "jsonrpc": "2.0", "method": "user.get", "params": { "output": "extend", "filter":{ "alias":"%v" } }, "auth": "%v", "id": %v }` ) func (api *API) UserCreate(name, password, mail, groupID string) error { payload := strings.NewReader(fmt.Sprintf(UserPostTemplate, name, password, groupID, mail, api.Session, api.ID)) req, err := http.NewRequest("POST", api.URL, payload) if err != nil { return err } req.Header.Add("content-type", "application/json") res, err := http.DefaultClient.Do(req) if err != nil { return err } defer res.Body.Close() if res.StatusCode != 200 { return fmt.Errorf("zabbix api return response code %v", res.StatusCode) } result := map[string]interface{}{} if err = json.NewDecoder(res.Body).Decode(&result); err != nil { return err } if errmsg, ok := result["error"]; ok { return fmt.Errorf("%v", errmsg) } return nil } func (api *API) UserGet(name, password, mail string) (map[string]interface{}, error) { payload := strings.NewReader(fmt.Sprintf(UserGetTemplate, name, api.Session, api.ID)) req, err := http.NewRequest("POST", api.URL, payload) if err != nil { return nil, err } req.Header.Add("content-type", "application/json") GET: res, err := http.DefaultClient.Do(req) if err != nil { return nil, err } defer res.Body.Close() data := map[string]interface{}{} if err = json.NewDecoder(res.Body).Decode(&data); err != nil { return nil, err } if len(data["result"].([]interface{})) == 0 { result, err := api.UserGroupGet("Guests") if err != nil { return nil, err } if result != nil && result["usrgrpid"] != nil { err = api.UserCreate(name, password, mail, result["usrgrpid"].(string)) if err != nil { return nil, err } goto GET } } if len(data["result"].([]interface{})) != 0 { return data["result"].([]interface{})[0].(map[string]interface{}), nil } return nil, nil }