text
stringlengths
11
4.05M
package main import ( "os" "github.com/sirupsen/logrus" dockerclient "github.com/docker/docker/client" "github.com/square/p2/pkg/hooks" "github.com/square/p2/pkg/logging" "github.com/square/p2/pkg/manifest" "github.com/square/p2/pkg/pods" "github.com/square/p2/pkg/types" "github.com/square/p2/pkg/uri" "github.com/square/p2/pkg/version" "gopkg.in/alecthomas/kingpin.v2" ) const ( fullDescription = `Setup runtime environment of an installed pod EXAMPLES $ p2-setup-runtime podManifest.yaml $ p2-setup-runtime https://artifactory.local/podManifest.yaml $ p2-setup-runtime --pod-root '/var/pods' https://artifactory.local/podManifest.yaml ` ) var ( app = kingpin.New("p2-setup-runtime", fullDescription) manifestURI = app.Arg("manifest", "a path to a pod manifest").Required().URL() requireFile = app.Flag( "require-file", "If set, the p2-exec invocation(s) written for the pod will not execute until the file exists on the system", ).Default("/dev/shm/p2-may-run").String() podRoot = app.Flag("pod-root", "Pod root directory").Default(pods.DefaultPath).String() hooksDir = app.Flag("hooks-dir", "Directory hooks run scripts are located").Default(hooks.DefaultPath).String() dockerUrl = app.Flag("docker-url", "Docker host url").Default(dockerclient.DefaultDockerHost).String() dockerVersion = app.Flag("docker-version", "Docker Version").Default("1.21").String() tlsCA = app.Flag("tls-ca-file", "File containing the x509 PEM-encoded CA ").ExistingFile() tlsCert = app.Flag("tls-cert", "File containing tls cert").ExistingFile() tlsKey = app.Flag("tls-key", "File containing tls key").ExistingFile() ) func dockerClient() (*dockerclient.Client, error) { var client *dockerclient.Client var err error if *tlsCA != "" && *tlsCert != "" && *tlsKey != "" { client, err = dockerclient.NewClientWithOpts( dockerclient.WithTLSClientConfig(*tlsCA, *tlsCert, *tlsKey), dockerclient.WithHost(*dockerUrl), dockerclient.WithVersion(*dockerVersion), ) if err != nil { return nil, err } } else { client, err = dockerclient.NewClientWithOpts( dockerclient.WithHost(*dockerUrl), dockerclient.WithVersion(*dockerVersion), ) if err != nil { return nil, err } } return client, err } func initPod(manifest manifest.Manifest) (*pods.Pod, error) { nodeName, err := os.Hostname() if err != nil { return nil, err } fetcher := uri.DefaultFetcher podReadOnlyPolicy := pods.NewReadOnlyPolicy(false, nil, nil) podFactory := pods.NewFactory(*podRoot, types.NodeName(nodeName), fetcher, *requireFile, podReadOnlyPolicy) dockerClient, err := dockerClient() if err != nil { return nil, err } podFactory.SetDockerClient(*dockerClient) pod := podFactory.NewLegacyPod(manifest.ID()) return pod, nil } func main() { app.Version(version.VERSION) kingpin.MustParse(app.Parse(os.Args[1:])) pods.Log.Logger.Formatter = &logrus.TextFormatter{ DisableTimestamp: false, FullTimestamp: true, TimestampFormat: "23:59:59.999", } logger := pods.Log // read manifest manifest, err := manifest.FromURI(*manifestURI) if err != nil { logger.WithError(err).WithField("manifest", *manifestURI).Fatalln("Unable to parse manifest file") } // list of hook names for which failure is fatal hooksRequired := []string{} // setup hooks context hookLogger := logging.DefaultLogger hookLogger.Logger.SetLevel(logrus.ErrorLevel) auditLogger := hooks.NewFileAuditLogger(&hookLogger) hookContext := hooks.NewContext(*hooksDir, *podRoot, &hookLogger, auditLogger) logger = logger.WithField("app", manifest.ID()) // initialize pod pod, err := initPod(manifest) if err != nil { logger.WithError(err).Fatalln("Failure initializing pod environment") } launchables, err := pod.Launchables(manifest) if err != nil { logger.WithError(err).Fatalln("Failure getting launchables from manifest") } if len(launchables) == 0 { logger.Fatalln("There are no launchables in manifest") } //run hooks BeforeInstall logger.Infoln("Running before_install hooks") err = hookContext.RunHookType(hooks.BeforeInstall, pod, manifest, hooksRequired) if err != nil { logger.WithError(err).Fatalln("Failure running before_install hook(s)") } // run hooks AfterInstall logger.Infoln("Running after_install hooks") err = hookContext.RunHookType(hooks.AfterInstall, pod, manifest, hooksRequired) if err != nil { logger.WithError(err).Fatalln("Failure running after_install hook(s)") } // run hooks BeforeLaunch logger.Infoln("Running before_launch hooks") err = hookContext.RunHookType(hooks.BeforeLaunch, pod, manifest, hooksRequired) if err != nil { logger.WithError(err).WithField("app", manifest.ID()).Fatalln("Failure running before_launch hook(s)") } // run all parts of pods.Launch except for pod.StartLaunchables // write current manifest logger.Infoln("Writing current manifest") oldManifestTemp, err := pod.WriteCurrentManifest(manifest) defer os.RemoveAll(oldManifestTemp) if err != nil { logger.WithError(err).WithField("app", manifest.ID()).Fatalln("Unable to write current manifest") } // run post activate logger.Infoln("Running post-activate") err = pod.PostActivate(launchables) if err != nil { logger.WithError(err).Fatalln("Failure running PostActivate for launchables") } // build startup services logger.Infoln("Running build runit services") err = pod.BuildRunitServices(launchables, manifest) if err != nil { logger.WithError(err).Fatalln("Failure building run scripts") } logger.Infoln("Success setting up runtime environment for pod: ", manifest.ID()) }
package secretbox import ( "testing" "github.com/stretchr/testify/require" ) func TestSecretKey(t *testing.T) { secretKey := New() plaintext1 := []byte("hello world") ciphertext := secretKey.Seal(plaintext1) plaintext2, err := secretKey.Open(ciphertext) require.NoError(t, err) require.Equal(t, plaintext1, plaintext2) }
// Copyright 2019 CUE Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //go:build go1.18 package cmd import ( "encoding/json" "errors" "fmt" "os" "runtime/debug" "time" "golang.org/x/mod/module" ) func runVersion(cmd *Command, args []string) error { w := cmd.OutOrStdout() // read in build info bi, ok := debug.ReadBuildInfo() if !ok { // shouldn't happen return errors.New("unknown error reading build-info") } // test-based overrides if v := os.Getenv("CUE_VERSION_TEST_CFG"); v != "" { var extra []debug.BuildSetting if err := json.Unmarshal([]byte(v), &extra); err != nil { return err } bi.Settings = append(bi.Settings, extra...) } // prefer ldflags `version` override if version == defaultVersion { // no version provided via ldflags, try buildinfo if bi.Main.Version != "" && bi.Main.Version != defaultVersion { version = bi.Main.Version } } if version == defaultVersion { // a specific version was not provided by ldflags or buildInfo // attempt to make our own var vcsTime time.Time var vcsRevision string for _, s := range bi.Settings { switch s.Key { case "vcs.time": // If the format is invalid, we'll print a zero timestamp. vcsTime, _ = time.Parse(time.RFC3339Nano, s.Value) case "vcs.revision": vcsRevision = s.Value // module.PseudoVersion recommends the revision to be a 12-byte // commit hash prefix, which is what cmd/go uses as well. if len(vcsRevision) > 12 { vcsRevision = vcsRevision[:12] } } } if vcsRevision != "" { version = module.PseudoVersion("", "", vcsTime, vcsRevision) } } fmt.Fprintf(w, "cue version %v\n\n", version) for _, s := range bi.Settings { if s.Value == "" { // skip empty build settings continue } // The padding helps keep readability by aligning: // // veryverylong.key value // short.key some-other-value // // Empirically, 16 is enough; the longest key seen is "vcs.revision". fmt.Fprintf(w, "%16s %s\n", s.Key, s.Value) } return nil }
package iban import "testing" func TestValidate(t *testing.T) { cases := map[string]bool{ "DE44 # 5001 0517 5407 3249": false, "DE44 5001 0517 5407 3249 231": false, "de44 5001 0517 5407 3249 31": true, "DE44 5001 0517 5407 3249 31": true, "GR16 0110 1250 0000 0001 2300 695": true, "GB29 NWBK 6016 1331 9268 19": true, "SA03 8000 0000 6080 1016 7519": true, "CH93 0076 2011 6238 5295 7": true, } for iban, ok := range cases { if err := Validate(iban); (err == nil) != ok { t.Errorf("expected validation of %q to be %v: %s", iban, ok, err) } } }
package wikipedia import "testing" func contains(s []string, e string) bool { for _, a := range s { if a == e { return true } } return false } func TestGetLanguages(t *testing.T) { t.Parallel() w := NewWikipedia() languages, err := w.GetLanguages() if err != nil { t.Error("Failed to get languages") return } for _, lang := range languages { if lang.code == "en" { if lang.name == "English" { return } t.Error("en is not named English") return } } t.Error("Could not find English") } func TestBaseUrlLanguage(t *testing.T) { t.Parallel() w := NewWikipedia() w.SetBaseUrl("http://wikipedia.com/{language}/test") url := w.GetBaseUrl() if url != "http://wikipedia.com/en/test" { t.Error("Got wrong url") return } } func TestBaseUrlNoLanguage(t *testing.T) { t.Parallel() w := NewWikipedia() w.SetBaseUrl("http://wikipedia.com/test") url := w.GetBaseUrl() if url != "http://wikipedia.com/test" { t.Error("Got wrong url") return } } func TestSearch(t *testing.T) { t.Parallel() w := NewWikipedia() results, err := w.Search("hello world") if err != nil { t.Error("Got error") return } if contains(results, "\"Hello, World!\" program") == false { t.Error("Expected results to contain hello world program") return } } func TestGeosearchValidation(t *testing.T) { t.Parallel() w := NewWikipedia() _, err := w.Geosearch(-2000, 0, 100) if err == nil { t.Error("Expected error") return } err2, ok := err.(*WikipediaError) if ok == false || err2.Type != ParameterError { t.Error("Expected error type to be ParameterError") return } errString := err.Error() if errString != "parameter error: invalid latitude" { t.Error("Expected error type to be ParameterError") return } } func TestGeosearch(t *testing.T) { t.Parallel() w := NewWikipedia() results, err := w.Geosearch(-34.603333, -58.381667, 10) if err != nil { t.Error("Got error") return } if contains(results, "Buenos Aires") == false { t.Error("Expected results to contain Buenos Aires") return } } func TestRandom(t *testing.T) { t.Parallel() w := NewWikipedia() title, err := w.Random() if err != nil { t.Error("Got error") return } if title == "" { t.Error("Got no title") return } } func TestRandomCount(t *testing.T) { t.Parallel() w := NewWikipedia() list, err := w.RandomCount(3) if err != nil { t.Error("Got error") return } if len(list) != 3 { t.Error("Got wrong number of titles") return } }
package sleepy import ( "github.com/stretchr/testify/require" "testing" ) func TestChannelFullBufferWorstCase(t *testing.T) { channel := NewChannel(nil) i := 0 for len(channel.queue) == 0 { i++ channel.Write(nil) require.NoError(t, channel.Update(0)) } require.EqualValues(t, channel.endpoint.config.RecvPacketBufferSize+1, i) require.EqualValues(t, channel.window.buf.latest, channel.endpoint.config.RecvPacketBufferSize) // ACK all packets except sequence number 0. for i := uint16(255); i >= 1; i-- { channel.ACK(i) } // ACK sequence number 0. require.EqualValues(t, 0, channel.oldestUnacked) require.Nil(t, channel.window.Find(uint16(channel.endpoint.config.RecvPacketBufferSize))) channel.ACK(0) require.EqualValues(t, channel.endpoint.config.RecvPacketBufferSize, channel.oldestUnacked) require.NotNil(t, channel.window.Find(uint16(channel.endpoint.config.RecvPacketBufferSize))) } func TestChannelEmptyQueue(t *testing.T) { channel := NewChannel(nil) i := 0 for len(channel.queue) == 0 { i++ channel.Write(nil) require.NoError(t, channel.Update(0)) } require.EqualValues(t, channel.endpoint.config.RecvPacketBufferSize+1, i) require.EqualValues(t, channel.window.buf.latest, channel.endpoint.config.RecvPacketBufferSize) // ACK seq 0. for i := uint16(0); i < 1; i++ { require.EqualValues(t, i, channel.oldestUnacked) channel.ACK(i) } // Queue should have emptied. require.Len(t, channel.queue, 0) require.EqualValues(t, channel.window.buf.latest, channel.endpoint.config.RecvPacketBufferSize+1) }
package sqlbuilder import ( . "github.com/smartystreets/goconvey/convey" "testing" ) func TestConstraints(t *testing.T) { Convey("Constraints SQL generation", t, func() { cache := &VarCache{} Convey("and combined", func() { c := new(constraint) c.gate = gate_and c.addChild(Equal{"foo", 10}) c.addChild(Equal{"bar", "bar"}) sql := c.GetSQL(cache) So(sql, ShouldEqual, `(foo = $1 AND bar = $2)`) So(len(cache.vars), ShouldEqual, 2) So(cache.vars[0], ShouldEqual, 10) So(cache.vars[1], ShouldEqual, "bar") }) Convey("or combined", func() { c := new(constraint) c.gate = gate_or c.addChild(Equal{"foo", 10}) c.addChild(Equal{"bar", "bar"}) sql := c.GetSQL(cache) So(sql, ShouldEqual, `(foo = $1 OR bar = $2)`) So(len(cache.vars), ShouldEqual, 2) So(cache.vars[0], ShouldEqual, 10) So(cache.vars[1], ShouldEqual, "bar") }) Convey("complex", func() { c := new(constraint) c.gate = gate_or c.children = []SQLProvider{ Equal{"foo", 10}, &constraint{ gate: gate_and, children: []SQLProvider{ Equal{"bar", "bar"}, Equal{"baz", "baz"}, }, }, } sql := c.GetSQL(cache) So(sql, ShouldEqual, `(foo = $1 OR (bar = $2 AND baz = $3))`) So(len(cache.vars), ShouldEqual, 3) So(cache.vars[0], ShouldEqual, 10) So(cache.vars[1], ShouldEqual, "bar") So(cache.vars[2], ShouldEqual, "baz") }) }) }
package commands import ( "fmt" "github.com/qubitz/lawyer/constants" ) // A Command executes a predefined procedure established before its creation. type Command interface { Execute() error } type setup interface { Parse(args []string) Command } var helpSuggestion = "use \"lawyer help\" to show usage information" // Parse creates a valid Command from args. The expected format // of args is: "<subcommand> <arguments...>". If an error occurs and a // valid command can not be constructed, a new command is created explaining // the error and suggesting the "lawyer help" command. func Parse(args []string) Command { if len(args) == 0 { return welcomeCommand{} } setup, err := getSetup(args[0]) if err != nil { return suggestHelpWith(err) } return setup.Parse(args[1:]) } func getSetup(command string) (setup, error) { switch command { case "indict": return setupForIndict(), nil case "help", "--help", "-h": return setupForHelp(), nil default: return nil, fmt.Errorf("unknown command \"%v\"", command) } } func suggestHelpWith(err error) suggestHelpCommand { return suggestHelpCommand{ error: err, } } type suggestHelpCommand struct { error } func (suggHelp suggestHelpCommand) Execute() error { fmt.Println("invalid command: " + suggHelp.error.Error()) fmt.Println(helpSuggestion) return nil } type welcomeCommand struct{} func (welcome welcomeCommand) Execute() error { fmt.Println(constants.LawyerDescription) fmt.Println("version " + constants.LawyerVersion) fmt.Println(helpSuggestion) return nil }
package types type ReqContent struct { Tag string Command string Params []string } type P2pRequest struct { ReqType string Content ReqContent } type BroadUnitEntity struct { HasPeers []string Message string } type LightNewUnitEntity struct { FromAddress string ToAddress string Amount int } type LightNewUnitRepEntity struct { Error string Unit Unit } type SyncDataEntity struct { State int StableUnits Units UnStableUnits Units } type PeerInfoEntity struct { CurrentPeerMCI int64 UnStableUnits int64 MaxLevel int64 } type NewUnitEntity struct { FromPeerId string HasPeerIds []string NewUnit Unit } type ValidMciEntity struct { MCI int64 UnitHash string }
package master import ( "github.com/stretchr/testify/assert" "net/http" "net/http/httptest" "testing" ) func TestCheckStatusCode(t *testing.T) { testServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, request *http.Request) { })) responseStatusCode := checkStatusCode(testServer.URL) assert.Equal(t, 200, responseStatusCode) responseStatusCode = checkStatusCode("") assert.Equal(t, 0, responseStatusCode) } func TestCheckStatusCodeWithoutHttp(t *testing.T) { testServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, request *http.Request) { })) responseStatusCode := checkStatusCode(testServer.URL[7:]) assert.Equal(t, 200, responseStatusCode) } func TestIfURLIsValid(t *testing.T) { testServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, request *http.Request) { })) assert.True(t, IsURLValid(testServer.URL)) } func TestIfURLIsInvalid(t *testing.T) { assert.False(t, IsURLValid("")) }
package pgsql import ( "database/sql" "database/sql/driver" "strconv" ) // Int8ArrayFromIntSlice returns a driver.Valuer that produces a PostgreSQL int8[] from the given Go []int. func Int8ArrayFromIntSlice(val []int) driver.Valuer { return int8ArrayFromIntSlice{val: val} } // Int8ArrayToIntSlice returns an sql.Scanner that converts a PostgreSQL int8[] into a Go []int and sets it to val. func Int8ArrayToIntSlice(val *[]int) sql.Scanner { return int8ArrayToIntSlice{val: val} } // Int8ArrayFromInt8Slice returns a driver.Valuer that produces a PostgreSQL int8[] from the given Go []int8. func Int8ArrayFromInt8Slice(val []int8) driver.Valuer { return int8ArrayFromInt8Slice{val: val} } // Int8ArrayToInt8Slice returns an sql.Scanner that converts a PostgreSQL int8[] into a Go []int8 and sets it to val. func Int8ArrayToInt8Slice(val *[]int8) sql.Scanner { return int8ArrayToInt8Slice{val: val} } // Int8ArrayFromInt16Slice returns a driver.Valuer that produces a PostgreSQL int8[] from the given Go []int16. func Int8ArrayFromInt16Slice(val []int16) driver.Valuer { return int8ArrayFromInt16Slice{val: val} } // Int8ArrayToInt16Slice returns an sql.Scanner that converts a PostgreSQL int8[] into a Go []int16 and sets it to val. func Int8ArrayToInt16Slice(val *[]int16) sql.Scanner { return int8ArrayToInt16Slice{val: val} } // Int8ArrayFromInt32Slice returns a driver.Valuer that produces a PostgreSQL int8[] from the given Go []int32. func Int8ArrayFromInt32Slice(val []int32) driver.Valuer { return int8ArrayFromInt32Slice{val: val} } // Int8ArrayToInt32Slice returns an sql.Scanner that converts a PostgreSQL int8[] into a Go []int32 and sets it to val. func Int8ArrayToInt32Slice(val *[]int32) sql.Scanner { return int8ArrayToInt32Slice{val: val} } // Int8ArrayFromInt64Slice returns a driver.Valuer that produces a PostgreSQL int8[] from the given Go []int64. func Int8ArrayFromInt64Slice(val []int64) driver.Valuer { return int8ArrayFromInt64Slice{val: val} } // Int8ArrayToInt64Slice returns an sql.Scanner that converts a PostgreSQL int8[] into a Go []int64 and sets it to val. func Int8ArrayToInt64Slice(val *[]int64) sql.Scanner { return int8ArrayToInt64Slice{val: val} } // Int8ArrayFromUintSlice returns a driver.Valuer that produces a PostgreSQL int8[] from the given Go []uint. func Int8ArrayFromUintSlice(val []uint) driver.Valuer { return int8ArrayFromUintSlice{val: val} } // Int8ArrayToUintSlice returns an sql.Scanner that converts a PostgreSQL int8[] into a Go []uint and sets it to val. func Int8ArrayToUintSlice(val *[]uint) sql.Scanner { return int8ArrayToUintSlice{val: val} } // Int8ArrayFromUint8Slice returns a driver.Valuer that produces a PostgreSQL int8[] from the given Go []uint8. func Int8ArrayFromUint8Slice(val []uint8) driver.Valuer { return int8ArrayFromUint8Slice{val: val} } // Int8ArrayToUint8Slice returns an sql.Scanner that converts a PostgreSQL int8[] into a Go []uint8 and sets it to val. func Int8ArrayToUint8Slice(val *[]uint8) sql.Scanner { return int8ArrayToUint8Slice{val: val} } // Int8ArrayFromUint16Slice returns a driver.Valuer that produces a PostgreSQL int8[] from the given Go []uint16. func Int8ArrayFromUint16Slice(val []uint16) driver.Valuer { return int8ArrayFromUint16Slice{val: val} } // Int8ArrayToUint16Slice returns an sql.Scanner that converts a PostgreSQL int8[] into a Go []uint16 and sets it to val. func Int8ArrayToUint16Slice(val *[]uint16) sql.Scanner { return int8ArrayToUint16Slice{val: val} } // Int8ArrayFromUint32Slice returns a driver.Valuer that produces a PostgreSQL int8[] from the given Go []uint32. func Int8ArrayFromUint32Slice(val []uint32) driver.Valuer { return int8ArrayFromUint32Slice{val: val} } // Int8ArrayToUint32Slice returns an sql.Scanner that converts a PostgreSQL int8[] into a Go []uint32 and sets it to val. func Int8ArrayToUint32Slice(val *[]uint32) sql.Scanner { return int8ArrayToUint32Slice{val: val} } // Int8ArrayFromUint64Slice returns a driver.Valuer that produces a PostgreSQL int8[] from the given Go []uint64. func Int8ArrayFromUint64Slice(val []uint64) driver.Valuer { return int8ArrayFromUint64Slice{val: val} } // Int8ArrayToUint64Slice returns an sql.Scanner that converts a PostgreSQL int8[] into a Go []uint64 and sets it to val. func Int8ArrayToUint64Slice(val *[]uint64) sql.Scanner { return int8ArrayToUint64Slice{val: val} } // Int8ArrayFromFloat32Slice returns a driver.Valuer that produces a PostgreSQL int8[] from the given Go []float32. func Int8ArrayFromFloat32Slice(val []float32) driver.Valuer { return int8ArrayFromFloat32Slice{val: val} } // Int8ArrayToFloat32Slice returns an sql.Scanner that converts a PostgreSQL int8[] into a Go []float32 and sets it to val. func Int8ArrayToFloat32Slice(val *[]float32) sql.Scanner { return int8ArrayToFloat32Slice{val: val} } // Int8ArrayFromFloat64Slice returns a driver.Valuer that produces a PostgreSQL int8[] from the given Go []float64. func Int8ArrayFromFloat64Slice(val []float64) driver.Valuer { return int8ArrayFromFloat64Slice{val: val} } // Int8ArrayToFloat64Slice returns an sql.Scanner that converts a PostgreSQL int8[] into a Go []float64 and sets it to val. func Int8ArrayToFloat64Slice(val *[]float64) sql.Scanner { return int8ArrayToFloat64Slice{val: val} } type int8ArrayFromIntSlice struct { val []int } func (v int8ArrayFromIntSlice) Value() (driver.Value, error) { if v.val == nil { return nil, nil } else if len(v.val) == 0 { return []byte{'{', '}'}, nil } out := []byte{'{'} for _, i := range v.val { out = strconv.AppendInt(out, int64(i), 10) out = append(out, ',') } out[len(out)-1] = '}' // replace last "," with "}" return out, nil } type int8ArrayToIntSlice struct { val *[]int } func (v int8ArrayToIntSlice) Scan(src interface{}) error { arr, err := srcbytes(src) if err != nil { return err } else if arr == nil { *v.val = nil return nil } elems := pgParseCommaArray(arr) ints := make([]int, len(elems)) for i := 0; i < len(elems); i++ { i64, err := strconv.ParseInt(string(elems[i]), 10, 64) if err != nil { return err } ints[i] = int(i64) } *v.val = ints return nil } type int8ArrayFromInt8Slice struct { val []int8 } func (v int8ArrayFromInt8Slice) Value() (driver.Value, error) { if v.val == nil { return nil, nil } else if len(v.val) == 0 { return []byte{'{', '}'}, nil } out := []byte{'{'} for _, i8 := range v.val { out = strconv.AppendInt(out, int64(i8), 10) out = append(out, ',') } out[len(out)-1] = '}' // replace last "," with "}" return out, nil } type int8ArrayToInt8Slice struct { val *[]int8 } func (v int8ArrayToInt8Slice) Scan(src interface{}) error { arr, err := srcbytes(src) if err != nil { return err } else if arr == nil { *v.val = nil return nil } elems := pgParseCommaArray(arr) int8s := make([]int8, len(elems)) for i := 0; i < len(elems); i++ { i64, err := strconv.ParseInt(string(elems[i]), 10, 8) if err != nil { return err } int8s[i] = int8(i64) } *v.val = int8s return nil } type int8ArrayFromInt16Slice struct { val []int16 } func (v int8ArrayFromInt16Slice) Value() (driver.Value, error) { if v.val == nil { return nil, nil } else if len(v.val) == 0 { return []byte{'{', '}'}, nil } out := []byte{'{'} for _, i16 := range v.val { out = strconv.AppendInt(out, int64(i16), 10) out = append(out, ',') } out[len(out)-1] = '}' // replace last "," with "}" return out, nil } type int8ArrayToInt16Slice struct { val *[]int16 } func (v int8ArrayToInt16Slice) Scan(src interface{}) error { arr, err := srcbytes(src) if err != nil { return err } else if arr == nil { *v.val = nil return nil } elems := pgParseCommaArray(arr) int16s := make([]int16, len(elems)) for i := 0; i < len(elems); i++ { i64, err := strconv.ParseInt(string(elems[i]), 10, 16) if err != nil { return err } int16s[i] = int16(i64) } *v.val = int16s return nil } type int8ArrayFromInt32Slice struct { val []int32 } func (v int8ArrayFromInt32Slice) Value() (driver.Value, error) { if v.val == nil { return nil, nil } else if len(v.val) == 0 { return []byte{'{', '}'}, nil } out := []byte{'{'} for _, i32 := range v.val { out = strconv.AppendInt(out, int64(i32), 10) out = append(out, ',') } out[len(out)-1] = '}' // replace last "," with "}" return out, nil } type int8ArrayToInt32Slice struct { val *[]int32 } func (v int8ArrayToInt32Slice) Scan(src interface{}) error { arr, err := srcbytes(src) if err != nil { return err } else if arr == nil { *v.val = nil return nil } elems := pgParseCommaArray(arr) int32s := make([]int32, len(elems)) for i := 0; i < len(elems); i++ { i64, err := strconv.ParseInt(string(elems[i]), 10, 32) if err != nil { return err } int32s[i] = int32(i64) } *v.val = int32s return nil } type int8ArrayFromInt64Slice struct { val []int64 } func (v int8ArrayFromInt64Slice) Value() (driver.Value, error) { if v.val == nil { return nil, nil } else if len(v.val) == 0 { return []byte{'{', '}'}, nil } out := []byte{'{'} for _, i64 := range v.val { out = strconv.AppendInt(out, i64, 10) out = append(out, ',') } out[len(out)-1] = '}' // replace last "," with "}" return out, nil } type int8ArrayToInt64Slice struct { val *[]int64 } func (v int8ArrayToInt64Slice) Scan(src interface{}) error { arr, err := srcbytes(src) if err != nil { return err } else if arr == nil { *v.val = nil return nil } elems := pgParseCommaArray(arr) int64s := make([]int64, len(elems)) for i := 0; i < len(elems); i++ { i64, err := strconv.ParseInt(string(elems[i]), 10, 64) if err != nil { return err } int64s[i] = i64 } *v.val = int64s return nil } type int8ArrayFromUintSlice struct { val []uint } func (v int8ArrayFromUintSlice) Value() (driver.Value, error) { if v.val == nil { return nil, nil } else if len(v.val) == 0 { return []byte{'{', '}'}, nil } out := []byte{'{'} for _, u := range v.val { out = strconv.AppendUint(out, uint64(u), 10) out = append(out, ',') } out[len(out)-1] = '}' // replace last "," with "}" return out, nil } type int8ArrayToUintSlice struct { val *[]uint } func (v int8ArrayToUintSlice) Scan(src interface{}) error { arr, err := srcbytes(src) if err != nil { return err } else if arr == nil { *v.val = nil return nil } elems := pgParseCommaArray(arr) uints := make([]uint, len(elems)) for i := 0; i < len(elems); i++ { u64, err := strconv.ParseUint(string(elems[i]), 10, 32) if err != nil { return err } uints[i] = uint(u64) } *v.val = uints return nil } type int8ArrayFromUint8Slice struct { val []uint8 } func (v int8ArrayFromUint8Slice) Value() (driver.Value, error) { if v.val == nil { return nil, nil } else if len(v.val) == 0 { return []byte{'{', '}'}, nil } out := []byte{'{'} for _, u := range v.val { out = strconv.AppendUint(out, uint64(u), 10) out = append(out, ',') } out[len(out)-1] = '}' // replace last "," with "}" return out, nil } type int8ArrayToUint8Slice struct { val *[]uint8 } func (v int8ArrayToUint8Slice) Scan(src interface{}) error { arr, err := srcbytes(src) if err != nil { return err } else if arr == nil { *v.val = nil return nil } elems := pgParseCommaArray(arr) uint8s := make([]uint8, len(elems)) for i := 0; i < len(elems); i++ { u64, err := strconv.ParseUint(string(elems[i]), 10, 8) if err != nil { return err } uint8s[i] = uint8(u64) } *v.val = uint8s return nil } type int8ArrayFromUint16Slice struct { val []uint16 } func (v int8ArrayFromUint16Slice) Value() (driver.Value, error) { if v.val == nil { return nil, nil } else if len(v.val) == 0 { return []byte{'{', '}'}, nil } out := []byte{'{'} for _, u := range v.val { out = strconv.AppendUint(out, uint64(u), 10) out = append(out, ',') } out[len(out)-1] = '}' // replace last "," with "}" return out, nil } type int8ArrayToUint16Slice struct { val *[]uint16 } func (v int8ArrayToUint16Slice) Scan(src interface{}) error { arr, err := srcbytes(src) if err != nil { return err } else if arr == nil { *v.val = nil return nil } elems := pgParseCommaArray(arr) uint16s := make([]uint16, len(elems)) for i := 0; i < len(elems); i++ { u64, err := strconv.ParseUint(string(elems[i]), 10, 16) if err != nil { return err } uint16s[i] = uint16(u64) } *v.val = uint16s return nil } type int8ArrayFromUint32Slice struct { val []uint32 } func (v int8ArrayFromUint32Slice) Value() (driver.Value, error) { if v.val == nil { return nil, nil } else if len(v.val) == 0 { return []byte{'{', '}'}, nil } out := []byte{'{'} for _, u := range v.val { out = strconv.AppendUint(out, uint64(u), 10) out = append(out, ',') } out[len(out)-1] = '}' // replace last "," with "}" return out, nil } type int8ArrayToUint32Slice struct { val *[]uint32 } func (v int8ArrayToUint32Slice) Scan(src interface{}) error { arr, err := srcbytes(src) if err != nil { return err } else if arr == nil { *v.val = nil return nil } elems := pgParseCommaArray(arr) uint32s := make([]uint32, len(elems)) for i := 0; i < len(elems); i++ { u64, err := strconv.ParseUint(string(elems[i]), 10, 32) if err != nil { return err } uint32s[i] = uint32(u64) } *v.val = uint32s return nil } type int8ArrayFromUint64Slice struct { val []uint64 } func (v int8ArrayFromUint64Slice) Value() (driver.Value, error) { if v.val == nil { return nil, nil } else if len(v.val) == 0 { return []byte{'{', '}'}, nil } out := []byte{'{'} for _, u := range v.val { out = strconv.AppendUint(out, u, 10) out = append(out, ',') } out[len(out)-1] = '}' // replace last "," with "}" return out, nil } type int8ArrayToUint64Slice struct { val *[]uint64 } func (v int8ArrayToUint64Slice) Scan(src interface{}) error { arr, err := srcbytes(src) if err != nil { return err } else if arr == nil { *v.val = nil return nil } elems := pgParseCommaArray(arr) uint64s := make([]uint64, len(elems)) for i := 0; i < len(elems); i++ { u64, err := strconv.ParseUint(string(elems[i]), 10, 64) if err != nil { return err } uint64s[i] = u64 } *v.val = uint64s return nil } type int8ArrayFromFloat32Slice struct { val []float32 } func (v int8ArrayFromFloat32Slice) Value() (driver.Value, error) { if v.val == nil { return nil, nil } else if len(v.val) == 0 { return []byte{'{', '}'}, nil } out := []byte{'{'} for _, f := range v.val { out = strconv.AppendInt(out, int64(f), 10) out = append(out, ',') } out[len(out)-1] = '}' // replace last "," with "}" return out, nil } type int8ArrayToFloat32Slice struct { val *[]float32 } func (v int8ArrayToFloat32Slice) Scan(src interface{}) error { arr, err := srcbytes(src) if err != nil { return err } else if arr == nil { *v.val = nil return nil } elems := pgParseCommaArray(arr) float32s := make([]float32, len(elems)) for i := 0; i < len(elems); i++ { i64, err := strconv.ParseInt(string(elems[i]), 10, 64) if err != nil { return err } float32s[i] = float32(i64) } *v.val = float32s return nil } type int8ArrayFromFloat64Slice struct { val []float64 } func (v int8ArrayFromFloat64Slice) Value() (driver.Value, error) { if v.val == nil { return nil, nil } else if len(v.val) == 0 { return []byte{'{', '}'}, nil } out := []byte{'{'} for _, f := range v.val { out = strconv.AppendInt(out, int64(f), 10) out = append(out, ',') } out[len(out)-1] = '}' // replace last "," with "}" return out, nil } type int8ArrayToFloat64Slice struct { val *[]float64 } func (v int8ArrayToFloat64Slice) Scan(src interface{}) error { arr, err := srcbytes(src) if err != nil { return err } else if arr == nil { *v.val = nil return nil } elems := pgParseCommaArray(arr) float64s := make([]float64, len(elems)) for i := 0; i < len(elems); i++ { i64, err := strconv.ParseInt(string(elems[i]), 10, 64) if err != nil { return err } float64s[i] = float64(i64) } *v.val = float64s return nil }
package queue type Queue []interface{} func NewQueue() *Queue { return &Queue{} } func (q *Queue) Enqueue(v interface{}) { *q = append(*q, v) } func (q *Queue) Equeue() (v interface{}) { if len(*q) == 0 { return nil } v = (*q)[0] *q = (*q)[1:] return } func (q *Queue) len() int { return len(*q) } func (q *Queue) empty() bool { return len(*q) == 0 }
package csender import ( "bytes" "encoding/json" "net/http" "time" "net/url" "strings" "compress/gzip" "crypto/tls" "fmt" log "github.com/sirupsen/logrus" ) func (cs *Csender) initHubHttpClient() { if cs.hubHttpClient == nil { tr := *(http.DefaultTransport.(*http.Transport)) if cs.rootCAs != nil { tr.TLSClientConfig = &tls.Config{RootCAs: cs.rootCAs} } if cs.HubProxy != "" { if !strings.HasPrefix(cs.HubProxy, "http://") { cs.HubProxy = "http://" + cs.HubProxy } u, err := url.Parse(cs.HubProxy) if err != nil { log.Errorf("Failed to parse 'hub_proxy' URL") } else { if cs.HubProxyUser != "" { u.User = url.UserPassword(cs.HubProxyUser, cs.HubProxyPassword) } tr.Proxy = func(_ *http.Request) (*url.URL, error) { return u, nil } } } else { tr.Proxy = http.ProxyFromEnvironment } cs.hubHttpClient = &http.Client{ Timeout: time.Second * 30, Transport: &tr, } } } func (cs *Csender) PostResultsToHub(result Result) error { cs.initHubHttpClient() if cs.HubURL == "" { return fmt.Errorf("Both 'hub_url' in config and 'CSENDER_HUB_URL' env variable are empty") } if _, err := url.Parse(cs.HubURL); err != nil { return fmt.Errorf("Can't parse Hub URL: %s", err.Error()) } b, err := json.Marshal(result) if err != nil { return err } var req *http.Request if cs.HubGzip { var buffer bytes.Buffer zw := gzip.NewWriter(&buffer) zw.Write(b) zw.Close() req, err = http.NewRequest("POST", cs.HubURL, &buffer) req.Header.Set("Content-Encoding", "gzip") } else { req, err = http.NewRequest("POST", cs.HubURL, bytes.NewBuffer(b)) } if err != nil { return err } req.Header.Add("User-Agent", cs.userAgent()) if cs.HubUser != "" { req.SetBasicAuth(cs.HubUser, cs.HubPassword) } resp, err := cs.hubHttpClient.Do(req) if err != nil { return err } log.Debugf("Sent to HUB.. Status %d", resp.StatusCode) defer resp.Body.Close() if resp.StatusCode < 200 || resp.StatusCode >= 300 { return fmt.Errorf("Hub responded with a bad HTTP status: %d(%s)", resp.StatusCode, resp.Status) } return nil }
// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. /* Package auth defines an opinionated wrapper around OAuth2. It hides configurability of base oauth2 library and instead makes a predefined set of choices regarding where the credentials should be stored and how OAuth2 should be used. It makes authentication flows look more uniform across tools that use infra.libs.auth and allow credentials reuse across multiple binaries. Also it knows about various environments Chrome Infra tools are running under (GCE, Chrome Infra Golo, GAE, developers' machine) and switches default authentication scheme accordingly (e.g. on GCE machine the default is to use GCE metadata server). All tools that use infra.libs.auth share same credentials by default, meaning a user needs to authenticate only once to use them all. Credentials are cached in ~/.config/chrome_infra/auth/* and reused by all processes running under the same user account. */ package auth import ( "crypto/sha1" "encoding/hex" "errors" "fmt" "io/ioutil" "net/http" "os" "os/user" "path/filepath" "sort" "sync" "golang.org/x/net/context" "google.golang.org/cloud/compute/metadata" "github.com/luci/luci-go/common/auth/internal" "github.com/luci/luci-go/common/logging" ) var ( // ErrLoginRequired is returned by Transport() in case long term credentials // are not cached and the user must go through interactive login. ErrLoginRequired = errors.New("interactive login is required") // ErrInsufficientAccess is returned by Login() or Transport() if access_token // can't be minted for given OAuth scopes. For example if GCE instance wasn't // granted access to requested scopes when it was created. ErrInsufficientAccess = internal.ErrInsufficientAccess ) // Known Google API OAuth scopes. const ( OAuthScopeEmail = "https://www.googleapis.com/auth/userinfo.email" ) // Method defines a method to use to obtain OAuth access_token. type Method string // Supported authentication methods. const ( // AutoSelectMethod can be used to allow the library to pick a method most // appropriate for current execution environment. It will search for a private // key for a service account, then (if running on GCE) will try to query GCE // metadata server, and only then pick UserCredentialsMethod that requires // interaction with a user. AutoSelectMethod Method = "" // UserCredentialsMethod is used for interactive OAuth 3-legged login flow. UserCredentialsMethod Method = "UserCredentialsMethod" // ServiceAccountMethod is used to authenticate as a service account using // a private key. ServiceAccountMethod Method = "ServiceAccountMethod" // GCEMetadataMethod is used on Compute Engine to use tokens provided by // Metadata server. See https://cloud.google.com/compute/docs/authentication GCEMetadataMethod Method = "GCEMetadataMethod" ) // LoginMode is used as enum in AuthenticatedClient function. type LoginMode string const ( // InteractiveLogin is passed to AuthenticatedClient to forcefully rerun full // login flow and cache resulting tokens. Used by 'login' CLI command. InteractiveLogin LoginMode = "InteractiveLogin" // SilentLogin is passed to AuthenticatedClient if authentication must be used // and it is NOT OK to run interactive login flow to get the tokens. The call // will fail with ErrLoginRequired error if there's no cached tokens. Should // normally be used by all CLI tools that need to use authentication. SilentLogin LoginMode = "SilentLogin" // OptionalLogin is passed to AuthenticatedClient if it is OK not to use // authentication if there are no cached credentials. Interactive login will // never be called, default unauthenticated client will be returned instead. // Should be used by CLI tools where authentication is optional. OptionalLogin LoginMode = "OptionalLogin" ) // Options are used by NewAuthenticator call. All fields are optional and have // sane default values. type Options struct { // Method defaults to AutoSelectMethod. Method Method // Scopes is a list of OAuth scopes to request, defaults to [OAuthScopeEmail]. Scopes []string // ClientID is OAuth client_id to use with UserCredentialsMethod. // Default: provided by DefaultClient(). ClientID string // ClientID is OAuth client_secret to use with UserCredentialsMethod. // Default: provided by DefaultClient(). ClientSecret string // ServiceAccountJSONPath is a path to a JSON blob with a private key to use // with ServiceAccountMethod. See the "Credentials" page under "APIs & Auth" // for your project at Cloud Console. // Default: ~/.config/chrome_infra/auth/service_account.json. ServiceAccountJSONPath string // GCEAccountName is an account name to query to fetch token for from metadata // server when GCEMetadataMethod is used. If given account wasn't granted // required set of scopes during instance creation time, Transport() call // fails with ErrInsufficientAccess. // Default: "default" account. GCEAccountName string // Context carries the underlying HTTP transport to use. If context is not // provided or doesn't contain the transport, http.DefaultTransport will be // used. Context will also be used to grab a logger if passed Logger is nil. Context context.Context // Logger is used to write log messages. If nil, extract it from the context. Logger logging.Logger } // Authenticator is a factory for http.RoundTripper objects that know how to use // cached OAuth credentials. Authenticator also knows how to run interactive // login flow, if required. type Authenticator interface { // Transport returns http.RoundTripper that adds authentication details to // each request. An interactive authentication flow (if required) must be // complete before making a transport, otherwise ErrLoginRequired is returned. // Returned transport object can be safely reused across many http.Client's. Transport() (http.RoundTripper, error) // Login perform an interaction with the user to get a long term refresh token // and cache it. Blocks for user input, can use stdin. Returns ErrNoTerminal // if interaction with a user is required, but the process is not running // under a terminal. It overwrites currently cached credentials, if any. Login() error // PurgeCredentialsCache removes cached tokens. PurgeCredentialsCache() error } // NewAuthenticator returns a new instance of Authenticator given its options. func NewAuthenticator(opts Options) Authenticator { // Add default scope, sort scopes. if len(opts.Scopes) == 0 { opts.Scopes = []string{OAuthScopeEmail} } tmp := make([]string, len(opts.Scopes)) copy(tmp, opts.Scopes) sort.Strings(tmp) opts.Scopes = tmp // Fill in blanks with default values. if opts.ClientID == "" || opts.ClientSecret == "" { opts.ClientID, opts.ClientSecret = DefaultClient() } if opts.ServiceAccountJSONPath == "" { opts.ServiceAccountJSONPath = filepath.Join(SecretsDir(), "service_account.json") } if opts.GCEAccountName == "" { opts.GCEAccountName = "default" } if opts.Context == nil { opts.Context = context.Background() } if opts.Logger == nil { opts.Logger = logging.Get(opts.Context) } // See ensureInitialized for the rest of the initialization. auth := &authenticatorImpl{opts: &opts, log: opts.Logger} auth.transport = &authTransport{ parent: auth, base: internal.TransportFromContext(opts.Context), log: opts.Logger, } return auth } // AuthenticatedClient performs login (if requested) and returns http.Client. // See documentation for 'mode' for more details. func AuthenticatedClient(mode LoginMode, auth Authenticator) (*http.Client, error) { if mode == InteractiveLogin { if err := auth.PurgeCredentialsCache(); err != nil { return nil, err } } transport, err := auth.Transport() if err == nil { return &http.Client{Transport: transport}, nil } if err != ErrLoginRequired || mode == SilentLogin { return nil, err } if mode == OptionalLogin { return http.DefaultClient, nil } if mode != InteractiveLogin { return nil, fmt.Errorf("invalid mode argument: %s", mode) } if err = auth.Login(); err != nil { return nil, err } if transport, err = auth.Transport(); err != nil { return nil, err } return &http.Client{Transport: transport}, nil } //////////////////////////////////////////////////////////////////////////////// // Authenticator implementation. type authenticatorImpl struct { // Immutable members. opts *Options transport http.RoundTripper log logging.Logger // Mutable members. lock sync.Mutex cache *tokenCache provider internal.TokenProvider err error token internal.Token } func (a *authenticatorImpl) Transport() (http.RoundTripper, error) { a.lock.Lock() defer a.lock.Unlock() err := a.ensureInitialized() if err != nil { return nil, err } // No cached token and token provider requires interaction with a user: need // to login. Only non-interactive token providers are allowed to mint tokens // on the fly, see refreshToken. if a.token == nil && a.provider.RequiresInteraction() { return nil, ErrLoginRequired } return a.transport, nil } func (a *authenticatorImpl) Login() error { a.lock.Lock() defer a.lock.Unlock() err := a.ensureInitialized() if err != nil { return err } if !a.provider.RequiresInteraction() { return nil } // Create initial token. This may require interaction with a user. a.token, err = a.provider.MintToken() if err != nil { return err } // Store the initial token in the cache. Don't abort if it fails, the token // is still usable from the memory. if err = a.cacheToken(a.token); err != nil { a.log.Warningf("auth: failed to write token to cache: %v", err) } return nil } func (a *authenticatorImpl) PurgeCredentialsCache() error { a.lock.Lock() defer a.lock.Unlock() if err := a.ensureInitialized(); err != nil { return err } if err := a.cache.clear(); err != nil { return err } a.token = nil return nil } //////////////////////////////////////////////////////////////////////////////// // Authenticator private methods. // ensureInitialized is supposed to be called under the lock. func (a *authenticatorImpl) ensureInitialized() error { if a.err != nil || a.provider != nil { return a.err } // selectDefaultMethod may do heavy calls, call it lazily here rather than in // NewAuthenticator. if a.opts.Method == AutoSelectMethod { a.opts.Method = selectDefaultMethod(a.opts) } a.log.Debugf("auth: using %s", a.opts.Method) a.provider, a.err = makeTokenProvider(a.opts) if a.err != nil { return a.err } // Setup the cache only when Method is known, cache filename depends on it. a.cache = &tokenCache{ path: filepath.Join(SecretsDir(), cacheFileName(a.opts)+".tok"), log: a.log, } // Broken token cache is not a fatal error. So just log it and forget, a new // token will be minted. var err error a.token, err = a.readTokenCache() if err != nil { a.log.Warningf("auth: failed to read token from cache: %v", err) } return nil } // readTokenCache may be called with a.lock held or not held. It works either way. func (a *authenticatorImpl) readTokenCache() (internal.Token, error) { // 'read' returns (nil, nil) if cache is empty. buf, err := a.cache.read() if err != nil || buf == nil { return nil, err } token, err := a.provider.UnmarshalToken(buf) if err != nil { return nil, err } return token, nil } // cacheToken may be called with a.lock held or not held. It works either way. func (a *authenticatorImpl) cacheToken(tok internal.Token) error { buf, err := a.provider.MarshalToken(tok) if err != nil { return err } return a.cache.write(buf) } // currentToken lock a.lock inside. It MUST NOT be called when a.lock is held. func (a *authenticatorImpl) currentToken() internal.Token { // TODO(vadimsh): Test with go test -race. The lock may be unnecessary. a.lock.Lock() defer a.lock.Unlock() return a.token } // refreshToken compares current token to 'prev' and launches token refresh // procedure if they still match. Returns a refreshed token (if a refresh // procedure happened) or the current token (i.e. if it's different from prev). // Acts as "Compare-And-Swap" where "Swap" is a token refresh procedure. func (a *authenticatorImpl) refreshToken(prev internal.Token) (internal.Token, error) { // Refresh the token under the lock. tok, cache, err := func() (internal.Token, bool, error) { a.lock.Lock() defer a.lock.Unlock() // Some other goroutine already updated the token, just return the token. if a.token != nil && !a.token.Equals(prev) { return a.token, false, nil } // Rescan the cache. Maybe some other process updated the token. cached, err := a.readTokenCache() if err == nil && cached != nil && !cached.Equals(prev) && !cached.Expired() { a.log.Debugf("auth: some other process put refreshed token in the cache") a.token = cached return a.token, false, nil } // Mint a new token or refresh the existing one. if a.token == nil { // Can't do user interaction outside of Login. if a.provider.RequiresInteraction() { return nil, false, ErrLoginRequired } a.log.Debugf("auth: minting a new token") a.token, err = a.provider.MintToken() if err != nil { a.log.Warningf("auth: failed to mint a token: %v", err) return nil, false, err } } else { a.log.Debugf("auth: refreshing the token") a.token, err = a.provider.RefreshToken(a.token) if err != nil { a.log.Warningf("auth: failed to refresh the token: %v", err) return nil, false, err } } return a.token, true, nil }() if err != nil { return nil, err } // Store the new token in the cache outside the lock, no need for callers to // wait for this. Do not die if failed, token is still usable from the memory. if cache { if err = a.cacheToken(tok); err != nil { a.log.Warningf("auth: failed to write refreshed token to the cache: %v", err) } } return tok, nil } //////////////////////////////////////////////////////////////////////////////// // authTransport implementation. // TODO(vadimsh): Support CancelRequest if underlying transport supports it. // It's tricky. http.Client uses type cast to figure out whether transport // supports request cancellation or not. So new authTransportWithCancelation // should be used when parent transport provides CancelRequest. Also // authTransport should keep a mapping between original http.Request objects // and ones with access tokens attached (to know what to pass to // parent transport CancelRequest). type authTransport struct { parent *authenticatorImpl base http.RoundTripper log logging.Logger } // RoundTrip appends authorization details to the request. func (t *authTransport) RoundTrip(req *http.Request) (resp *http.Response, err error) { tok := t.parent.currentToken() if tok == nil || tok.Expired() { tok, err = t.parent.refreshToken(tok) if err != nil { return } if tok == nil || tok.Expired() { err = fmt.Errorf("auth: failed to refresh the token") return } } clone := *req clone.Header = make(http.Header) for k, v := range req.Header { clone.Header[k] = v } for k, v := range tok.RequestHeaders() { clone.Header.Set(k, v) } return t.base.RoundTrip(&clone) } //////////////////////////////////////////////////////////////////////////////// // tokenCache implementation. type tokenCache struct { path string log logging.Logger lock sync.Mutex } func (c *tokenCache) read() (buf []byte, err error) { c.lock.Lock() defer c.lock.Unlock() c.log.Debugf("auth: reading token from %s", c.path) buf, err = ioutil.ReadFile(c.path) if err != nil && os.IsNotExist(err) { err = nil } return } func (c *tokenCache) write(buf []byte) error { c.lock.Lock() defer c.lock.Unlock() c.log.Debugf("auth: writing token to %s", c.path) err := os.MkdirAll(filepath.Dir(c.path), 0700) if err != nil { return err } // TODO(vadimsh): Make it atomic across multiple processes. return ioutil.WriteFile(c.path, buf, 0600) } func (c *tokenCache) clear() error { c.lock.Lock() defer c.lock.Unlock() err := os.Remove(c.path) if err != nil && !os.IsNotExist(err) { return err } return nil } //////////////////////////////////////////////////////////////////////////////// // Utility functions. func cacheFileName(opts *Options) string { // Construct a name of cache file from data that identifies requested // credential, to allow multiple differently configured instances of // Authenticator to coexist. sum := sha1.New() _, _ = sum.Write([]byte(opts.Method)) _, _ = sum.Write([]byte{0}) _, _ = sum.Write([]byte(opts.ClientID)) _, _ = sum.Write([]byte{0}) _, _ = sum.Write([]byte(opts.ClientSecret)) _, _ = sum.Write([]byte{0}) for _, scope := range opts.Scopes { _, _ = sum.Write([]byte(scope)) _, _ = sum.Write([]byte{0}) } _, _ = sum.Write([]byte(opts.GCEAccountName)) return hex.EncodeToString(sum.Sum(nil))[:16] } // selectDefaultMethod is mocked in tests. var selectDefaultMethod = func(opts *Options) Method { if opts.ServiceAccountJSONPath != "" { info, _ := os.Stat(opts.ServiceAccountJSONPath) if info != nil && info.Mode().IsRegular() { return ServiceAccountMethod } } if metadata.OnGCE() { return GCEMetadataMethod } return UserCredentialsMethod } // secretsDir is mocked in tests. Called by publicly visible SecretsDir(). var secretsDir = func() string { usr, err := user.Current() if err != nil { panic(err.Error()) } // TODO(vadimsh): On Windows use SHGetFolderPath with CSIDL_LOCAL_APPDATA to // locate a directory to store app files. return filepath.Join(usr.HomeDir, ".config", "chrome_infra", "auth") } // makeTokenProvider is mocked in tests. Called by ensureInitialized. var makeTokenProvider = func(opts *Options) (internal.TokenProvider, error) { switch opts.Method { case UserCredentialsMethod: return internal.NewUserAuthTokenProvider( opts.Context, opts.ClientID, opts.ClientSecret, opts.Scopes) case ServiceAccountMethod: return internal.NewServiceAccountTokenProvider( opts.Context, opts.ServiceAccountJSONPath, opts.Scopes) case GCEMetadataMethod: return internal.NewGCETokenProvider( opts.GCEAccountName, opts.Scopes) default: return nil, fmt.Errorf("unrecognized authentication method: %s", opts.Method) } } // DefaultClient returns OAuth client_id and client_secret to use for 3 legged // OAuth flow. Note that client_secret is not really a secret since it's // hardcoded into the source code (and binaries). It's totally fine, as long // as it's callback URI is configured to be 'localhost'. If someone decides to // reuse such client_secret they have to run something on user's local machine // to get the refresh_token. func DefaultClient() (clientID string, clientSecret string) { clientID = "446450136466-2hr92jrq8e6i4tnsa56b52vacp7t3936.apps.googleusercontent.com" clientSecret = "uBfbay2KCy9t4QveJ-dOqHtp" return } // SecretsDir returns an absolute path to a directory to keep secret files in. func SecretsDir() string { return secretsDir() }
package controllers import ( "./../../pkg" pkg_model "./../../pkg/models" "./../../transfer/task" "cydex" "cydex/transfer" "errors" clog "github.com/cihub/seelog" "strconv" "strings" "time" ) func fillTransferState(state *cydex.TransferState, uid string, size uint64, jd *pkg_model.JobDetail) { state.Uid = uid state.State = jd.State if size > 0 { state.Percent = int((jd.FinishedSize + jd.CurSegSize) * 100 / size) if state.Percent > 100 { state.Percent = 100 } } else { state.Percent = 100 } if !jd.StartTime.IsZero() { s := MarshalUTCTime(jd.StartTime) state.StartTime = &s } if !jd.FinishTime.IsZero() { s := MarshalUTCTime(jd.FinishTime) state.FinishTime = &s } } // 根据model里的pkg,得到消息响应 func aggregate(pkg_m *pkg_model.Pkg) (pkg_c *cydex.Pkg, err error) { if pkg_m == nil { return nil, errors.New("nil pkg model") } // clog.Trace(pkg_m.Pid) pkg_c = new(cydex.Pkg) pkg_c.Pid = pkg_m.Pid pkg_c.Title = pkg_m.Title pkg_c.Notes = pkg_m.Notes pkg_c.NumFiles = int(pkg_m.NumFiles) pkg_c.Date = MarshalUTCTime(pkg_m.CreateAt) pkg_c.EncryptionType = pkg_m.EncryptionType pkg_c.MetaData = pkg_m.MetaData if err = pkg_m.GetFiles(true); err != nil { return nil, err } // 根据pid获取下载该pkg的信息 download_jobs, err := pkg_model.GetJobsByPid(pkg_m.Pid, cydex.DOWNLOAD, nil) if err != nil { return nil, err } upload_jobs, err := pkg_model.GetJobsByPid(pkg_m.Pid, cydex.UPLOAD, nil) if err != nil { return nil, err } for _, file_m := range pkg_m.Files { file := new(cydex.File) file.Fid = file_m.Fid file.Filename = file_m.Name file.Path = file_m.Path file.Type = file_m.Type file.Chara = file_m.EigenValue file.PathAbs = file_m.PathAbs file.Mode = file_m.Mode file.SetSize(file_m.Size) // 获取该文件的关联信息 // 获取文件下载信息 for _, d_job := range download_jobs { // 使用cache中的jd值,cache里没有则使用数据库的, 通过JobMgr接口 jd := pkg.JobMgr.GetJobDetail(d_job.JobId, file.Fid) if jd == nil { return nil, errors.New("get job detail failed") } state := new(cydex.TransferState) fillTransferState(state, d_job.Uid, file_m.Size, jd) file.DownloadState = append(file.DownloadState, state) } // 获取文件上传信息 for _, u_job := range upload_jobs { // 使用cache中的jd值,cache里没有则使用数据库的, 通过JobMgr接口 jd := pkg.JobMgr.GetJobDetail(u_job.JobId, file.Fid) if jd == nil { return nil, errors.New("get job detail failed") } state := new(cydex.TransferState) fillTransferState(state, u_job.Uid, file_m.Size, jd) file.UploadState = append(file.UploadState, state) } //jzh: 每次都要从数据库里取 file_m.GetSegs() for _, seg_m := range file_m.Segs { seg := new(cydex.Seg) seg.Sid = seg_m.Sid seg.SetSize(seg_m.Size) seg.Status = seg_m.State file.Segs = append(file.Segs, seg) } // fill default if nil if file.Segs == nil { file.Segs = make([]*cydex.Seg, 0) } if file.DownloadState == nil { file.DownloadState = make([]*cydex.TransferState, 0) } if file.UploadState == nil { file.UploadState = make([]*cydex.TransferState, 0) } pkg_c.Files = append(pkg_c.Files, file) } return } // 包控制器 type PkgsController struct { BaseController } func (self *PkgsController) Get() { query := self.GetString("query") filter := self.GetString("filter") list := self.GetString("list") // sec 3.2 in api doc if list == "list" { self.getLitePkgs() return } switch query { case "all": if filter == "change" { // sec 3.1.2 in api doc self.getActive() } case "sender": // 3.1 self.getJobs(cydex.UPLOAD) case "receiver": // 3.1 self.getJobs(cydex.DOWNLOAD) case "admin": // 3.1 self.getAllJobs() } } func (self *PkgsController) getAllJobs() { // uid := self.GetString(":uid") page := new(cydex.Pagination) page.PageSize, _ = self.GetInt("page_size") page.PageNum, _ = self.GetInt("page_num") if !page.Verify() { page = nil } rsp := new(cydex.QueryPkgRsp) rsp.Error = cydex.OK defer func() { if rsp.Pkgs == nil { rsp.Pkgs = make([]*cydex.Pkg, 0) } self.Data["json"] = rsp self.ServeJSON() }() // 非admin用户无权限 if self.UserLevel != cydex.USER_LEVEL_ADMIN { rsp.Error = cydex.ErrNotAllowed return } jobs, err := pkg_model.GetJobs(cydex.UPLOAD, page) if err != nil { // error rsp.Error = cydex.ErrInnerServer return } for _, job := range jobs { if err = job.GetPkg(true); err != nil { // error rsp.Error = cydex.ErrInnerServer return } pkg_c, err := aggregate(job.Pkg) if err != nil { rsp.Error = cydex.ErrInnerServer return } rsp.Pkgs = append(rsp.Pkgs, pkg_c) } if page != nil { rsp.TotalNum = int(page.TotalNum) } } func (self *PkgsController) getJobs(typ int) { uid := self.GetString(":uid") page := new(cydex.Pagination) page.PageSize, _ = self.GetInt("page_size") page.PageNum, _ = self.GetInt("page_num") if !page.Verify() { page = nil } rsp := new(cydex.QueryPkgRsp) rsp.Error = cydex.OK defer func() { if rsp.Pkgs == nil { rsp.Pkgs = make([]*cydex.Pkg, 0) } self.Data["json"] = rsp self.ServeJSON() }() // admin返回空 if self.UserLevel == cydex.USER_LEVEL_ADMIN { return } // 按照uid和type得到和用户相关的jobs jobs, err := pkg_model.GetJobsByUid(uid, typ, page) if err != nil { // error rsp.Error = cydex.ErrInnerServer return } for _, job := range jobs { if err = job.GetPkg(true); err != nil { // error rsp.Error = cydex.ErrInnerServer return } pkg_c, err := aggregate(job.Pkg) if err != nil { rsp.Error = cydex.ErrInnerServer return } rsp.Pkgs = append(rsp.Pkgs, pkg_c) } if page != nil { rsp.TotalNum = int(page.TotalNum) } } func (self *PkgsController) getActive() { uid := self.GetString(":uid") rsp := cydex.NewQueryActivePkgRsp() clog.Debugf("query active") defer func() { self.Data["json"] = rsp self.ServeJSON() }() // jzh: 管理员不实现该接口 if self.UserLevel == cydex.USER_LEVEL_ADMIN { return } // upload { jobs, err := pkg.JobMgr.GetJobsByUid(uid, cydex.UPLOAD) if err != nil { clog.Error("get jobs failed, u[%s] t[%d]", uid, cydex.UPLOAD) rsp.Error = cydex.ErrInnerServer return } for _, job_m := range jobs { if job_m.Pkg == nil || job_m.Pkg.Files == nil { // err rsp.Error = cydex.ErrInnerServer return } pkg_u := new(cydex.PkgUpload) pkg_u.Pid = job_m.Pid pkg_u.MetaData = job_m.Pkg.MetaData pkg_u.EncryptionType = job_m.Pkg.EncryptionType download_jobs, err := pkg.JobMgr.GetJobsByPid(pkg_u.Pid, cydex.DOWNLOAD) if err != nil { clog.Error("get jobs failed, p[%s] t[%d]", pkg_u.Pid, cydex.DOWNLOAD) rsp.Error = cydex.ErrInnerServer return } for _, file_m := range job_m.Pkg.Files { file := new(cydex.FileReceiver) file.Fid = file_m.Fid file.Filename = file_m.Name for _, d_job := range download_jobs { jd := pkg.JobMgr.GetJobDetail(d_job.JobId, file.Fid) if jd != nil { state := new(cydex.TransferState) fillTransferState(state, d_job.Uid, file_m.Size, jd) file.Receivers = append(file.Receivers, state) } } pkg_u.Files = append(pkg_u.Files, file) } rsp.Uploads = append(rsp.Uploads, pkg_u) } } // download { jobs, err := pkg.JobMgr.GetJobsByUid(uid, cydex.DOWNLOAD) if err != nil { clog.Error("get jobs failed, u[%s] t[%d]", uid, cydex.DOWNLOAD) rsp.Error = cydex.ErrInnerServer return } for _, job_m := range jobs { if job_m.Pkg == nil || job_m.Pkg.Files == nil { // err rsp.Error = cydex.ErrInnerServer return } pkg_d := new(cydex.PkgDownload) pkg_d.Pid = job_m.Pid pkg_d.MetaData = job_m.Pkg.MetaData pkg_d.EncryptionType = job_m.Pkg.EncryptionType uploads_jobs, err := pkg.JobMgr.GetJobsByPid(pkg_d.Pid, cydex.UPLOAD) if err != nil || uploads_jobs == nil { clog.Error("get jobs failed, p[%s] t[%d]", pkg_d.Pid, cydex.UPLOAD) rsp.Error = cydex.ErrInnerServer return } for _, file_m := range job_m.Pkg.Files { file := new(cydex.FileSender) file.Fid = file_m.Fid file.Filename = file_m.Name for _, u_job := range uploads_jobs { // clog.Trace(file.Fid) // clog.Trace(u_job.JobId) jd := pkg.JobMgr.GetJobDetail(u_job.JobId, file.Fid) if jd != nil { state := new(cydex.TransferState) fillTransferState(state, u_job.Uid, file_m.Size, jd) file.Sender = append(file.Sender, state) } } //jzh: 每次都要从数据库里取 file_m.GetSegs() for _, seg_m := range file_m.Segs { seg := new(cydex.Seg) seg.Sid = seg_m.Sid seg.SetSize(seg_m.Size) seg.Status = seg_m.State file.Segs = append(file.Segs, seg) } pkg_d.Files = append(pkg_d.Files, file) } rsp.Downloads = append(rsp.Downloads, pkg_d) } } //delete_sender_pkg_list pids := pkg.JobMgr.GetTrackOfDelete(uid, cydex.UPLOAD, true, true) for _, pid := range pids { rsp.DelSenderPkgs = append(rsp.DelSenderPkgs, &cydex.PkgId{pid}) } //delete_receive_pkg_list pids = pkg.JobMgr.GetTrackOfDelete(uid, cydex.DOWNLOAD, true, true) for _, pid := range pids { rsp.DelReceiverPkgs = append(rsp.DelReceiverPkgs, &cydex.PkgId{pid}) } } func (self *PkgsController) parseJobFilter() *pkg_model.JobFilter { filter := new(pkg_model.JobFilter) filter.Owner = self.GetString("o") filter.Title = self.GetString("title") filter.OrderBy = self.GetString("sort") dt := self.GetString("dt") if dt != "" { strs := strings.Split(dt, "-") if len(strs) == 2 { if strs[0] != "" { v, err := strconv.ParseInt(strs[0], 10, 64) if err == nil { filter.BegTime = time.Unix(v, 0) } } if strs[1] != "" { v, err := strconv.ParseInt(strs[1], 10, 64) if err == nil { filter.EndTime = time.Unix(v, 0) } } } } return filter } func (self *PkgsController) getLitePkgs() { uid := self.GetString(":uid") query := self.GetString("query") rsp := new(cydex.QueryPkgLiteRsp) page := new(cydex.Pagination) page.PageSize, _ = self.GetInt("page_size") page.PageNum, _ = self.GetInt("page_num") if !page.Verify() { page = nil } filter := self.parseJobFilter() defer func() { if rsp.Pkgs == nil { rsp.Pkgs = make([]*cydex.PkgLite, 0) } self.Data["json"] = rsp self.ServeJSON() }() clog.Debugf("get lite pkgs query is %s", query) var pkgs []*pkg_model.Pkg var err error switch query { case "admin": if self.UserLevel != cydex.USER_LEVEL_ADMIN { rsp.Error = cydex.ErrNotAllowed return } jobs, err := pkg_model.GetJobsEx(cydex.UPLOAD, page, filter) if err != nil { clog.Error(err) rsp.Error = cydex.ErrInnerServer return } for _, j := range jobs { if j.Pkg == nil { j.GetPkg(false) } pkgs = append(pkgs, j.Pkg) } case "sender": jobs, err := pkg_model.GetJobsByUid(uid, cydex.UPLOAD, page) if err != nil { clog.Error(err) rsp.Error = cydex.ErrInnerServer return } for _, j := range jobs { if j.Pkg == nil { j.GetPkg(false) } pkgs = append(pkgs, j.Pkg) } case "receiver": jobs, err := pkg_model.GetJobsByUid(uid, cydex.DOWNLOAD, page) if err != nil { clog.Error(err) rsp.Error = cydex.ErrInnerServer return } for _, j := range jobs { if j.Pkg == nil { j.GetPkg(false) } pkgs = append(pkgs, j.Pkg) } default: clog.Warnf("Invalid query:%s", query) rsp.Error = cydex.ErrInvalidParam return } if err != nil { rsp.Error = cydex.ErrInnerServer return } for _, p := range pkgs { pkg_lite := &cydex.PkgLite{ Pid: p.Pid, Title: p.Title, Date: MarshalUTCTime(p.CreateAt), Notes: p.Notes, NumFiles: int(p.NumFiles), Size: int64(p.Size), Sender: make([]*cydex.UserLite, 0), Receiver: make([]*cydex.UserLite, 0), } uj, _ := pkg_model.GetJobsByPid(p.Pid, cydex.UPLOAD, nil) for _, j := range uj { pkg_lite.Sender = append(pkg_lite.Sender, &cydex.UserLite{Uid: j.Uid}) } dj, _ := pkg_model.GetJobsByPid(p.Pid, cydex.DOWNLOAD, nil) for _, j := range dj { pkg_lite.Receiver = append(pkg_lite.Receiver, &cydex.UserLite{Uid: j.Uid}) } rsp.Pkgs = append(rsp.Pkgs, pkg_lite) } if page != nil { rsp.TotalNum = int(page.TotalNum) } } func (self *PkgsController) Post() { rsp := new(cydex.CreatePkgRsp) req := new(cydex.CreatePkgReq) defer func() { self.Data["json"] = rsp self.ServeJSON() }() if self.UserLevel == cydex.USER_LEVEL_ADMIN { clog.Error("admin not allowed to create pkg") rsp.Error = cydex.ErrNotAllowed return } // 获取拆包器 unpacker := pkg.GetUnpacker() if unpacker == nil { rsp.Error = cydex.ErrInnerServer return } // 获取请求 if err := self.FetchJsonBody(req); err != nil { rsp.Error = cydex.ErrInvalidParam return } for _, f := range req.Files { var err error f.Size, err = strconv.ParseUint(f.SizeStr, 10, 64) if err != nil { rsp.Error = cydex.ErrInvalidParam return } } self.createPkg(req, rsp) } // 批量删除包裹 func (self *PkgsController) Delete() { req := new(cydex.DelPkgsReq) rsp := new(cydex.DelPkgsRsp) defer func() { self.Data["json"] = rsp self.ServeJSON() }() uid := self.GetString(":uid") if uid == "" { rsp.Error = cydex.ErrInvalidParam return } if err := self.FetchJsonBody(req); err != nil { rsp.Error = cydex.ErrInvalidParam return } if len(req.PkgList) == 0 { rsp.Error = cydex.ErrInvalidParam return } pid_list := req.PkgList jobs := make([]*pkg_model.Job, 0, len(pid_list)) // 普通用户 if self.UserLevel != cydex.USER_LEVEL_ADMIN { for _, pid := range pid_list { hashid := pkg.HashJob(uid, pid, cydex.UPLOAD) job, _ := pkg_model.GetJob(hashid, true) if job != nil { jobs = append(jobs, job) } } } else { // 管理员 for _, pid := range pid_list { j, _ := pkg_model.GetJobsByPid(pid, cydex.UPLOAD, nil) if j != nil { j[0].GetPkg(true) jobs = append(jobs, j[0]) } } } // 判断是否在传输, 取出不传输的jobs ret, err := isJobsTransferring(jobs) if err != nil { rsp.Error = cydex.ErrInnerServer return } var avail_jobs []*pkg_model.Job for i, b := range ret { if !b { avail_jobs = append(avail_jobs, jobs[i]) } } rsp.NumDelPkgs = len(avail_jobs) for _, job_m := range avail_jobs { deleteJob(job_m) } go func() { for _, job := range avail_jobs { job.GetPkg(true) freePkgSpace(job) } }() } // 创建包裹 func (self *PkgsController) createPkg(req *cydex.CreatePkgReq, rsp *cydex.CreatePkgRsp) { if !req.Verify() { clog.Error("create pkg request is not verified!") rsp.Error = cydex.ErrInvalidParam return } var ( err error uid, fid, pid string ) uid = self.GetString(":uid") if uid == "" { rsp.Error = cydex.ErrInvalidParam return } session := pkg_model.DB().NewSession() session.Begin() defer func() { if err != nil { session.Rollback() } session.Close() }() // 分片与否确定file flag file_flag := 0 if !pkg.IsUsingFileSlice() { file_flag = file_flag | cydex.FILE_FLAG_NO_SLICE } unpacker := pkg.GetUnpacker() if unpacker == nil { rsp.Error = cydex.ErrInnerServer return } unpacker.Enter() defer unpacker.Leave() // pkg_o := new(cydex.Pkg) pid = unpacker.GeneratePid(uid, req.Title, req.Notes) size := uint64(0) for _, f := range req.Files { size += f.Size } // 创建pkg数据库记录 pkg_m := &pkg_model.Pkg{ Pid: pid, Title: req.Title, Notes: req.Notes, NumFiles: uint64(len(req.Files)), Size: size, EncryptionType: req.EncryptionType, MetaData: req.MetaData, } if _, err = session.Insert(pkg_m); err != nil { clog.Error(err) rsp.Error = cydex.ErrInnerServer return } for i, f := range req.Files { if fid, err = unpacker.GenerateFid(pid, i, f); err != nil { rsp.Error = cydex.ErrInnerServer return } segs, err := unpacker.GenerateSegs(fid, f) if err != nil { rsp.Error = cydex.ErrInnerServer return } file_m := &pkg_model.File{ Fid: fid, Pid: pid, Name: f.Filename, Path: f.Path, Size: f.Size, Mode: f.Mode, Type: f.Type, PathAbs: f.PathAbs, EigenValue: f.Chara, NumSegs: len(segs), Flag: file_flag, } if _, err = session.Insert(file_m); err != nil { rsp.Error = cydex.ErrInnerServer return } for _, s := range segs { seg_m := &pkg_model.Seg{ Sid: s.Sid, Fid: fid, Size: s.Size, } if _, err = session.Insert(seg_m); err != nil { rsp.Error = cydex.ErrInnerServer return } } } session.Commit() // Dispatch jobs pkg.JobMgr.CreateJob(uid, pid, cydex.UPLOAD) if req.Receivers != nil { for _, r := range req.Receivers { pkg.JobMgr.CreateJob(r.Uid, pid, cydex.DOWNLOAD) } } rsp.Pkg, err = aggregate(pkg_m) if err != nil { rsp.Error = cydex.ErrInnerServer return } } // 单包控制器 type PkgController struct { BaseController } func (self *PkgController) Get() { rsp := new(cydex.QuerySinglePkgRsp) defer func() { self.Data["json"] = rsp self.ServeJSON() }() uid := self.GetString(":uid") pid := self.GetString(":pid") if self.UserLevel != cydex.USER_LEVEL_ADMIN { found := false types := []int{cydex.UPLOAD, cydex.DOWNLOAD} for _, t := range types { hashid := pkg.HashJob(uid, pid, t) job, err := pkg_model.GetJob(hashid, true) if err == nil && job != nil { found = true rsp.Pkg, _ = aggregate(job.Pkg) break } } if !found { rsp.Error = cydex.ErrNotAllowed } } else { // 管理员用户 clog.Trace("admin get pkg") jobs, _ := pkg_model.GetJobsByPid(pid, cydex.UPLOAD, nil) if len(jobs) > 0 { job := jobs[0] job.GetPkg(true) rsp.Pkg, _ = aggregate(job.Pkg) } else { rsp.Error = cydex.ErrPackageNotExisted } } } // 3.7.2 func (self *PkgController) Put() { uid := self.GetString(":uid") pid := self.GetString(":pid") req := new(cydex.ModifyPkgReq) rsp := new(cydex.ModifyPkgRsp) defer func() { self.Data["json"] = rsp self.ServeJSON() }() var err error // 获取请求 if err = self.FetchJsonBody(req); err != nil { rsp.Error = cydex.ErrInvalidParam return } var job_m *pkg_model.Job if self.UserLevel != cydex.USER_LEVEL_ADMIN { hashid := pkg.HashJob(uid, pid, cydex.UPLOAD) job_m, err = pkg_model.GetJob(hashid, false) } else { // admin clog.Trace("admin put pkg") jobs, _ := pkg_model.GetJobsByPid(pid, cydex.UPLOAD, nil) if len(jobs) > 0 { job_m = jobs[0] job_m.GetPkg(true) } } if err != nil { clog.Error(err) rsp.Error = cydex.ErrInvalidParam return } if job_m == nil { rsp.Error = cydex.ErrPackageNotExisted return } clog.Tracef("%+v", job_m) job_m.GetPkg(true) // add for _, uid := range req.AddList { if err := pkg.JobMgr.CreateJob(uid, pid, cydex.DOWNLOAD); err != nil { clog.Error(err) } } // delete for _, uid := range req.RemoveList { // stop transferring tasks clog.Trace("remove:", uid, pid) jobid := pkg.HashJob(uid, pid, cydex.DOWNLOAD) task.TaskMgr.StopTasks(jobid) // delete resource in cache and db if err := pkg.JobMgr.DeleteJob(uid, pid, cydex.DOWNLOAD); err != nil { clog.Error(err) continue } } rsp.Pkg, _ = aggregate(job_m.Pkg) } // 删除包裹, 释放空间 func (self *PkgController) Delete() { uid := self.GetString(":uid") pid := self.GetString(":pid") rsp := new(cydex.BaseRsp) defer func() { self.Data["json"] = rsp self.ServeJSON() }() var job_m *pkg_model.Job // 判断是否有此包 if self.UserLevel != cydex.USER_LEVEL_ADMIN { hashid := pkg.HashJob(uid, pid, cydex.UPLOAD) clog.Trace(hashid) job_m, _ = pkg_model.GetJob(hashid, true) } else { // admin clog.Trace("admin delete pkg") jobs, _ := pkg_model.GetJobsByPid(pid, cydex.UPLOAD, nil) if len(jobs) > 0 { job_m = jobs[0] job_m.GetPkg(true) } } if job_m == nil || job_m.Pkg == nil { rsp.Error = cydex.ErrPackageNotExisted return } // 是否在传输 // ret, err := isJobTransferring(job_m) // if err != nil { // rsp.Error = cydex.ErrInnerServer // return // } // if ret { // rsp.Error = cydex.ErrActivePackage // return // } // 停止传输任务 task.TaskMgr.StopTasks(job_m.JobId) deleteJob(job_m) go freePkgSpace(job_m) } // 删除上传任务 func deleteJob(job *pkg_model.Job) { if job == nil { return } //上传Job软删除 if job.Type == cydex.UPLOAD { job.SoftDelete(pkg_model.SOFT_DELETE_TAG) } // 下载Job真删除 download_jobs, _ := pkg_model.GetJobsByPid(job.Pid, cydex.DOWNLOAD, nil) for _, j := range download_jobs { // delete resource in cache and db if err := pkg.JobMgr.DeleteJob(j.Uid, j.Pid, cydex.DOWNLOAD); err != nil { clog.Error(err) continue } } // 删除cache, 因为该pkg可能没有downloader pkg.JobMgr.DelTrack(job.Uid, job.Pid, job.Type, true) } func freePkgSpace(job *pkg_model.Job) { // 删除文件, 释放空间 if job == nil { return } job.Pkg.GetFiles(true) pid := job.Pid c := make(chan int) const timeout = 5 * time.Second for _, file := range job.Pkg.Files { // async job // 注意闭包参数file, 在循环里capture file := file go func() { defer func() { c <- 1 }() if file.Size == 0 { return } detail := getFileDetail(file) task_req := buildTaskDownloadReq(job.Uid, pid, file.Fid, nil, 0) clog.Tracef("%+v", task_req) node, err := task.TaskMgr.Scheduler().DispatchDownload(task_req) if node != nil { // 发送协议 msg := transfer.NewReqMessage("", "removefile", "", 0) msg.Req.RemoveFile = &transfer.RemoveFileReq{ RemoveId: "", Uid: job.Uid, Pid: pid, Fid: file.Fid, FileStorage: task_req.DownloadTaskReq.FileStorage, FileDetail: detail, } clog.Tracef("%+v", msg.Req.RemoveFile) if _, err = node.SendRequestSync(msg, timeout); err != nil { return } } }() } // wait delete job over for i := 0; i < len(job.Pkg.Files); i++ { <-c } job.SoftDelete(pkg_model.SOFT_DELETE_FILES_REMOVED) } // 单文件控制器 type FileController struct { BaseController } func (self *FileController) Get() { uid := self.GetString(":uid") pid := self.GetString(":pid") fid := self.GetString(":fid") rsp := new(cydex.QuerySingleFileRsp) defer func() { self.Data["json"] = rsp self.ServeJSON() }() file_m, err := pkg_model.GetFile(fid) if err != nil || file_m == nil || file_m.Pid != pid { rsp.Error = cydex.ErrPackageNotExisted return } var job *pkg_model.Job // 管理员 if self.UserLevel == cydex.USER_LEVEL_ADMIN { clog.Trace("admin get file") jobs, _ := pkg_model.GetJobsByPid(pid, cydex.UPLOAD, nil) if len(jobs) > 0 { job = jobs[0] job.GetPkg(true) } } else { // 普通用户 types := [2]int{cydex.DOWNLOAD, cydex.UPLOAD} for _, typ := range types { hashid := pkg.HashJob(uid, pid, typ) job, _ = pkg_model.GetJob(hashid, true) if job != nil { break } } } if job == nil { rsp.Error = cydex.ErrPackageNotExisted return } file := new(cydex.File) file.Fid = file_m.Fid file.Filename = file_m.Name file.SetSize(file_m.Size) file.Path = file_m.Path file.Type = file_m.Type file.Chara = file_m.EigenValue file.PathAbs = file_m.PathAbs file_m.GetSegs() for _, seg_m := range file_m.Segs { seg := new(cydex.Seg) seg.Sid = seg_m.Sid seg.SetSize(seg_m.Size) seg.Status = seg_m.State file.Segs = append(file.Segs, seg) } uploads_jobs, err := pkg_model.GetJobsByPid(pid, cydex.UPLOAD, nil) if err != nil { rsp.Error = cydex.ErrInnerServer return } for _, u_job := range uploads_jobs { jd := pkg.JobMgr.GetJobDetail(u_job.JobId, fid) if jd != nil { state := new(cydex.TransferState) fillTransferState(state, u_job.Uid, file_m.Size, jd) file.UploadState = append(file.UploadState, state) } } download_jobs, err := pkg_model.GetJobsByPid(pid, cydex.DOWNLOAD, nil) if err != nil { rsp.Error = cydex.ErrInnerServer return } for _, d_job := range download_jobs { jd := pkg.JobMgr.GetJobDetail(d_job.JobId, fid) if jd != nil { state := new(cydex.TransferState) fillTransferState(state, d_job.Uid, file_m.Size, jd) file.DownloadState = append(file.DownloadState, state) } } // fill default if nil if file.Segs == nil { file.Segs = make([]*cydex.Seg, 0) } if file.DownloadState == nil { file.DownloadState = make([]*cydex.TransferState, 0) } if file.UploadState == nil { file.UploadState = make([]*cydex.TransferState, 0) } rsp.File = file return } // 是否在传输 // func isJobTransferring(job *pkg_model.Job) (bool, error) { // tasks, err := task.LoadTasksByPidFromCache(job.Pid) // if err != nil { // return false, err // } // if len(tasks) > 0 { // return true, nil // } // return false, nil // } func isJobsTransferring(jobs []*pkg_model.Job) ([]bool, error) { tasks, err := task.LoadTasksFromCache(nil) if err != nil { return nil, err } var ret []bool var found bool for _, job := range jobs { found = false for _, t := range tasks { if job.Pid == t.Pid { found = true break } } ret = append(ret, found) } return ret, nil }
package main import ( "errors" "fmt" "os" "os/exec" "runtime" "strings" "time" "github.com/AlecAivazis/survey/v2" "github.com/AlecAivazis/survey/v2/core" "github.com/GoAdminGroup/go-admin/modules/db" "github.com/GoAdminGroup/go-admin/plugins/admin/modules" "github.com/GoAdminGroup/go-admin/plugins/admin/modules/tools" "github.com/mgutz/ansi" "github.com/schollz/progressbar" "gopkg.in/ini.v1" ) var systemGoAdminTables = []string{ "goadmin_menu", "goadmin_operation_log", "goadmin_permissions", "goadmin_role_menu", "goadmin_site", "goadmin_roles", "goadmin_session", "goadmin_users", "goadmin_role_permissions", "goadmin_role_users", "goadmin_user_permissions", } func generating(cfgFile, connName string) { clear(runtime.GOOS) cliInfo() var ( info = new(dbInfo) connection, packageName, outputPath, generatePermissionFlag string chooseTables = make([]string, 0) cfgModel *ini.File err error ) if cfgFile != "" { cfgModel, err = ini.Load(cfgFile) if err != nil { panic(errors.New("wrong config file path")) } languageCfg, err := cfgModel.GetSection("language") if err == nil { setDefaultLangSet(languageCfg.Key("language").Value()) } modelCfgModel, exist2 := cfgModel.GetSection("model") if exist2 == nil { connection = modelCfgModel.Key("connection").Value() packageName = modelCfgModel.Key("package").Value() outputPath = modelCfgModel.Key("output").Value() generatePermissionFlag = modelCfgModel.Key("generate_permission_flag").Value() } if connection == "" { connection = connName } info = getDBInfoFromINIConfig(cfgModel, connection) } // step 1. get connection conn := askForDBConnection(info) // step 2. show tables if len(chooseTables) == 0 { tables, err := db.WithDriver(conn).Table(info.Database).ShowTables() if err != nil { panic(err) } tables = filterTables(tables) if len(tables) == 0 { panic(newError(`no tables, you should build a table of your own business first.`)) } tables = append([]string{"[" + getWord("select all") + "]"}, tables...) survey.SelectQuestionTemplate = strings.ReplaceAll(survey.SelectQuestionTemplate, "<enter> to select", "<space> to select") chooseTables = selects(tables) if len(chooseTables) == 0 { panic(newError("no table is selected")) } if modules.InArray(chooseTables, "["+getWord("select all")+"]") { chooseTables = tables[1:] } } if packageName == "" { packageName = promptWithDefault("set package name", "main") } if connection == "" { connection = promptWithDefault("set connection name", "default") } if outputPath == "" { outputPath = promptWithDefault("set file output path", "./") } if generatePermissionFlag == "" { generatePermissionFlag = singleSelect(getWord("generate permission records for tables"), []string{getWord("yes"), getWord("no")}, getWord("yes")) } if generatePermissionFlag == getWord("yes") { if connection == "default" { for _, table := range chooseTables { insertPermissionOfTable(conn, table) } } else { var defInfo = new(dbInfo) if cfgFile != "" { defInfo = getDBInfoFromINIConfig(cfgModel, "") } defConn := askForDBConnection(defInfo) for _, table := range chooseTables { insertPermissionOfTable(defConn, table) } } } fmt.Println() fmt.Println(ansi.Color("✔", "green") + " " + getWord("generating: ")) fmt.Println() bar := progressbar.New(len(chooseTables)) for i := 0; i < len(chooseTables); i++ { _ = bar.Add(1) time.Sleep(10 * time.Millisecond) checkError(tools.Generate(tools.NewParam(tools.Config{ Connection: connection, Driver: info.DriverName, Package: packageName, HideFilterArea: true, Table: chooseTables[i], Schema: info.Schema, Output: outputPath, Conn: conn, }))) } if err := tools.GenerateTables(outputPath, packageName, chooseTables, true); err != nil { panic(err) } fmt.Println() fmt.Println() fmt.Println(ansi.Color(getWord("Generate data table models success~~🍺🍺"), "green")) fmt.Println() if defaultLang == "cn" { fmt.Println(getWord("see the docs: ") + ansi.Color("http://doc.go-admin.cn", "blue")) } else { fmt.Println(getWord("see the docs: ") + ansi.Color("https://book.go-admin.com", "blue")) } fmt.Println(getWord("visit forum: ") + ansi.Color("http://discuss.go-admin.com", "blue")) fmt.Println() fmt.Println() } func clear(osName string) { if osName == "linux" || osName == "darwin" { cmd := exec.Command("clear") //Linux example, its tested cmd.Stdout = os.Stdout _ = cmd.Run() } if osName == "windows" { cmd := exec.Command("cmd", "/c", "cls") //Windows example, its tested cmd.Stdout = os.Stdout _ = cmd.Run() } } func filterTables(models []string) []string { tables := make([]string, 0) for i := 0; i < len(models); i++ { // skip goadmin system tables if isSystemTable(models[i]) { continue } tables = append(tables, models[i]) } return tables } func isSystemTable(name string) bool { for _, v := range systemGoAdminTables { if name == v { return true } } return false } func prompt(label string) string { var qs = []*survey.Question{ { Name: label, Prompt: &survey.Input{Message: getWord(label)}, Validate: survey.Required, }, } var result = make(map[string]interface{}) err := survey.Ask(qs, &result) checkError(err) return result[label].(string) } func promptWithDefault(label string, defaultValue string) string { var qs = []*survey.Question{ { Name: label, Prompt: &survey.Input{Message: getWord(label), Default: defaultValue}, Validate: survey.Required, }, } var result = make(map[string]interface{}) err := survey.Ask(qs, &result) checkError(err) return result[label].(string) } func promptPassword() string { password := "" prompt := &survey.Password{ Message: getWord("sql password"), } err := survey.AskOne(prompt, &password, nil) checkError(err) return password } func selects(tables []string) []string { chooseTables := make([]string, 0) prompt := &survey.MultiSelect{ Message: getWord("choose table to generate"), Options: tables, PageSize: 10, } err := survey.AskOne(prompt, &chooseTables, nil) checkError(err) return chooseTables } func singleSelect(msg string, options []string, def string) string { var qs = []*survey.Question{ { Name: "question", Prompt: &survey.Select{ Message: msg, Options: options, Default: def, }, }, } var result = make(map[string]interface{}) err := survey.Ask(qs, &result) checkError(err) return result["question"].(core.OptionAnswer).Value }
package main import "github.com/gin-gonic/gin" func main() { server := gin.Default() server.GET("/test", func(ctx *gin.Context) { ctx.JSON(200, gin.H{ "message": "heloo kalam", }) }) server.Run(":8080") }
package main import ( "encoding/json" "io/ioutil" "os" "path/filepath" ) type Conf struct { ClientSecret string `json:"clientSecret"` CalendarId string `json:"calendarId"` DebugCalendarId string `json:"debugCalendarId"` } func (conf *Conf) Load() (err error) { row, err := ioutil.ReadFile(filepath.Join(os.Getenv("SACHI_PRIVATE_PATH"), "conf.json")) if err != nil { return } err = json.Unmarshal(row, &conf) return }
// 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 set import ( "fmt" "strconv" "testing" ) func BenchmarkFloat64SetMemoryUsage(b *testing.B) { b.ReportAllocs() type testCase struct { rowNum int } cases := []testCase{ {rowNum: 0}, {rowNum: 100}, {rowNum: 10000}, {rowNum: 1000000}, {rowNum: 851968}, // 6.5 * (1 << 17) {rowNum: 851969}, // 6.5 * (1 << 17) + 1 {rowNum: 425984}, // 6.5 * (1 << 16), {rowNum: 425985}, // 6.5 * (1 << 16) + 1 } for _, c := range cases { b.Run(fmt.Sprintf("MapRows %v", c.rowNum), func(b *testing.B) { b.ReportAllocs() for i := 0; i < b.N; i++ { float64Set, _ := NewFloat64SetWithMemoryUsage() for num := 0; num < c.rowNum; num++ { float64Set.Insert(float64(num)) } } }) } } func BenchmarkInt64SetMemoryUsage(b *testing.B) { b.ReportAllocs() type testCase struct { rowNum int } cases := []testCase{ {rowNum: 0}, {rowNum: 100}, {rowNum: 10000}, {rowNum: 1000000}, {rowNum: 851968}, // 6.5 * (1 << 17) {rowNum: 851969}, // 6.5 * (1 << 17) + 1 {rowNum: 425984}, // 6.5 * (1 << 16) {rowNum: 425985}, // 6.5 * (1 << 16) + 1 } for _, c := range cases { b.Run(fmt.Sprintf("MapRows %v", c.rowNum), func(b *testing.B) { b.ReportAllocs() for i := 0; i < b.N; i++ { int64Set, _ := NewInt64SetWithMemoryUsage() for num := 0; num < c.rowNum; num++ { int64Set.Insert(int64(num)) } } }) } } func BenchmarkStringSetMemoryUsage(b *testing.B) { b.ReportAllocs() type testCase struct { rowNum int } cases := []testCase{ {rowNum: 0}, {rowNum: 100}, {rowNum: 10000}, {rowNum: 1000000}, {rowNum: 851968}, // 6.5 * (1 << 17) {rowNum: 851969}, // 6.5 * (1 << 17) + 1 {rowNum: 425984}, // 6.5 * (1 << 16) {rowNum: 425985}, // 6.5 * (1 << 16) + 1 } for _, c := range cases { b.Run(fmt.Sprintf("MapRows %v", c.rowNum), func(b *testing.B) { b.ReportAllocs() for i := 0; i < b.N; i++ { stringSet, _ := NewStringSetWithMemoryUsage() for num := 0; num < c.rowNum; num++ { stringSet.Insert(strconv.Itoa(num)) } } }) } }
package history import ( "github.com/stellar/go/xdr" "github.com/stretchr/testify/mock" ) // MockQHistoryClaimableBalances is a mock implementation of the QClaimableBalances interface type MockQHistoryClaimableBalances struct { mock.Mock } func (m *MockQHistoryClaimableBalances) CreateHistoryClaimableBalances(ids []xdr.ClaimableBalanceId, maxBatchSize int) (map[string]int64, error) { a := m.Called(ids, maxBatchSize) return a.Get(0).(map[string]int64), a.Error(1) } func (m *MockQHistoryClaimableBalances) NewTransactionClaimableBalanceBatchInsertBuilder(maxBatchSize int) TransactionClaimableBalanceBatchInsertBuilder { a := m.Called(maxBatchSize) return a.Get(0).(TransactionClaimableBalanceBatchInsertBuilder) } // MockTransactionClaimableBalanceBatchInsertBuilder is a mock implementation of the // TransactionClaimableBalanceBatchInsertBuilder interface type MockTransactionClaimableBalanceBatchInsertBuilder struct { mock.Mock } func (m *MockTransactionClaimableBalanceBatchInsertBuilder) Add(transactionID, accountID int64) error { a := m.Called(transactionID, accountID) return a.Error(0) } func (m *MockTransactionClaimableBalanceBatchInsertBuilder) Exec() error { a := m.Called() return a.Error(0) } // NewOperationClaimableBalanceBatchInsertBuilder mock func (m *MockQHistoryClaimableBalances) NewOperationClaimableBalanceBatchInsertBuilder(maxBatchSize int) OperationClaimableBalanceBatchInsertBuilder { a := m.Called(maxBatchSize) return a.Get(0).(OperationClaimableBalanceBatchInsertBuilder) } // MockOperationClaimableBalanceBatchInsertBuilder is a mock implementation of the // OperationClaimableBalanceBatchInsertBuilder interface type MockOperationClaimableBalanceBatchInsertBuilder struct { mock.Mock } func (m *MockOperationClaimableBalanceBatchInsertBuilder) Add(transactionID, accountID int64) error { a := m.Called(transactionID, accountID) return a.Error(0) } func (m *MockOperationClaimableBalanceBatchInsertBuilder) Exec() error { a := m.Called() return a.Error(0) }
package main import ( _ "gowechatsubscribe/routers" "fmt" "github.com/astaxie/beego" "github.com/astaxie/beego/context" "github.com/silenceper/wechat" "github.com/silenceper/wechat/message" "gowechatsubscribe/dblite" "github.com/going/toolkit/log" "gowechatsubscribe/controllers" "gowechatsubscribe/models" ) func init() { models.RegisterDB() } func main() { beego.Any("/", hello) beego.Router("/mis", &controllers.HomeController{}) beego.Router("/mis/login", &controllers.LoginController{}) beego.Router("/mis/poetry/?:id", &controllers.PoetryController{}) beego.Router("/mis/tag", &controllers.TagController{}) beego.Run() } var accessToken string func hello(ctx *context.Context) { //配置微信参数 config := &wechat.Config{ AppID: beego.AppConfig.String("AppID"), AppSecret: beego.AppConfig.String("AppSecret"), Token: beego.AppConfig.String("Token"), EncodingAESKey: beego.AppConfig.String("EncodingAESKey"), } wc := wechat.NewWechat(config) // 传入request和responseWriter server := wc.GetServer(ctx.Request, ctx.ResponseWriter) //设置接收消息的处理方法 server.SetMessageHandler(func(msg message.MixMessage) *message.Reply { //openId := server.GetOpenID() switch msg.MsgType { // 文本消息 case message.MsgTypeText: //回复消息:演示回复用户发送的消息 text := message.NewText(msg.Content) dbManager := dblite.NewDBManager() var result string fmt.Println("input:", text.Content) if (len(text.Content) < 2) { result = "请输入两个字以上哦!" } else { result = dbManager.SelectPoetry(text.Content) } reply := message.NewText(result) return &message.Reply{message.MsgTypeText, reply} case message.MsgTypeEvent: aReply := message.NewText("Hi 主人," + "谢谢您的关注!我是您的国学小助手。尝试回复表情、诗句或者词牌名,如:\"[难过]\"或者\"静夜思\", 看看都有什么吧!") return &message.Reply{message.MsgTypeText, aReply} } return &message.Reply{message.MsgTypeText, "没有找到哦,亲~\n"} }) //处理消息接收以及回复 err := server.Serve() if err != nil { fmt.Println(err) return } if err != nil { log.Warn(err) } //accessToken, err = server.GetAccessToken() //if err != nil { // beego.Error(err) //} //beego.Debug("access_token:", accessToken) //发送回复的消息 server.Send() }
package pgtest import ( "database/sql" "testing" _ "github.com/lib/pq" gc "gopkg.in/check.v1" ) func Test(t *testing.T) { gc.TestingT(t) } type S struct { PGSuite } var _ = gc.Suite(&S{}) func (s *S) TestRun(c *gc.C) { db, err := sql.Open("postgres", s.URL) c.Assert(err, gc.IsNil) var n int err = db.QueryRow("SELECT 1").Scan(&n) c.Assert(err, gc.IsNil) c.Assert(n, gc.Equals, 1, gc.Commentf("SELECT 1 = %d", n)) }
package main import ( "KafkaLog/src/KafkaLag/GetCluster" "KafkaLog/src/KafkaLag/GetConsumers" getlag "KafkaLog/src/KafkaLag/GetLag" "fmt" ) const ( url string = "xxxxx:8000/v3/kafka/" ) func main() { c, err := kafkaclusters.GetCluster(url) if err != nil { fmt.Println("get kafka cluster faild:", err) } cluster := c[0] data, err := getconsumers.GetConsumer(url, cluster) if err != nil { fmt.Println("get all consumers faild:", err) } //fmt.Println(data) for _, v := range data { lag, err := getlag.GetLag(url, cluster, v) if err != nil { fmt.Println("get lag faild:", err) } fmt.Println(lag) } }
package main import ( "fmt" "time" ) func main() { go say("virat") go say("kohli") // time.Sleep(time.Second) } func say(greet string) { for i := 0; i < 3; i++ { fmt.Println(greet) } }
package tc /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. */ import ( "testing" "time" ) func TestUser_UpgradeFromLegacyUser(t *testing.T) { addressLine1 := "Address Line 1" addressLine2 := "Address Line 2" city := "City" company := "Company" confirmLocalPassword := "Confirm LocalPasswd" country := "Country" email := "em@i.l" fullName := "Full Name" gid := 1 id := 2 lastUpdated := NewTimeNoMod() localPassword := "LocalPasswd" newUser := true phoneNumber := "555-555-5555" postalCode := "55555" publicSSHKey := "Public SSH Key" registrationSent := NewTimeNoMod() role := "Role Name" stateOrProvince := "State or Province" tenant := "Tenant" tenantID := 3 token := "Token" uid := 4 username := "Username" var user User user.AddressLine1 = &addressLine1 user.AddressLine2 = &addressLine2 user.City = &city user.Company = &company user.ConfirmLocalPassword = &confirmLocalPassword user.Country = &country user.Email = &email user.FullName = &fullName user.GID = &gid user.ID = &id user.LastUpdated = lastUpdated user.LocalPassword = &localPassword user.NewUser = &newUser user.PhoneNumber = &phoneNumber user.PostalCode = &postalCode user.PublicSSHKey = &publicSSHKey user.RegistrationSent = registrationSent user.Role = new(int) user.RoleName = &role user.StateOrProvince = &stateOrProvince user.Tenant = &tenant user.TenantID = &tenantID user.Token = &token user.UID = &uid user.Username = &username upgraded := user.Upgrade() if upgraded.AddressLine1 == nil { t.Error("AddressLine1 became nil after upgrade") } else if *upgraded.AddressLine1 != addressLine1 { t.Errorf("Incorrect AddressLine1 after upgrade; want: '%s', got: '%s'", addressLine1, *upgraded.AddressLine1) } if upgraded.AddressLine2 == nil { t.Error("AddressLine2 became nil after upgrade") } else if *upgraded.AddressLine2 != addressLine2 { t.Errorf("Incorrect AddressLine2 after upgrade; want: '%s', got: '%s'", addressLine2, *upgraded.AddressLine2) } if upgraded.City == nil { t.Error("City became nil after upgrade") } else if *upgraded.City != city { t.Errorf("Incorrect City after upgrade; want: '%s', got: '%s'", city, *upgraded.City) } if upgraded.Company == nil { t.Error("Company became nil after upgrade") } else if *upgraded.Company != company { t.Errorf("Incorrect Company after upgrade; want: '%s', got: '%s'", company, *upgraded.Company) } if upgraded.ConfirmLocalPassword == nil { t.Error("ConfirmLocalPassword became nil after upgrade") } else if *upgraded.ConfirmLocalPassword != confirmLocalPassword { t.Errorf("Incorrect ConfirmLocalPassword after upgrade; want: '%s', got: '%s'", confirmLocalPassword, *upgraded.ConfirmLocalPassword) } if upgraded.Country == nil { t.Error("Country became nil after upgrade") } else if *upgraded.Country != country { t.Errorf("Incorrect Country after upgrade; want: '%s', got: '%s'", country, *upgraded.Country) } if upgraded.Email == nil { t.Error("Email became nil after upgrade") } else if *upgraded.Email != email { t.Errorf("Incorrect Email after upgrade; want: '%s', got: '%s'", email, *upgraded.Email) } if upgraded.FullName == nil { t.Error("Fullname became nil after upgrade") } else if *upgraded.FullName != fullName { t.Errorf("Incorrect FullName after upgrade; want: '%s', got: '%s'", fullName, *upgraded.FullName) } if upgraded.GID == nil { t.Error("GID became nil after upgrade") } else if *upgraded.GID != gid { t.Errorf("Incorrect GID after upgrade; want: %d, got: %d", gid, *upgraded.GID) } if upgraded.ID == nil { t.Error("ID became nil after upgrade") } else if *upgraded.ID != id { t.Errorf("Incorrect ID after upgrade; want: %d, got: %d", id, *upgraded.ID) } if !upgraded.LastUpdated.Equal(lastUpdated.Time) { t.Errorf("Incorrect LastUpdated after upgrade; want: %v, got: %v", lastUpdated.Time, upgraded.LastUpdated) } if upgraded.LocalPassword == nil { t.Error("LocalPassword became nil after upgrade") } else if *upgraded.LocalPassword != localPassword { t.Errorf("Incorrect LocalPassword after upgrade; want: '%s', got: '%s'", localPassword, *upgraded.LocalPassword) } if upgraded.NewUser != newUser { t.Errorf("Incorrect NewUser after upgrade; want: %t, got: %t", newUser, upgraded.NewUser) } if upgraded.PhoneNumber == nil { t.Error("PhoneNumber became nil after upgrade") } else if *upgraded.PhoneNumber != phoneNumber { t.Errorf("Incorrect PhoneNumber after upgrade; want: '%s', got: '%s'", phoneNumber, *upgraded.PhoneNumber) } if upgraded.PostalCode == nil { t.Error("PostalCode became nil after upgrade") } else if *upgraded.PostalCode != postalCode { t.Errorf("Incorrect PostalCode after upgrade; want: '%s', got: '%s'", postalCode, *upgraded.PostalCode) } if upgraded.PublicSSHKey == nil { t.Error("PublicSSHKey became nil after upgrade") } else if *upgraded.PublicSSHKey != publicSSHKey { t.Errorf("Incorrect PublicSSHKey after upgrade; want: '%s', got: '%s'", publicSSHKey, *upgraded.PublicSSHKey) } if upgraded.RegistrationSent == nil { t.Error("RegistrationSent became nil after upgrade") } else if !upgraded.RegistrationSent.Equal(registrationSent.Time) { t.Errorf("Incorrect RegistrationSent after upgrade; want: %v, got: %v", registrationSent.Time, *upgraded.RegistrationSent) } if upgraded.Role != role { t.Errorf("Incorrect Role after upgrade; want: '%s', got: '%s'", role, upgraded.Role) } if upgraded.StateOrProvince == nil { t.Error("StateOrProvince became nil after upgrade") } else if *upgraded.StateOrProvince != stateOrProvince { t.Errorf("Incorrect StateOrProvince after upgrade; want: '%s', got: '%s'", stateOrProvince, *upgraded.StateOrProvince) } if upgraded.Tenant == nil { t.Error("Tenant became nil after upgrade") } else if *upgraded.Tenant != tenant { t.Errorf("Incorrect Tenant after upgrade; want: '%s', got: '%s'", tenant, *upgraded.Tenant) } if upgraded.TenantID != tenantID { t.Errorf("Incorrect TenantID after upgrade; want: %d, got: %d", tenantID, upgraded.TenantID) } if upgraded.Token == nil { t.Error("Token became nil after upgrade") } else if *upgraded.Token != token { t.Errorf("Incorrect Token after upgrade; want: '%s', got: '%s'", token, *upgraded.Token) } if upgraded.UID == nil { t.Error("UID became nil after upgrade") } else if *upgraded.UID != uid { t.Errorf("Incorrect UID after upgrade; want: %d, got: %d", uid, *upgraded.UID) } if upgraded.Username != username { t.Errorf("Incorrect Username after upgrade; want: '%s', got: '%s'", username, upgraded.Username) } user = upgraded.Downgrade() if user.Role != nil { t.Errorf("Expected Role to be nil after downgrade, got: %d", *user.Role) } } func TestUserV4_Downgrade(t *testing.T) { addressLine1 := "Address Line 1" addressLine2 := "Address Line 2" city := "City" company := "Company" confirmLocalPassword := "Confirm LocalPasswd" country := "Country" email := "em@i.l" fullName := "Full Name" gid := 1 id := 2 lastUpdated := time.Now() localPassword := "LocalPasswd" newUser := true phoneNumber := "555-555-5555" postalCode := "55555" publicSSHKey := "Public SSH Key" registrationSent := time.Now().Add(time.Second) role := "Role Name" stateOrProvince := "State or Province" tenant := "Tenant" tenantID := 3 token := "Token" uid := 4 username := "Username" user := UserV4{ FullName: &fullName, LastUpdated: lastUpdated, NewUser: newUser, Role: role, TenantID: tenantID, Username: username, } user.AddressLine1 = &addressLine1 user.AddressLine2 = &addressLine2 user.City = &city user.Company = &company user.ConfirmLocalPassword = &confirmLocalPassword user.Country = &country user.Email = &email user.GID = &gid user.ID = &id user.LocalPassword = &localPassword user.PhoneNumber = &phoneNumber user.PostalCode = &postalCode user.PublicSSHKey = &publicSSHKey user.RegistrationSent = &registrationSent user.StateOrProvince = &stateOrProvince user.Tenant = &tenant user.Token = &token user.UID = &uid downgraded := user.Downgrade() if downgraded.AddressLine1 == nil { t.Error("AddressLine1 became nil after downgrade") } else if *downgraded.AddressLine1 != addressLine1 { t.Errorf("Incorrect AddressLine1 after downgrade; want: '%s', got: '%s'", addressLine1, *downgraded.AddressLine1) } if downgraded.AddressLine2 == nil { t.Error("AddressLine2 became nil after downgrade") } else if *downgraded.AddressLine2 != addressLine2 { t.Errorf("Incorrect AddressLine2 after downgrade; want: '%s', got: '%s'", addressLine2, *downgraded.AddressLine2) } if downgraded.City == nil { t.Error("City became nil after downgrade") } else if *downgraded.City != city { t.Errorf("Incorrect City after downgrade; want: '%s', got: '%s'", city, *downgraded.City) } if downgraded.Company == nil { t.Error("Company became nil after downgrade") } else if *downgraded.Company != company { t.Errorf("Incorrect Company after downgrade; want: '%s', got: '%s'", company, *downgraded.Company) } if downgraded.ConfirmLocalPassword == nil { t.Error("ConfirmLocalPassword became nil after downgrade") } else if *downgraded.ConfirmLocalPassword != confirmLocalPassword { t.Errorf("Incorrect ConfirmLocalPassword after downgrade; want: '%s', got: '%s'", confirmLocalPassword, *downgraded.ConfirmLocalPassword) } if downgraded.Country == nil { t.Error("Country became nil after downgrade") } else if *downgraded.Country != country { t.Errorf("Incorrect Country after downgrade; want: '%s', got: '%s'", country, *downgraded.Country) } if downgraded.Email == nil { t.Error("Email became nil after downgrade") } else if *downgraded.Email != email { t.Errorf("Incorrect Email after downgrade; want: '%s', got: '%s'", email, *downgraded.Email) } if downgraded.FullName == nil { t.Error("FullName became nil after downgrade") } else if *downgraded.FullName != fullName { t.Errorf("Incorrect FullName after downgrade; want: '%s', got: '%s'", fullName, *downgraded.FullName) } if downgraded.GID == nil { t.Error("GID became nil after downgrade") } else if *downgraded.GID != gid { t.Errorf("Incorrect GID after downgrade; want: %d, got: %d", gid, *downgraded.GID) } if downgraded.ID == nil { t.Error("ID became nil after downgrade") } else if *downgraded.ID != id { t.Errorf("Incorrect ID after downgrade; want: %d, got: %d", id, *downgraded.ID) } if downgraded.LastUpdated == nil { t.Error("LastUpdated became nil after downgrade") } else if !downgraded.LastUpdated.Time.Equal(lastUpdated) { t.Errorf("Incorrect LastUpdated after downgrade; want: %v, got: %v", lastUpdated, downgraded.LastUpdated.Time) } if downgraded.LocalPassword == nil { t.Error("LocalPassword became nil after downgrade") } else if *downgraded.LocalPassword != localPassword { t.Errorf("Incorrect LocalPassword after downgrade; want: '%s', got: '%s'", localPassword, *downgraded.LocalPassword) } if downgraded.NewUser == nil { t.Error("NewUser became nil after downgrade") } else if *downgraded.NewUser != newUser { t.Errorf("Incorrect NewUser after downgrade; want: %t, got: %t", newUser, *downgraded.NewUser) } if downgraded.PhoneNumber == nil { t.Error("PhoneNumber became nil after downgrade") } else if *downgraded.PhoneNumber != phoneNumber { t.Errorf("Incorrect PhoneNumber after downgrade; want: '%s', got: '%s'", phoneNumber, *downgraded.PhoneNumber) } if downgraded.PostalCode == nil { t.Error("PostalCode became nil after downgrade") } else if *downgraded.PostalCode != postalCode { t.Errorf("Incorrect PostalCode after downgrade; want: '%s', got: '%s'", postalCode, *downgraded.PostalCode) } if downgraded.PublicSSHKey == nil { t.Error("PublicSSHKey became nil after downgrade") } else if *downgraded.PublicSSHKey != publicSSHKey { t.Errorf("Incorrect PublicSSHKey after downgrade; want: '%s', got: '%s'", publicSSHKey, *downgraded.PublicSSHKey) } if downgraded.RegistrationSent == nil { t.Error("RegistrationSent became nil after downgrade") } else if !downgraded.RegistrationSent.Time.Equal(registrationSent) { t.Errorf("Incorrect RegistrationSent after downgrade; want: %v, got: %v", registrationSent, downgraded.RegistrationSent.Time) } if downgraded.RoleName == nil { t.Error("RoleName became nil after downgrade") } else if *downgraded.RoleName != role { t.Errorf("Incorrect RoleName after downgrade; want: '%s', got: '%s'", role, *downgraded.RoleName) } if downgraded.StateOrProvince == nil { t.Error("StateOrProvince became nil after downgrade") } else if *downgraded.StateOrProvince != stateOrProvince { t.Errorf("Incorrect StateOrProvince after downgrade; want: '%s', got: '%s'", stateOrProvince, *downgraded.StateOrProvince) } if downgraded.Tenant == nil { t.Error("Tenant became nil after downgrade") } else if *downgraded.Tenant != tenant { t.Errorf("Incorrect Tenant after downgrade; want: '%s', got: '%s'", tenant, *downgraded.Tenant) } if downgraded.TenantID == nil { t.Error("TenantID became nil after downgrade") } else if *downgraded.TenantID != tenantID { t.Errorf("Incorrect TenantID after downgrade; want: %d, got: %d", tenantID, *downgraded.TenantID) } if downgraded.Token == nil { t.Error("Token became nil after downgrade") } else if *downgraded.Token != token { t.Errorf("Incorrect Token after downgrade; want: '%s', got: '%s'", token, *downgraded.Token) } if downgraded.UID == nil { t.Error("UID became nil after downgrade") } else if *downgraded.UID != uid { t.Errorf("Incorrect UID after downgrade; want: %d, got: %d", uid, *downgraded.UID) } if downgraded.Username == nil { t.Error("Username became nil after downgrade") } else if *downgraded.Username != username { t.Errorf("Incorrect Username after downgrade; want: '%s', got: '%s'", username, *downgraded.Username) } } func TestCopyUtilities(t *testing.T) { var s *string copiedS := copyStringIfNotNil(s) if copiedS != nil { t.Errorf("Copying a nil string should've given nil, got: %s", *copiedS) } s = new(string) *s = "test string" copiedS = copyStringIfNotNil(s) if copiedS == nil { t.Errorf("Copied pointer to '%s' was nil", *s) } else { if *copiedS != *s { t.Errorf("Incorrectly copied string pointer; expected: '%s', got: '%s'", *s, *copiedS) } *s = "a different test string" if *copiedS == *s { t.Error("Expected copy to be 'deep' but modifying the original string changed the copy") } } var i *int copiedI := copyIntIfNotNil(i) if copiedI != nil { t.Errorf("Copying a nil int should've given nil, got: %d", *copiedI) } i = new(int) *i = 9000 copiedI = copyIntIfNotNil(i) if copiedI == nil { t.Errorf("Copied pointer to %d was nil", *i) } else { if *copiedI != *i { t.Errorf("Incorrectly copied int pointer; expected: %d, got: %d", *i, *copiedI) } *i = 9001 if *copiedI == *i { t.Error("Expected copy to be 'deep' but modifying the original int changed the copy") } } }
package main import ( "database/sql" "fmt" ) type task struct { ID int `json:"id"` Completed bool `json:"completed"` Description string `json:"description"` } func (t *task) getTask(db *sql.DB) error { statement := fmt.Sprintf("SELECT description, completed FROM tasks WHERE id=%d", t.ID) return db.QueryRow(statement).Scan(&t.Description, &t.Completed) } func (t *task) deleteTask(db *sql.DB) error { statement := fmt.Sprintf("DELETE FROM tasks WHERE id=%d", t.ID) _, err := db.Exec(statement) return err } func (t *task) createTask(db *sql.DB) error { statement := fmt.Sprintf("INSERT INTO tasks(description, completed) VALUES('%v', false)", t.Description) _, err := db.Exec(statement) if err != nil { return err } err = db.QueryRow("SELECT id FROM tasks ORDER BY id DESC LIMIT 1").Scan(&t.ID) if err != nil { return err } return nil } func (t *task) updateTask(db *sql.DB) error { statement := fmt.Sprintf("UPDATE tasks SET completed=%t WHERE id=%d", t.Completed, t.ID) _, err := db.Exec(statement) return err } func getTasks(db *sql.DB) ([]task, error) { statement := fmt.Sprintf("SELECT id, description, completed FROM tasks") rows, err := db.Query(statement) if err != nil { return nil, err } defer rows.Close() tasks := []task{} for rows.Next() { var t task if err := rows.Scan(&t.ID, &t.Description, &t.Completed); err != nil { return nil, err } tasks = append(tasks, t) } return tasks, nil }
// Copyright 2017 Martin Hebnes Pedersen (LA5NTA). All rights reserved. // Use of this source code is governed by the MIT-license that can be // found in the LICENSE file. package main import ( "log" "net" "sync" "time" ) type TransportListener interface { Init() (net.Listener, error) Name() string CurrentFreq() (Frequency, bool) } type Beaconer interface { BeaconStop() BeaconStart() error } type Listener struct { t TransportListener hub *ListenerHub mu sync.Mutex isClosed bool err error ln net.Listener } func NewListener(t TransportListener) *Listener { return &Listener{t: t} } func (l *Listener) Err() error { l.mu.Lock() defer l.mu.Unlock() return l.err } func (l *Listener) Close() error { l.mu.Lock() defer l.mu.Unlock() if l.isClosed { return l.err } l.isClosed = true // If l.err is not nil, then the last attempt to open the listener failed and we don't have anything to close if l.err != nil { return l.err } return l.ln.Close() } func (l *Listener) listenLoop() { var silenceErr bool for { l.mu.Lock() if l.isClosed { l.mu.Unlock() break } // Try to init the TNC l.ln, l.err = l.t.Init() if l.err != nil { l.mu.Unlock() if !silenceErr { log.Printf("Listener %s failed: %s", l.t.Name(), l.err) log.Printf("Will try to re-establish listener in the background...") silenceErr = true websocketHub.UpdateStatus() } time.Sleep(time.Second) continue } l.mu.Unlock() if silenceErr { log.Printf("Listener %s re-established", l.t.Name()) silenceErr = false websocketHub.UpdateStatus() } if b, ok := l.t.(Beaconer); ok { b.BeaconStart() } // Run the accept loop until an error occurs if err := l.acceptLoop(); err != nil { log.Printf("Accept %s failed: %s", l.t.Name(), err) } if b, ok := l.t.(Beaconer); ok { b.BeaconStop() } } } type RemoteCaller interface { RemoteCall() string } func (l *Listener) acceptLoop() error { for { conn, err := l.ln.Accept() if err != nil { return err } remoteCall := conn.RemoteAddr().String() if c, ok := conn.(RemoteCaller); ok { remoteCall = c.RemoteCall() } freq, _ := l.t.CurrentFreq() eventLog.LogConn("accept", freq, conn, nil) log.Printf("Got connect (%s:%s)", l.t.Name(), remoteCall) err = exchange(conn, remoteCall, true) if err != nil { log.Printf("Exchange failed: %s", err) } else { log.Println("Disconnected.") } } } type ListenerHub struct { mu sync.Mutex listeners map[string]*Listener } func NewListenerHub() *ListenerHub { return &ListenerHub{ listeners: map[string]*Listener{}, } } func (h *ListenerHub) Active() []TransportListener { h.mu.Lock() defer h.mu.Unlock() slice := make([]TransportListener, 0, len(h.listeners)) for _, l := range h.listeners { if l.Err() != nil { continue } slice = append(slice, l.t) } return slice } func (h *ListenerHub) Enable(t TransportListener) { h.mu.Lock() defer func() { h.mu.Unlock() websocketHub.UpdateStatus() }() l := NewListener(t) if _, ok := h.listeners[t.Name()]; ok { return } h.listeners[t.Name()] = l go l.listenLoop() } func (h *ListenerHub) Disable(name string) (bool, error) { if name == MethodAX25 { name = defaultAX25Method() } h.mu.Lock() defer func() { h.mu.Unlock() websocketHub.UpdateStatus() }() l, ok := h.listeners[name] if !ok { return false, nil } delete(h.listeners, name) return true, l.Close() } func (h *ListenerHub) Close() { h.mu.Lock() defer func() { h.mu.Unlock() websocketHub.UpdateStatus() }() for k, l := range h.listeners { l.Close() delete(h.listeners, k) } }
package main import ( "fmt" "strconv" "os" "bufio" ) //常规写法 func normalFor() { sum := 0 for i := 1; i <= 100; i++ { sum += i } fmt.Println(sum) } //省略初始条件,相当于while func convertToBin(n int) string { result := "" for ; n > 0; n /= 2 { lsb := n % 2 result = strconv.Itoa(lsb) + result } return result } //省略初始条件和递增条件,相当于while func printFile(filename string) { file, err := os.Open(filename) if err != nil { panic(err) } scanner := bufio.NewScanner(file) for scanner.Scan() { fmt.Println(scanner.Text()) } } //省略所有条件,死循环 func forever() { for { fmt.Println("abc") } } func main() { normalFor() fmt.Printf("%s,%s,%s,%q", convertToBin(5), convertToBin(13), convertToBin(72387885), convertToBin(0), ) printFile("example/example01/loop.go") forever() }
package scrabble import ( "strings" ) var values = map[string]int{ "A": 1, "E": 1, "I": 1, "O": 1, "U": 1, "L": 1, "N": 1, "R": 1, "S": 1, "T": 1, "D": 2, "G": 2, "B": 3, "C": 3, "M": 3, "P": 3, "F": 4, "H": 4, "V": 4, "W": 4, "Y": 4, "K": 5, "J": 8, "X": 8, "Q": 10, "Z": 10, } //Score - Computes the scrabble score of 'word' based on the character values in 'values' func Score(word string) int { word = strings.ToUpper(word) return BuildScore(word, 0) } //BuildScore - Recursive function that sums the scrabble score of the characters of 'word' func BuildScore(word string, sum int) int { if word == "" { return sum } first, rest := word[0], word[1:] sum += values[string(first)] return BuildScore(rest, sum) }
package template func init() { Default.Add("version.go", Version, "cmd/version.go") Default.Add("versions.go", LibVersion, "pkg/versions/versions.go") Default.Add("description.go", Description, "pkg/versions/description.go") } // Version cmd/version.go模板 const Version = ` package cmd import ( "{{.importPath}}/pkg/versions" "github.com/spf13/cobra" ) var versionCmd = &cobra.Command{ Use: "version", Short: "打印出版本号", Run: func(cmd *cobra.Command, args []string) { versions.Print() }, } func init() { rootCmd.AddCommand(versionCmd) } ` // LibVersion cmd/version.go模板 const LibVersion = ` package versions import ( "fmt" "runtime" ) // 通过go build -X 注入的参数 var ( xVersion string // Version 程序版本 xGitCommit string // GitCommit git提交的hash xBuilt string // Built 编译时间 ) // Info 版本信息 type Info struct { Version string {{.backquoted}}json:"version"{{.backquoted}} GitCommit string {{.backquoted}}json:"gitCommit"{{.backquoted}} GoVersion string {{.backquoted}}json:"goVersion"{{.backquoted}} Built string {{.backquoted}}json:"built"{{.backquoted}} } // New 返回*info对象 func New(version, gitcommit, built string) *Info { return &Info{ Version: version, GitCommit: gitcommit, GoVersion: runtime.Version(), Built: built, } } func (i *Info) strings() string { return fmt.Sprintf("%s GitCommit:%s GoVersion:%s Built:%s", i.Version, i.GitCommit, i.GoVersion, i.Built) } func Strings() string { return Default.strings() } func Print() { fmt.Println(Default.strings()) } func init() { Default = New(xVersion, xGitCommit, xBuilt) } var Default *Info ` // Description 版本描述 const Description = ` package versions // ShortDescribe 简单的描述 var ShortDescribe = "用于创建GO项目的脚手架" // LongDescribe 长描述 var LongDescribe = "" `
package rangeproof import ( "math/big" "math/rand" "testing" ristretto "github.com/bwesterb/go-ristretto" "github.com/stretchr/testify/assert" ) func TestProveBulletProof(t *testing.T) { // due to inner product proof, must be a multiple of two m := 4 amounts := []ristretto.Scalar{} for i := 0; i < m; i++ { var amount ristretto.Scalar n := rand.Int63() amount.SetBigInt(big.NewInt(n)) amounts = append(amounts, amount) } // Prove // t.Fail() p, err := Prove(amounts, true) if err != nil { assert.FailNowf(t, err.Error(), "Prove function failed %s", "") } // Verify ok, err := Verify(p) assert.Equal(t, nil, err) assert.Equal(t, true, ok) } func TestComputeMu(t *testing.T) { var one ristretto.Scalar one.SetOne() var expected ristretto.Scalar expected.SetBigInt(big.NewInt(2)) res := computeMu(one, one, one) ok := expected.Equals(&res) assert.Equal(t, true, ok) } func BenchmarkProve(b *testing.B) { var amount ristretto.Scalar amount.SetBigInt(big.NewInt(100000)) for i := 0; i < 100; i++ { // Prove Prove([]ristretto.Scalar{amount}, false) } } func BenchmarkVerify(b *testing.B) { var amount ristretto.Scalar amount.SetBigInt(big.NewInt(100000)) p, _ := Prove([]ristretto.Scalar{amount}, false) b.ResetTimer() for i := 0; i < 100; i++ { // Verify Verify(p) } }
package main import ( _ "server-monitor-admin/config" "server-monitor-admin/core" "server-monitor-admin/global" "server-monitor-admin/initialize" ) func main() { //初始化mysql initialize.Mysql() //注册所有表 initialize.DbTables() //程序结束关闭数据库连接 defer global.DB.Close() //启动服务 core.RunServer() }
package objs type IpasTrackingFilter struct { IpasFilter EquipIdWithOrg string `form:"equip_id_with_org"` }
package models // Models generated from: https://mholt.github.io/json-to-go/ type BlockRes struct { Hash string `json:"hash"` Size int `json:"size"` Version int `json:"version"` Previousblockhash string `json:"previousblockhash"` Merkleroot string `json:"merkleroot"` Time int `json:"time"` Index int `json:"index"` Nonce string `json:"nonce"` Nextconsensus string `json:"nextconsensus"` Script struct { Invocation string `json:"invocation"` Verification string `json:"verification"` } `json:"script"` Tx []struct { Txid string `json:"txid"` Size int `json:"size"` Type string `json:"type"` Version int `json:"version"` Attributes []map[string]string `json:"attributes"` Vin []struct { Txid string `json:"txid"` VoutIndex int `json:"vout"` } `json:"vin"` Vout []struct { N int `json:"n"` Address string `json:"address"` Value string `json:"value"` Asset string `json:"asset"` } `json:"vout"` SysFee string `json:"sys_fee"` NetFee string `json:"net_fee"` Scripts []struct { VerificationScript string `json:"verification"` InvocationScript string `json:"invocation"` } `json:"scripts"` Nonce int64 `json:"nonce"` } `json:"tx"` Confirmations int `json:"confirmations"` Nextblockhash string `json:"nextblockhash"` } type VersionResults struct { Port int `json:"port"` Nonce int `json:"nonce"` Useragent string `json:"useragent"` } type Host struct { Address string Port int }
// Copyright 2022 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 sqlexec import ( "context" "github.com/pingcap/tidb/parser/ast" "github.com/pingcap/tidb/types" "github.com/pingcap/tidb/util/chunk" ) // SimpleRecordSet is a simple implementation of RecordSet. All values are known when creating SimpleRecordSet. type SimpleRecordSet struct { ResultFields []*ast.ResultField Rows [][]interface{} MaxChunkSize int idx int } // Fields implements the sqlexec.RecordSet interface. func (r *SimpleRecordSet) Fields() []*ast.ResultField { return r.ResultFields } // Next implements the sqlexec.RecordSet interface. func (r *SimpleRecordSet) Next(_ context.Context, req *chunk.Chunk) error { req.Reset() for r.idx < len(r.Rows) { if req.IsFull() { return nil } for i := range r.ResultFields { datum := types.NewDatum(r.Rows[r.idx][i]) req.AppendDatum(i, &datum) } r.idx++ } return nil } // NewChunk implements the sqlexec.RecordSet interface. func (r *SimpleRecordSet) NewChunk(alloc chunk.Allocator) *chunk.Chunk { fields := make([]*types.FieldType, 0, len(r.ResultFields)) for _, field := range r.ResultFields { fields = append(fields, &field.Column.FieldType) } if alloc != nil { return alloc.Alloc(fields, 0, r.MaxChunkSize) } return chunk.New(fields, r.MaxChunkSize, r.MaxChunkSize) } // Close implements the sqlexec.RecordSet interface. func (r *SimpleRecordSet) Close() error { r.idx = 0 return nil }
package gatekeeper import "log" func RetryAndPanic(retries uint, f func() error) { // retry a function n times before panicing and closing out the // program. This should only be for exceptional cases err := f() for i := uint(0); i <= retries; i++ { if err == nil { return } err = f() } log.Fatal(err) }
package data_test import ( "accountapi/data" "encoding/json" "strings" "testing" "github.com/biter777/countries" ) // TestCCode for testing unmarshalling JSON values. type TestCCode struct { TestCC data.CountryCode `json:"testCC"` } // TestCountryCode verifies proper country codes parsing and unmarshalling. func TestCountryCode(t *testing.T) { cc := data.NewCountryCode(countries.UnitedKingdom) if cc.String() != "GB" { t.Error("CountryCode string should be \"GB\".") t.Fail() } jString := `{"testCC":"GB"}` jStruct := TestCCode{} err := json.NewDecoder(strings.NewReader(jString)).Decode(&jStruct) if err != nil { t.Errorf("Can't unmarshal CountryCode: %s\n", err.Error()) t.Fail() } if jStruct.TestCC != cc { t.Errorf("Expected CountryCode value: '%s', got: '%s'\n", cc.String(), jStruct.TestCC.String()) t.Fail() } b, err := json.Marshal(&jStruct) if err != nil { t.Errorf("Can't marshal CountryCode to string: %s\n", err.Error()) t.Fail() } else if string(b) != jString { t.Errorf("Expected marshalled value: '%s', got: '%s'\n", jString, string(b)) t.Fail() } jString = `{"testCC":"fake_country"}` err = json.NewDecoder(strings.NewReader(jString)).Decode(&jStruct) if err == nil { t.Error("Invalid country code unmarshalling should fail.") t.Fail() } }
package main import ( "database/sql" "fmt" _ "github.com/go-sql-driver/mysql" "log" "time" ) var MysqlDb *sql.DB var MysqlDbErr error const ( UserName = "root" PassWord = "jsw135799" HOST = "115.29.243.4" PORT = "3306" DATABASE = "blog" CHARSET = "utf8" ) // 初始化链接 func init() { dbDSN := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=%s", UserName, PassWord, HOST, PORT, DATABASE, CHARSET) // 打开连接失败 MysqlDb, MysqlDbErr = sql.Open("mysql", dbDSN) //defer MysqlDb.Close(); if MysqlDbErr != nil { log.Println("dbDSN: " + dbDSN) panic("数据源配置不正确: " + MysqlDbErr.Error()) } // 最大连接数 MysqlDb.SetMaxOpenConns(100) // 闲置连接数 MysqlDb.SetMaxIdleConns(20) // 最大连接周期 MysqlDb.SetConnMaxLifetime(100 * time.Second) if MysqlDbErr = MysqlDb.Ping(); nil != MysqlDbErr { panic("数据库链接失败: " + MysqlDbErr.Error()) } } type Field struct { id string title string summary string } func main() { defer func(MysqlDb *sql.DB) { err := MysqlDb.Close() if err != nil { fmt.Println("关闭mysql连接失败!!!!!!!!!!!!") } }(MysqlDb) // 查询 fields := search() for _, tmpResult := range fields { fmt.Println(tmpResult) } // 插入 insert() // 删除 delete() } func search() []Field { query, err := MysqlDb.Query("select id,title,summary from blog") if err != nil { fmt.Println("查询出现未知错误!!!!!") } defer func(query *sql.Rows) { err := query.Close() if err != nil { println("出现位置错误。") } }(query) var result []Field for query.Next() { var tmpTarget Field if err = query.Scan(&tmpTarget.id, &tmpTarget.title, &tmpTarget.summary); err != nil { fmt.Println(err) // Handle scan error } result = append(result, tmpTarget) } return result } func insert() { sqlStr := "insert into type_name(id,name) value(?,? )" exec, err := MysqlDb.Exec(sqlStr, "4", "测试go连接mysql") if err != nil { fmt.Println(err) return } id, err := exec.LastInsertId() if err != nil { fmt.Printf("getLastId error , %v\n", err) return } fmt.Printf("lastInsertId:%v\n", id) } func delete() { sqlStr := "delete from type_name where id = ?" exec, err := MysqlDb.Exec(sqlStr, "4") if err != nil { fmt.Println(err) return } affected, err := exec.RowsAffected() if err != nil { fmt.Println(nil) return } fmt.Printf("affect row : %v\n", affected) }
package unionfind import ( "fmt" "math" "testing" ) func setupUnionCalls(uf UnionFind) { uf.Union(4, 3) uf.Union(3, 8) uf.Union(6, 5) uf.Union(9, 4) uf.Union(2, 1) uf.Union(8, 9) uf.Union(5, 0) uf.Union(7, 2) } var expectedConnectedResults = []struct { p, q int expected bool }{ {0, 1, false}, {0, 5, true}, {1, 6, false}, {6, 1, false}, {8, 9, true}, {4, 9, true}, } func assertEqual(t *testing.T, actual, expected []int) { for i, _ := range expected { if actual[i] != expected[i] { t.Fatalf("expected %v but got %v", expected, actual) } } } func TestOneStep(t *testing.T) { uf := NewQuickFind(10) uf.Union(0, 1) assertEqual(t, uf.id, []int{1, 1, 2, 3, 4, 5, 6, 7, 8, 9}) } func TestQuickFind(t *testing.T) { uf := NewQuickFind(10) setupUnionCalls(uf) for _, r := range expectedConnectedResults { actual := uf.Connected(r.p, r.q) if actual != r.expected { t.Errorf("Expected Connected(%v, %v) to be %v, but was %v\n", r.p, r.q, r.expected, actual) } } } var rootResults = []struct { p, expected int }{ {0, 2}, {1, 1}, {2, 2}, {3, 3}, } func TestQuickUnionRootFunc(t *testing.T) { uf := NewQuickUnion(4) uf.id = []int{2, 1, 2, 3} for _, r := range rootResults { actual := root(uf.id, r.p) if actual != r.expected { t.Errorf("Expected root(%v) to be %v, it was %v\n", r.p, r.expected, actual) } } } func TestUnionFind(t *testing.T) { uf := NewQuickUnion(10) setupUnionCalls(uf) for _, r := range expectedConnectedResults { actual := uf.Connected(r.p, r.q) if actual != r.expected { t.Errorf("Expected Connected(%v, %v) to be %v, but was %v\n", r.p, r.q, r.expected, actual) } } } func TestWeightedUnionFind(t *testing.T) { w := NewWeightedQuickUnion(10) setupUnionCalls(w) for _, r := range expectedConnectedResults { actual := w.Connected(r.p, r.q) if actual != r.expected { t.Errorf("Expected Connected(%v, %v) to be %v, but was %v\n", r.p, r.q, r.expected, actual) } } fmt.Printf("id:%v\nsz:%v\n", w.id, w.sz) } func TestTreeSizeWeightedQU(t *testing.T){ n := 8 w := NewWeightedQuickUnion(n) for i := 1; i < n; i++ { w.Union(i,0) } log2n := int(math.Log2(float64(n))) for _, val := range w.sz { if val > log2n { t.Errorf("No depth should be greater than log2(%v), which is %v. This one was: %v", n, log2n, val) } } // fmt.Printf("%v", w.sz) }
// consume the queue called 'encryptonator' and run a go routine to start // the encryption process package main import ( "fmt" "log" "strings" "github.com/streadway/amqp" ) type consumer struct { uri string exchange string exchangeType string queueName string bindingKey string consumerTag string } // NewConsumer start consuming queue func (c *consumer) Consume(quitchan chan string) error { log.Printf("dialing %q", c.uri) conn, err := amqp.Dial(c.uri) if err != nil { return fmt.Errorf("Dial: %s", err) } defer conn.Close() log.Printf("got Connection, getting Channel") channel, err := conn.Channel() if err != nil { return fmt.Errorf("Channel: %s", err) } defer channel.Close() log.Printf("got Channel, declaring Exchange (%q)", c.exchange) err = channel.ExchangeDeclare( c.exchange, // name of the exchange c.exchangeType, // type true, // durable false, // delete when complete false, // internal false, // noWait nil, // arguments ) if err != nil { return fmt.Errorf("Exchange Declare: %s", err) } log.Printf("declared Exchange, declaring Queue %q", c.queueName) queue, err := channel.QueueDeclare( c.queueName, // name of the queue true, // durable false, // delete when usused false, // exclusive false, // noWait nil, // arguments ) if err != nil { return fmt.Errorf("Queue Declare: %s", err) } log.Printf("declared Queue (%q %d messages, %d consumers), binding to Exchange (key %q)", queue.Name, queue.Messages, queue.Consumers, c.bindingKey) err = channel.QueueBind( queue.Name, // name of the queue c.bindingKey, // bindingKey c.exchange, // sourceExchange false, // noWait nil, // arguments ) if err != nil { return fmt.Errorf("Queue Bind: %s", err) } log.Printf("Queue bound to Exchange, starting Consume (consumer tag %q)", c.consumerTag) deliveries, err := channel.Consume( queue.Name, // name c.consumerTag, // consumerTag, false, // noAck false, // exclusive false, // noLocal false, // noWait nil, // arguments ) if err != nil { return fmt.Errorf("Queue Consume: %s", err) } for { // check termination conditions first after every message select { // handle ctrl-c case <-quitchan: log.Printf("Consumer quit") return nil // server died case <-conn.NotifyClose(nil): log.Printf("NotifyClose") return nil // termination condition not met // wait for incoming message or termination condition default: select { // handle ctrl-c case <-quitchan: log.Printf("Consumer quit") return nil // server died case <-conn.NotifyClose(nil): log.Printf("NotifyClose") return nil case d := <-deliveries: if err := handle(string(d.Body)); err != nil { log.Printf("handle failed: %s", err) } if err := d.Ack(false); err != nil { log.Printf("d.Ack failed: %s", err) } } } } return nil } func handle(body string) error { p := strings.Split(body, ",") if len(p) != 3 { return fmt.Errorf("invalid message: %s", body) } platform, rsyncPID, path := p[0], p[1], p[2] log.Printf("got %v and %v and %v", platform, rsyncPID, path) return FileMover(platform, rsyncPID, path) }
package models import ( "github.com/gophergala2016/source/core/foundation" ) type UserRepository struct { RootRepository } func NewUserRepository(ctx foundation.Context) *UserRepository { return &UserRepository{ RootRepository: NewRootRepository(ctx), } } func (r *UserRepository) GetByID(id uint64) (*User, error) { ent := new(User) if err := r.Orm.Where("id = ?", id).First(ent).Error; err != nil { return nil, err } return ent, nil } func (r *UserRepository) FindByIDs(ids []uint64) ([]User, error) { var ents []User if len(ids) == 0 { return ents, nil } if err := r.Orm.Where("id IN (?)", ids).Find(&ents).Error; err != nil { return ents, err } return ents, nil } func (r *UserRepository) GetByAccessToken(token string) (*User, error) { ent := new(User) if err := r.Orm.Where("access_token = ?", token).First(ent).Error; err != nil { return nil, err } return ent, nil } func (r *UserRepository) GetByName(name string) (*User, error) { ent := new(User) if err := r.Orm.Where("name = ?", name).First(ent).Error; err != nil { return nil, err } return ent, nil } func (r *UserRepository) Create(ent *User) (*User, error) { if err := r.Orm.Create(ent).Error; err != nil { return nil, err } return ent, nil }
package api import ( "encoding/json" "fmt" "sync" "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/CosmWasm/wasmvm/types" dbm "github.com/tendermint/tm-db" ) type queueData struct { checksum []byte store *Lookup api *GoAPI querier types.Querier } func (q queueData) Store(meter MockGasMeter) KVStore { return q.store.WithGasMeter(meter) } func setupQueueContractWithData(t *testing.T, cache Cache, values ...int) queueData { checksum := createQueueContract(t, cache) gasMeter1 := NewMockGasMeter(TESTING_GAS_LIMIT) // instantiate it with this store store := NewLookup(gasMeter1) api := NewMockAPI() querier := DefaultQuerier(MOCK_CONTRACT_ADDR, types.Coins{types.NewCoin(100, "ATOM")}) env := MockEnvBin(t) info := MockInfoBin(t, "creator") msg := []byte(`{}`) igasMeter1 := GasMeter(gasMeter1) res, _, err := Instantiate(cache, checksum, env, info, msg, &igasMeter1, store, api, &querier, TESTING_GAS_LIMIT, TESTING_PRINT_DEBUG) require.NoError(t, err) requireOkResponse(t, res, 0) for _, value := range values { // push 17 var gasMeter2 GasMeter = NewMockGasMeter(TESTING_GAS_LIMIT) push := []byte(fmt.Sprintf(`{"enqueue":{"value":%d}}`, value)) res, _, err = Execute(cache, checksum, env, info, push, &gasMeter2, store, api, &querier, TESTING_GAS_LIMIT, TESTING_PRINT_DEBUG) require.NoError(t, err) requireOkResponse(t, res, 0) } return queueData{ checksum: checksum, store: store, api: api, querier: querier, } } func setupQueueContract(t *testing.T, cache Cache) queueData { return setupQueueContractWithData(t, cache, 17, 22) } func TestStoreIterator(t *testing.T) { const limit = 2000 callID1 := startCall() callID2 := startCall() store := dbm.NewMemDB() var iter dbm.Iterator var index uint64 var err error iter, _ = store.Iterator(nil, nil) index, err = storeIterator(callID1, iter, limit) require.NoError(t, err) require.Equal(t, uint64(1), index) iter, _ = store.Iterator(nil, nil) index, err = storeIterator(callID1, iter, limit) require.NoError(t, err) require.Equal(t, uint64(2), index) iter, _ = store.Iterator(nil, nil) index, err = storeIterator(callID2, iter, limit) require.NoError(t, err) require.Equal(t, uint64(1), index) iter, _ = store.Iterator(nil, nil) index, err = storeIterator(callID2, iter, limit) require.NoError(t, err) require.Equal(t, uint64(2), index) iter, _ = store.Iterator(nil, nil) index, err = storeIterator(callID2, iter, limit) require.NoError(t, err) require.Equal(t, uint64(3), index) endCall(callID1) endCall(callID2) } func TestStoreIteratorHitsLimit(t *testing.T) { callID := startCall() store := dbm.NewMemDB() var iter dbm.Iterator var err error const limit = 2 iter, _ = store.Iterator(nil, nil) _, err = storeIterator(callID, iter, limit) require.NoError(t, err) iter, _ = store.Iterator(nil, nil) _, err = storeIterator(callID, iter, limit) require.NoError(t, err) iter, _ = store.Iterator(nil, nil) _, err = storeIterator(callID, iter, limit) require.ErrorContains(t, err, "Reached iterator limit (2)") endCall(callID) } func TestRetrieveIterator(t *testing.T) { const limit = 2000 callID1 := startCall() callID2 := startCall() store := dbm.NewMemDB() var iter dbm.Iterator var err error iter, _ = store.Iterator(nil, nil) index11, err := storeIterator(callID1, iter, limit) require.NoError(t, err) iter, _ = store.Iterator(nil, nil) _, err = storeIterator(callID1, iter, limit) require.NoError(t, err) iter, _ = store.Iterator(nil, nil) _, err = storeIterator(callID2, iter, limit) require.NoError(t, err) iter, _ = store.Iterator(nil, nil) index22, err := storeIterator(callID2, iter, limit) require.NoError(t, err) iter, err = store.Iterator(nil, nil) index23, err := storeIterator(callID2, iter, limit) require.NoError(t, err) // Retrieve existing iter = retrieveIterator(callID1, index11) require.NotNil(t, iter) iter = retrieveIterator(callID2, index22) require.NotNil(t, iter) // Retrieve non-existent index iter = retrieveIterator(callID1, index23) require.Nil(t, iter) iter = retrieveIterator(callID1, uint64(0)) require.Nil(t, iter) // Retrieve non-existent call ID iter = retrieveIterator(callID1+1_234_567, index23) require.Nil(t, iter) endCall(callID1) endCall(callID2) } func TestQueueIteratorSimple(t *testing.T) { cache, cleanup := withCache(t) defer cleanup() setup := setupQueueContract(t, cache) checksum, querier, api := setup.checksum, setup.querier, setup.api // query the sum gasMeter := NewMockGasMeter(TESTING_GAS_LIMIT) igasMeter := GasMeter(gasMeter) store := setup.Store(gasMeter) query := []byte(`{"sum":{}}`) env := MockEnvBin(t) data, _, err := Query(cache, checksum, env, query, &igasMeter, store, api, &querier, TESTING_GAS_LIMIT, TESTING_PRINT_DEBUG) require.NoError(t, err) var qres types.QueryResponse err = json.Unmarshal(data, &qres) require.NoError(t, err) require.Equal(t, "", qres.Err) require.Equal(t, `{"sum":39}`, string(qres.Ok)) // query reduce (multiple iterators at once) query = []byte(`{"reducer":{}}`) data, _, err = Query(cache, checksum, env, query, &igasMeter, store, api, &querier, TESTING_GAS_LIMIT, TESTING_PRINT_DEBUG) require.NoError(t, err) var reduced types.QueryResponse err = json.Unmarshal(data, &reduced) require.NoError(t, err) require.Equal(t, "", reduced.Err) require.Equal(t, `{"counters":[[17,22],[22,0]]}`, string(reduced.Ok)) } func TestQueueIteratorRaces(t *testing.T) { cache, cleanup := withCache(t) defer cleanup() assert.Equal(t, 0, len(iteratorFrames)) contract1 := setupQueueContractWithData(t, cache, 17, 22) contract2 := setupQueueContractWithData(t, cache, 1, 19, 6, 35, 8) contract3 := setupQueueContractWithData(t, cache, 11, 6, 2) env := MockEnvBin(t) reduceQuery := func(t *testing.T, setup queueData, expected string) { checksum, querier, api := setup.checksum, setup.querier, setup.api gasMeter := NewMockGasMeter(TESTING_GAS_LIMIT) igasMeter := GasMeter(gasMeter) store := setup.Store(gasMeter) // query reduce (multiple iterators at once) query := []byte(`{"reducer":{}}`) data, _, err := Query(cache, checksum, env, query, &igasMeter, store, api, &querier, TESTING_GAS_LIMIT, TESTING_PRINT_DEBUG) require.NoError(t, err) var reduced types.QueryResponse err = json.Unmarshal(data, &reduced) require.NoError(t, err) require.Equal(t, "", reduced.Err) require.Equal(t, fmt.Sprintf(`{"counters":%s}`, expected), string(reduced.Ok)) } // 30 concurrent batches (in go routines) to trigger any race condition numBatches := 30 var wg sync.WaitGroup // for each batch, query each of the 3 contracts - so the contract queries get mixed together wg.Add(numBatches * 3) for i := 0; i < numBatches; i++ { go func() { reduceQuery(t, contract1, "[[17,22],[22,0]]") wg.Done() }() go func() { reduceQuery(t, contract2, "[[1,68],[19,35],[6,62],[35,0],[8,54]]") wg.Done() }() go func() { reduceQuery(t, contract3, "[[11,0],[6,11],[2,17]]") wg.Done() }() } wg.Wait() // when they finish, we should have removed all frames assert.Equal(t, 0, len(iteratorFrames)) } func TestQueueIteratorLimit(t *testing.T) { cache, cleanup := withCache(t) defer cleanup() setup := setupQueueContract(t, cache) checksum, querier, api := setup.checksum, setup.querier, setup.api var err error var qres types.QueryResponse var gasLimit uint64 // Open 5000 iterators gasLimit = TESTING_GAS_LIMIT gasMeter := NewMockGasMeter(gasLimit) igasMeter := GasMeter(gasMeter) store := setup.Store(gasMeter) query := []byte(`{"open_iterators":{"count":5000}}`) env := MockEnvBin(t) data, _, err := Query(cache, checksum, env, query, &igasMeter, store, api, &querier, gasLimit, TESTING_PRINT_DEBUG) require.NoError(t, err) err = json.Unmarshal(data, &qres) require.NoError(t, err) require.Equal(t, "", qres.Err) require.Equal(t, `{}`, string(qres.Ok)) // Open 35000 iterators gasLimit = TESTING_GAS_LIMIT * 4 gasMeter = NewMockGasMeter(gasLimit) igasMeter = GasMeter(gasMeter) store = setup.Store(gasMeter) query = []byte(`{"open_iterators":{"count":35000}}`) env = MockEnvBin(t) data, _, err = Query(cache, checksum, env, query, &igasMeter, store, api, &querier, gasLimit, TESTING_PRINT_DEBUG) require.ErrorContains(t, err, "Reached iterator limit (32768)") }
package models import "fmt" const ( _keyID = "id" _keyFieldsets = "fieldsets" _keyFields = "fields" ) // From models the structure of an HTML Form type Form struct { ID string `json:"id"` Fieldsets map[string]Fieldset `json:"fieldsets"` Fields map[string]Field `json:"fields"` } // EmptyFormInstance returns a FormInstance where all values are set to nil/null. func (f Form) EmptyFormInstance() FormInstance { data := map[string]interface{}{} fieldSets := map[string]interface{}{} for k, v := range f.Fieldsets { fieldSets[k] = v.emptyInstance() } if len(fieldSets) > 0 { data[_keyFieldsets] = fieldSets } fields := map[string]interface{}{} for k, _ := range f.Fields { fields[k] = nil } if len(fields) > 0 { data[_keyFields] = fields } return data } func (f Form) ValidateFormInstance(jsonFormInstance FormInstance) error { // Handle Fieldsets for k, v := range jsonFormInstance.Fieldsets() { formFieldset, ok := f.Fieldsets[k] if !ok { return fmt.Errorf("fieldset %q not present in form definition", k) } for fk, fv := range v { formField, ok := formFieldset.Fields[fk] if !ok { return fmt.Errorf("field %q not present in form's fieldset %q definition", fk, k) } if err := formField.validate(fv); err != nil { return fmt.Errorf("%s.%s.%s: %s", _keyFieldsets, k, fk, err.Error()) } } } // Handle Fields for k, v := range jsonFormInstance.Fields() { formField, ok := f.Fields[k] if !ok { return fmt.Errorf("field %q not present in form definition", k) } if err := formField.validate(v); err != nil { return fmt.Errorf("%s.%s: %s", _keyFields, k, err.Error()) } } return nil }
package taskpool import ( "errors" "time" ) var ( errPoolSizeNotValid = errors.New("pool size not valid") errQueueSizeNotValid = errors.New("pool size not valid") errPoolFull = errors.New("pool is full") errPoolTimeout = errors.New("timeout") errPoolPanic = errors.New("panic") errPoolClosed = errors.New("pool closed") ) var defaultPool *TaskPool func init() { defaultPool, _ = NewTaskPool() } type Option func(p *TaskPool) func WithMinSize(minSize int32) Option { return func(p *TaskPool) { p.minSize = minSize } } func WithMaxSize(maxSize int32) Option { return func(p *TaskPool) { p.maxSize = maxSize } } func WithQueueSize(queueSize int32) Option { return func(p *TaskPool) { p.queueSize = queueSize } } func NewTaskPool(options ...Option) (*TaskPool, error) { pool := &TaskPool{ status: poolStatusOpened, } for _, option := range options { option(pool) } // fill default value if pool.minSize == 0 { pool.minSize = defaultMinPoolSize } if pool.maxSize == 0 { pool.maxSize = defaultMaxPoolSize } if pool.queueSize == 0 { pool.queueSize = defaultQueueSize } err := checkPool(pool) if err != nil { return nil, err } pool.size = pool.minSize // size init to minSize pool.works = make([]*worker, 0, pool.minSize) pool.tasks = make(chan *taskWrap, pool.queueSize) pool.notifier = make(chan struct{}, pool.queueSize) pool.init() return pool, nil } func checkPool(p *TaskPool) error { if p.minSize < 1 || p.minSize > p.maxSize { return errPoolSizeNotValid } if p.queueSize < 1 { return errQueueSizeNotValid } return nil } func AsyncRunTask(task AsyncTask) error { return defaultPool.AsyncRunTask(task) } func SyncRunTask(task SyncTask) (interface{}, error) { return defaultPool.SyncRunTask(task) } func SyncRunTaskWithTimeout(task SyncTask, timeout time.Duration) (result interface{}, err error) { return defaultPool.SyncRunTaskWithTimeout(task, timeout) }
package prototype // cloneable接口 type Cloneable interface { Clone() Cloneable } // 原型类,实现cloneable接口 type Handler struct { Name string } func NewHandler(name string) *Handler { return &Handler{Name: name} } func (s *Handler) GetName() string { return s.Name } func (s *Handler) SetName(name string) { s.Name = name } func (s *Handler) Clone() Cloneable { cloneHandler := s return cloneHandler } // 原型管理类 type HandlerManager struct { list map[string]Handler } func NewManager() *HandlerManager { return &HandlerManager{ list: make(map[string]Handler, 0), } } func (s *HandlerManager) Get(name string) Handler { return s.list[name] } func (s *HandlerManager) Set(name string, prototype Handler) { s.list[name] = prototype }
package main //Request hold the content for performing cloning type Request struct { App App Bucket string Content []byte `json:"content"` Key string `json:"key"` }
package middleware import ( "net/http" "github.com/ismar/dsa/distrybuted_systems_api/utils" ) //Middleware ... type Middleware struct{} // CORS ... func (m Middleware) CORS(res http.ResponseWriter, req *http.Request, next http.HandlerFunc) { // CORS support for Preflighted requests res.Header().Set("Access-Control-Allow-Origin", "*") res.Header().Set("Access-Control-Allow-Methods", "OPTIONS, GET, POST, PUT, PATCH, DELETE") res.Header().Set("Access-Control-Allow-Headers", "Authorization, Content-Type") next(res, req) } // Preflight ... func (m Middleware) Preflight(res http.ResponseWriter, req *http.Request, next http.HandlerFunc) { if req.Method == "OPTIONS" { utils.Renderer.Render(res, http.StatusOK, map[string]string{"status": "OK"}) return } next(res, req) }
package lib type H map[string]interface{}
/* Copyright 2020 Kamal Nasser 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 kubectldoweb import ( "fmt" "io" "golang.org/x/net/context" "k8s.io/client-go/kubernetes" "k8s.io/client-go/tools/clientcmd" ) type Runner func(ctx context.Context, writer io.Writer, kubeConfig clientcmd.ClientConfig, namespace, typ, name string) (string, error) const cloudBase = "https://cloud.digitalocean.com/" var ErrMissingArgument = fmt.Errorf("missing argument") func Run(ctx context.Context, writer io.Writer, kubeConfig clientcmd.ClientConfig, namespace, typ, name string) (string, error) { // if a namespace is not explicitly provided, use the default set in kube config if namespace == "" { namespace, _, _ = kubeConfig.Namespace() } if namespace == "" { fmt.Println("could not determine namespace using the provided kube config") return "", ErrMissingArgument } clientConfig, err := kubeConfig.ClientConfig() if err != nil { return "", err } clientset, err := kubernetes.NewForConfig(clientConfig) if err != nil { return "", err } cp := &DOCloudPather{ clientConfig: clientConfig, clientset: clientset, output: writer, } fmt.Fprintf(writer, "opening %s %s (namespace %s)\n", typ, name, namespace) path, err := cloudPatherByType(ctx, cp, typ, namespace, name) if err != nil { return "", err } return path, nil } func cloudPatherByType(ctx context.Context, cp CloudPather, typ, namespace, name string) (string, error) { // cluster is the only type that doesn't take a name if typ == "cluster" { return cp.Cluster(ctx) } if name == "" { return "", ErrMissingArgument } switch typ { case "nodes": fallthrough case "node": fallthrough case "no": return cp.Node(ctx, name) case "services": fallthrough case "service": fallthrough case "svc": return cp.Service(ctx, namespace, name) case "persistentvolume": fallthrough case "persistentvolumes": fallthrough case "pv": return cp.PersistentVolume(ctx, name) case "persistentvolumeclaim": fallthrough case "persistentvolumeclaims": fallthrough case "pvc": return cp.PersistentVolumeClaim(ctx, namespace, name) default: return "", fmt.Errorf("unknown type %s", typ) } }
package main import ( "fmt" "time" "github.com/eapache/go-resiliency/retrier" ) func main() { n := 0 r := retrier.New(retrier.ConstantBackoff(3, 1*time.Second), nil) err := r.Run(func() error { fmt.Println("Attempt: ", n) n++ return fmt.Errorf("Failed") }) if err != nil { fmt.Println(err) } }
package ionic import ( "bytes" "encoding/json" "fmt" "github.com/ion-channel/ionic/aliases" "github.com/ion-channel/ionic/pagination" "github.com/ion-channel/ionic/projects" "github.com/ion-channel/ionic/requests" "github.com/ion-channel/ionic/tags" "io" "mime/multipart" "net/http" "net/url" "os" "reflect" "regexp" "strconv" "strings" "time" ) const ( validEmailRegex = `(?i)^[a-z0-9._%+\-]+@[a-z0-9.\-]+\.[a-z]{2,}$` validGitURIRegex = `^(?:(?:http|ftp|gopher|mailto|mid|cid|news|nntp|prospero|telnet|rlogin|tn3270|wais|svn|git|rsync)+\+ssh\:\/\/|git\+https?:\/\/|git\@|(?:http|ftp|gopher|mailto|mid|cid|news|nntp|prospero|telnet|rlogin|tn3270|wais|svn|git|rsync|ssh|file|s3)+s?:\/\/)[^\s]+$` validDockerURIRegex = `[a-z0-9]+(?:[._-][a-z0-9]+)*` ) var ( // ErrInvalidProject is returned when a given project does not pass the // standards for a project ErrInvalidProject = fmt.Errorf("project has invalid fields") ) // Project is a representation of a project within the Ion Channel system type Project struct { ID *string `json:"id,omitempty"` TeamID *string `json:"team_id,omitempty"` RulesetID *string `json:"ruleset_id,omitempty"` Name *string `json:"name,omitempty"` Type *string `json:"type,omitempty"` Source *string `json:"source,omitempty"` Branch *string `json:"branch,omitempty"` Description *string `json:"description,omitempty"` Active bool `json:"active"` Draft bool `json:"draft"` ChatChannel string `json:"chat_channel"` CreatedAt time.Time `json:"created_at"` UpdatedAt time.Time `json:"updated_at"` DeployKey string `json:"deploy_key"` Monitor bool `json:"should_monitor"` MonitorFrequency string `json:"monitor_frequency"` POCName string `json:"poc_name"` POCEmail string `json:"poc_email"` Username string `json:"username"` Password string `json:"password"` KeyFingerprint string `json:"key_fingerprint"` Private bool `json:"private"` Aliases []aliases.Alias `json:"aliases"` Tags []tags.Tag `json:"tags"` RulesetHistory []ProjectRulesetHistory `json:"ruleset_history"` SoftwareListID string `json:"sbom_id"` ComponentID string `json:"sbom_entry_id"` CPE string `json:"cpe"` PURL string `json:"purl"` } // RulesetID represents a ruleset ID type RulesetID struct { RulesetID string `json:"ruleset_id"` } // Name represents a single project name and id type Name struct { ID string `json:"project_id"` Name string `json:"name"` ProductName string `json:"product_name"` Version string `json:"version"` Org string `json:"org"` } // String returns a JSON formatted string of the project object func (p Project) String() string { b, err := json.Marshal(p) if err != nil { return fmt.Sprintf("failed to format project: %v", err.Error()) } return string(b) } // ProjectReachable checks if the artifact URL is reachable func (p *Project) ProjectReachable(client http.Client) (map[string]string, error) { invalidFields := make(map[string]string) var projErr error if p.Type != nil { switch strings.ToLower(*p.Type) { case "artifact": u, err := url.Parse(*p.Source) if err != nil { invalidFields["source"] = fmt.Sprintf("source must be a valid url: %v", err.Error()) projErr = ErrInvalidProject } if u != nil { res, err := client.Head(u.String()) if err != nil { invalidFields["source"] = "source failed to return a response" projErr = ErrInvalidProject } if res != nil && res.StatusCode == http.StatusNotFound { invalidFields["source"] = "source returned a not found" projErr = ErrInvalidProject } } case "git", "svn", "s3": r := regexp.MustCompile(validGitURIRegex) if p.Source != nil && !r.MatchString(strings.ToLower(*p.Source)) { invalidFields["source"] = "source must be a valid uri" projErr = ErrInvalidProject } case "docker": r := regexp.MustCompile(validDockerURIRegex) if p.Source != nil && !r.MatchString(*p.Source) { invalidFields["source"] = "source must be a docker image name" projErr = ErrInvalidProject } case "source_unavailable": if p.Source != nil && len(*p.Source) > 0 { invalidFields["source"] = "source cannot be specified for this project type" projErr = ErrInvalidProject } default: invalidFields["type"] = "invalid type value" projErr = ErrInvalidProject } } return invalidFields, projErr } // ValidateRequiredFields verifies the project contains the fields required func (p *Project) ValidateRequiredFields() (map[string]string, error) { invalidFields := make(map[string]string) var projErr error if p.TeamID == nil { invalidFields["team_id"] = "missing team id" projErr = ErrInvalidProject } if p.RulesetID == nil { invalidFields["ruleset_id"] = "missing ruleset id" projErr = ErrInvalidProject } if p.Name == nil { invalidFields["name"] = "missing name" projErr = ErrInvalidProject } if p.Type == nil { invalidFields["type"] = "missing type" projErr = ErrInvalidProject } if p.Source == nil && (p.Type != nil && strings.ToLower(*p.Type) != "source_unavailable") { invalidFields["source"] = "missing source" projErr = ErrInvalidProject } if p.Branch == nil && p.Type != nil && strings.ToLower(*p.Type) == "git" { invalidFields["branch"] = "missing branch" projErr = ErrInvalidProject } if p.Description == nil { invalidFields["description"] = "missing description" projErr = ErrInvalidProject } p.POCEmail = strings.TrimSpace(p.POCEmail) r := regexp.MustCompile(validEmailRegex) if p.POCEmail != "" && !r.MatchString(p.POCEmail) { invalidFields["poc_email"] = "invalid email supplied" projErr = ErrInvalidProject } if p.Type != nil { switch strings.ToLower(*p.Type) { case "artifact": _, err := url.Parse(*p.Source) if err != nil { invalidFields["source"] = fmt.Sprintf("source must be a valid url: %v", err.Error()) projErr = ErrInvalidProject } case "git", "svn", "s3": r := regexp.MustCompile(validGitURIRegex) if p.Source != nil && !r.MatchString(strings.ToLower(*p.Source)) { invalidFields["source"] = "source must be a valid uri" projErr = ErrInvalidProject } case "docker": r := regexp.MustCompile(validDockerURIRegex) if p.Source != nil && !r.MatchString(*p.Source) { invalidFields["source"] = "source must be a docker image name" projErr = ErrInvalidProject } case "source_unavailable": if p.Source != nil && len(*p.Source) > 0 { invalidFields["source"] = "source cannot be specified for this project type" projErr = ErrInvalidProject } default: invalidFields["type"] = "invalid type value" projErr = ErrInvalidProject } } return invalidFields, projErr } // Validate takes an http client; returns a slice of fields as a string and // an error. The fields will be a list of fields that did not pass the // validation. An error will only be returned if any of the fields fail their // validation. // Since this also checks for project reachability, ValidateRequiredFields // can be used to skip that check. func (p *Project) Validate(client http.Client) (map[string]string, error) { invalidFields := make(map[string]string) var projErr error if p.TeamID == nil { invalidFields["team_id"] = "missing team id" projErr = ErrInvalidProject } if p.RulesetID == nil { invalidFields["ruleset_id"] = "missing ruleset id" projErr = ErrInvalidProject } if p.Name == nil { invalidFields["name"] = "missing name" projErr = ErrInvalidProject } if p.Type == nil { invalidFields["type"] = "missing type" projErr = ErrInvalidProject } if p.Source == nil && (p.Type != nil && strings.ToLower(*p.Type) != "source_unavailable") { invalidFields["source"] = "missing source" projErr = ErrInvalidProject } if p.Branch == nil && p.Type != nil && strings.ToLower(*p.Type) == "git" { invalidFields["branch"] = "missing branch" projErr = ErrInvalidProject } if p.Description == nil { invalidFields["description"] = "missing description" projErr = ErrInvalidProject } p.POCEmail = strings.TrimSpace(p.POCEmail) r := regexp.MustCompile(validEmailRegex) if p.POCEmail != "" && !r.MatchString(p.POCEmail) { invalidFields["poc_email"] = "invalid email supplied" projErr = ErrInvalidProject } if p.Type != nil { switch strings.ToLower(*p.Type) { case "artifact": u, err := url.Parse(*p.Source) if err != nil { invalidFields["source"] = fmt.Sprintf("source must be a valid url: %v", err.Error()) projErr = ErrInvalidProject } if u != nil { res, err := client.Head(u.String()) if err != nil { invalidFields["source"] = "artifact source failed to return a response" projErr = ErrInvalidProject } if res != nil && res.StatusCode == http.StatusNotFound { invalidFields["source"] = fmt.Sprintf("artifact source of %v returned a 404 (not found)", *p.Source) projErr = ErrInvalidProject } } case "git", "svn", "s3": r := regexp.MustCompile(validGitURIRegex) if p.Source != nil && !r.MatchString(strings.ToLower(*p.Source)) { invalidFields["source"] = "source must be a valid uri" projErr = ErrInvalidProject } case "docker": r := regexp.MustCompile(validDockerURIRegex) if p.Source != nil && !r.MatchString(*p.Source) { invalidFields["source"] = "source must be a docker image name" projErr = ErrInvalidProject } case "source_unavailable": if p.Source != nil && len(*p.Source) > 0 { invalidFields["source"] = "source cannot be specified for this project type" projErr = ErrInvalidProject } default: invalidFields["type"] = "invalid type value" projErr = ErrInvalidProject } } return invalidFields, projErr } // ProjectFilter represents the available fields to filter a get project request // with. type ProjectFilter struct { // ID filters on a single ID ID *string `sql:"id"` // IDs filters on one or more IDs IDs *[]string `sql:"id"` TeamID *string `sql:"team_id"` SoftwareListID *string `sql:"sbom_id"` ComponentIDs *[]string `sql:"sbom_entry_id"` Source *string `sql:"source"` Type *string `sql:"type"` Active *bool `sql:"active"` Draft *bool `sql:"draft"` Monitor *bool `sql:"should_monitor"` } // ParseParam takes a param string, breaks it apart, and repopulates it into a // struct for further use. Any invalid or incomplete interpretations of a field // will be ignored and only valid entries put into the struct. func ParseParam(param string) ProjectFilter { pf := ProjectFilter{} fvs := strings.Split(param, ",") for ii := range fvs { parts := strings.SplitN(fvs[ii], ":", 2) if len(parts) != 2 { continue } name := parts[0] value := parts[1] field := reflect.ValueOf(&pf).Elem().FieldByNameFunc(func(n string) bool { return strings.ToLower(n) == strings.ToLower(name) }) if !field.IsValid() { continue } kind := field.Type().Kind() if kind == reflect.Ptr { kind = field.Type().Elem().Kind() } switch kind { case reflect.String: field.Set(reflect.ValueOf(&value)) case reflect.Bool: value, err := strconv.ParseBool(value) if err != nil { continue } field.Set(reflect.ValueOf(&value)) case reflect.Slice: value := strings.Split(value, " ") field.Set(reflect.ValueOf(&value)) default: // shouldn't ever happen, but just in case continue } } return pf } // Param converts the non nil fields of the Project ProjectFilter into a string usable // for URL query params. func (pf *ProjectFilter) Param() string { ps := make([]string, 0) // get the fields and values of the underlying ProjectFilter (Elem dereferences the pointer) fields := reflect.TypeOf(pf).Elem() values := reflect.ValueOf(pf).Elem() for i := 0; i < fields.NumField(); i++ { value := values.Field(i) if value.IsNil() { continue } if value.Kind() == reflect.Ptr { value = value.Elem() } name := fields.Field(i).Name switch value.Kind() { case reflect.String: ps = append(ps, fmt.Sprintf("%v:%v", name, value.String())) case reflect.Bool: ps = append(ps, fmt.Sprintf("%v:%v", name, value.Bool())) case reflect.Slice: // elements of the slice are separated by spaces: // example: IDs:abc def ghi sliceLen := value.Len() if sliceLen == 0 { continue } valueStr := strings.Join(value.Interface().([]string), " ") valueStr = fmt.Sprintf("%v:%v", name, valueStr) ps = append(ps, valueStr) } } return strings.Join(ps, ",") } // ProjectSliceContains checks if a given []Project contains a Project matching the given Project. // This is used to prevent duplicate Projects from appearing in a slice of Projects. // Returns true if the given Project has an alias that matches an alias of any other project in the slice. func ProjectSliceContains(projects []Project, projectToFind Project) bool { for _, project := range projects { for _, alias := range project.Aliases { for _, aliasToFind := range projectToFind.Aliases { if alias.Equal(aliasToFind) { return true } } } } return false } // CreateProjectsResponse represents the response from the API when sending a // list of projects to be created. It contains the details of each project // created, and a list of any errors that were encountered. type CreateProjectsResponse struct { Projects []Project `json:"projects"` Errors []struct { Message string `json:"message"` } `json:"errors"` } // CreateProject takes a project object, teamId, and token to use. It returns the // project stored or an error encountered by the API func (ic *IonClient) CreateProject(project *Project, teamID, token string) (*Project, error) { params := url.Values{} params.Set("team_id", teamID) b, err := json.Marshal(project) if err != nil { return nil, fmt.Errorf("failed to marshall project: %v", err.Error()) } b, err = ic.Post(projects.CreateProjectEndpoint, token, params, *bytes.NewBuffer(b), nil) if err != nil { return nil, fmt.Errorf("failed to create project: %v", err.Error()) } var p Project err = json.Unmarshal(b, &p) if err != nil { return nil, fmt.Errorf("failed to read response from create: %v", err.Error()) } return &p, nil } // CreateProjectsFromCSV takes a csv file location, team ID, and token to send // the specified file to the API. All projects that are able to be created will // be with their info returned, and a list of any errors encountered during the // process. func (ic *IonClient) CreateProjectsFromCSV(csvFile, teamID, token string) (*CreateProjectsResponse, error) { params := url.Values{} params.Set("team_id", teamID) var buf bytes.Buffer w := multipart.NewWriter(&buf) fw, err := w.CreateFormFile("file", csvFile) if err != nil { return nil, fmt.Errorf("failed to create form file: %v", err.Error()) } fh, err := os.Open(csvFile) if err != nil { return nil, fmt.Errorf("failed to open file: %v", err.Error()) } _, err = io.Copy(fw, fh) if err != nil { return nil, fmt.Errorf("failed to copy file contents: %v", err.Error()) } w.Close() h := http.Header{} h.Set("Content-Type", w.FormDataContentType()) b, err := ic.Post(projects.CreateProjectsFromCSVEndpoint, token, params, buf, h) if err != nil { return nil, fmt.Errorf("failed to create projects: %v", err.Error()) } var resp CreateProjectsResponse err = json.Unmarshal(b, &resp) if err != nil { return nil, fmt.Errorf("failed to read response: %v", err.Error()) } return &resp, nil } // GetProject takes a project ID, team ID, and token. It returns the project and // an error if it receives a bad response from the API or fails to unmarshal the // JSON response from the API. func (ic *IonClient) GetProject(id, teamID, token string) (*Project, error) { params := url.Values{} params.Set("id", id) params.Set("team_id", teamID) b, _, err := ic.Get(projects.GetProjectEndpoint, token, params, nil, pagination.Pagination{}) if err != nil { return nil, fmt.Errorf("failed to get project: %v", err.Error()) } var p Project err = json.Unmarshal(b, &p) if err != nil { return nil, fmt.Errorf("failed to get project: %v", err.Error()) } return &p, nil } // GetRawProject takes a project ID, team ID, and token. It returns the raw json of the // project. It also returns any API errors it may encounter. func (ic *IonClient) GetRawProject(id, teamID, token string) (json.RawMessage, error) { params := url.Values{} params.Set("id", id) params.Set("team_id", teamID) b, _, err := ic.Get(projects.GetProjectEndpoint, token, params, nil, pagination.Pagination{}) if err != nil { return nil, fmt.Errorf("failed to get project: %v", err.Error()) } return b, nil } // GetProjects takes a project filter and returns a slice of the projects matching that filter, or an error. func (ic *IonClient) GetProjects(filter ProjectFilter, token string, page pagination.Pagination) ([]Project, error) { params := url.Values{} params.Set("filter_by", filter.Param()) b, _, err := ic.Get(projects.GetProjectsEndpoint, token, params, nil, page) if err != nil { return nil, fmt.Errorf("failed to get projects: %v", err.Error()) } var pList []Project err = json.Unmarshal(b, &pList) if err != nil { return nil, fmt.Errorf("failed to unmarshal projects: %v", err.Error()) } return pList, nil } // GetProjectByURL takes a uri, teamID, and API token to request the noted // project from the API. It returns the project and any errors it encounters // with the API. func (ic *IonClient) GetProjectByURL(uri, teamID, token string) (*Project, error) { params := url.Values{} params.Set("url", uri) params.Set("team_id", teamID) b, _, err := ic.Get(projects.GetProjectByURLEndpoint, token, params, nil, pagination.Pagination{}) if err != nil { return nil, fmt.Errorf("failed to get projects by url: %v", err.Error()) } var p Project err = json.Unmarshal(b, &p) if err != nil { return nil, fmt.Errorf("failed to unmarshal projects: %v", err.Error()) } return &p, nil } // UpdateProject takes a project to update and token to use. It returns the // project stored or an error encountered by the API func (ic *IonClient) UpdateProject(project *Project, token string) (*Project, error) { params := url.Values{} if project.ID == nil { return nil, fmt.Errorf("%v: %v", ErrInvalidProject, "missing id") } b, err := json.Marshal(project) if err != nil { return nil, fmt.Errorf("failed to marshall project: %v", err.Error()) } b, err = ic.Put(projects.UpdateProjectEndpoint, token, params, *bytes.NewBuffer(b), nil) if err != nil { return nil, fmt.Errorf("failed to update projects: %v", err.Error()) } var p Project err = json.Unmarshal(b, &p) if err != nil { return nil, fmt.Errorf("failed to read response from update: %v", err.Error()) } return &p, nil } // GetUsedRulesetIds takes a team ID and returns rulesets used by all projects in that team func (ic *IonClient) GetUsedRulesetIds(teamID, token string) ([]RulesetID, error) { params := url.Values{} params.Set("team_id", teamID) b, _, err := ic.Get(projects.GetUsedRulesetIdsEndpoint, token, params, nil, pagination.Pagination{}) if err != nil { return nil, fmt.Errorf("failed to get team's ruleset ids: %v", err.Error()) } var rList []RulesetID err = json.Unmarshal(b, &rList) if err != nil { return nil, fmt.Errorf("failed to unmarshal team's ruleset ids: %v", err.Error()) } return rList, nil } // GetProjectsNames takes a team ID and slice of project ids. it returns slice of project ids, and project names func (ic *IonClient) GetProjectsNames(teamID string, ids []string, token string) ([]Name, error) { p := requests.ByIDsAndTeamID{ TeamID: teamID, IDs: ids, } b, err := json.Marshal(p) if err != nil { return nil, fmt.Errorf("failed to marshal request body: %v", err.Error()) } r, err := ic.Post(projects.GetProjectsNamesEndpoint, token, nil, *bytes.NewBuffer(b), nil) if err != nil { return nil, fmt.Errorf("failed to get projects names and versions: %v", err.Error()) } var list []Name err = json.Unmarshal(r, &list) if err != nil { return nil, fmt.Errorf("failed to unmarshal projects names: %v", err.Error()) } return list, nil }
package DCP import ( "encoding/csv" "encoding/json" "fmt" "github.com/google/uuid" "math/big" "math/rand" "os" "strconv" "testing" "time" ) func TestCalculationObjectPaillier_KeyGen(t *testing.T) { nodes := make([]CtNode, 10) for _, node := range nodes { node = CtNode{ Id: uuid.New(), Co: &CalculationObjectPaillier{}, Ids: nil, HandledBranchIds: nil, } e := node.Co.KeyGen() if e != nil { fmt.Println(e.Error()) t.Fail() } } } func TestCalculationObjectPaillier_Encrypt(t *testing.T) { node := CtNode{ Id: uuid.New(), Co: &CalculationObjectPaillier{}, Ids: nil, HandledBranchIds: nil, } e := node.Co.KeyGen() if e != nil { fmt.Println(e.Error()) t.Fail() } c, e := node.Co.Encrypt(24) if e != nil { fmt.Print(e.Error()) t.Fail() } decrypted := node.Co.Decrypt(c) if decrypted.Cmp(big.NewInt(24)) != 0 { t.Fail() } } func TestCalculationObjectPaillier_Json(t *testing.T) { co := &CalculationObjectPaillier{ Id: uuid.UUID{}, Counter: 10, privateKey: nil, PublicKey: nil, Cipher: nil, } _ = co.KeyGen() co.Cipher, _ = co.Encrypt(16) serialized, _ := json.Marshal(co) var deserialized CalculationObjectPaillier e := json.Unmarshal(serialized, &deserialized) if e != nil { t.Fail() } if deserialized.Counter != 10 { t.Fail() } decryptedCipher := co.Decrypt(deserialized.Cipher) if decryptedCipher.String() != "16" { t.Fail() } } func TestCalculationObjectGrowth(t *testing.T) { var values [][]string co := &CalculationObjectPaillier{ Id: uuid.UUID{}, Counter: 0, privateKey: nil, PublicKey: nil, Cipher: nil, } _ = co.KeyGen() b, _ := json.Marshal(co) values = append(values, []string{strconv.Itoa(co.Counter), strconv.Itoa(len(b))}) rand.Seed(time.Now().UnixNano()) for i := 0; i < 100000; i++ { c, _ := co.Encrypt(rand.Intn(100-1)+1) co.Add(c) co.Counter = co.Counter + 1 b, _ := json.Marshal(co) values = append(values, []string{strconv.Itoa(co.Counter), strconv.Itoa(len(b))}) } w := csv.NewWriter(os.Stdout) defer w.Flush() headers := []string{"Counter", "Size"} if err := w.Write(headers); err != nil { panic(err.Error()) } for _, value := range values { err := w.Write(value) if err != nil { panic(err.Error()) } } }
package octopus import ( "strconv" "testing" ) func Test_CachedWorkerPool(t *testing.T) { pool, _ := NewCachedWorkerPool() f, err := pool.SubmitCallable(func () interface{} { t.Log("Hi") return "Hi, result" }) if err != nil { t.Error(err) } v, _ := f.Get() t.Log(v) pool.SubmitRunnable(func () { t.Log("Hello") }) var r Runnable = func() { t.Log("test Runnable var") } pool.SubmitRunnable(r) r2 := func() { t.Log("test Runnable var 2") } pool.SubmitRunnable(r2) for i:=0; i<30; i++ { pool.SubmitCallable(func() interface{} { t.Log("num: ", i) return i }) } // wait for all goroutine done pool.Shutdown() } func Test_CachedDataProcessPool (t *testing.T) { pool, _ := NewCachedDataProcessPool(func (object interface{}) interface{} { v := object.(string) return v+" end" }) f, err := pool.Submit("test1") if err != nil { t.Error(err) } v, _ := f.Get() t.Log(v) for i:=0; i<30; i++ { f, err := pool.Submit(strconv.Itoa(i)) if err != nil { t.Error(err) } v, _ := f.Get() t.Log(v) } pool.Shutdown() }
package main func main() { } func buildTree(preorder []int, inorder []int) *TreeNode { if len(preorder) == 0 { return nil } root := &TreeNode{preorder[0], nil, nil} var stack []*TreeNode stack = append(stack, root) var inorderIndex int for i := 1; i < len(preorder); i++ { preorderVal := preorder[i] node := stack[len(stack)-1] if node.Val != inorder[inorderIndex] { node.Left = &TreeNode{preorderVal, nil, nil} stack = append(stack, node.Left) } else { for len(stack) != 0 && stack[len(stack)-1].Val == inorder[inorderIndex] { node = stack[len(stack)-1] stack = stack[:len(stack)-1] inorderIndex++ } node.Right = &TreeNode{preorderVal, nil, nil} stack = append(stack, node.Right) } } return root }
package jarviscore import ( "context" "io" "sync" "time" "google.golang.org/grpc/codes" "github.com/zhs007/jarviscore/coredb" coredbpb "github.com/zhs007/jarviscore/coredb/proto" "go.uber.org/zap" jarvisbase "github.com/zhs007/jarviscore/base" pb "github.com/zhs007/jarviscore/proto" "google.golang.org/grpc" "google.golang.org/grpc/status" ) type clientTask struct { jarvisbase.L2BaseTask servaddr string addr string client *jarvisClient2 msg *pb.JarvisMsg msgs []*pb.JarvisMsg node *coredbpb.NodeInfo funcOnResult FuncOnProcMsgResult } func (task *clientTask) Run(ctx context.Context) error { if task.msgs != nil { err := task.client._sendMsgStream(ctx, task.addr, task.msgs, task.funcOnResult) if err != nil && task.node != nil { if err == ErrServAddrIsMe || err == ErrInvalidServAddr { task.client.node.mgrEvent.onNodeEvent(ctx, EventOnDeprecateNode, task.node) } task.client.node.mgrEvent.onNodeEvent(ctx, EventOnIConnectNodeFail, task.node) } return err } if task.msg != nil { err := task.client._sendMsg(ctx, task.msg, task.funcOnResult) if err != nil && task.node != nil { if err == ErrServAddrIsMe || err == ErrInvalidServAddr { task.client.node.mgrEvent.onNodeEvent(ctx, EventOnDeprecateNode, task.node) } task.client.node.mgrEvent.onNodeEvent(ctx, EventOnIConnectNodeFail, task.node) } return err } err := task.client._connectNode(ctx, task.servaddr, task.node, task.funcOnResult) if err != nil && task.node != nil { if err == ErrServAddrIsMe || err == ErrInvalidServAddr { task.client.node.mgrEvent.onNodeEvent(ctx, EventOnDeprecateNode, task.node) } task.client.node.mgrEvent.onNodeEvent(ctx, EventOnIConnectNodeFail, task.node) } if err != nil { if task.node != nil { jarvisbase.Warn("clientTask.Run:_connectNode", zap.Error(err), zap.String("servaddr", task.servaddr), jarvisbase.JSON("node", task.node)) } else { jarvisbase.Warn("clientTask.Run:_connectNode", zap.Error(err), zap.String("servaddr", task.servaddr)) } } task.client.onConnTaskEnd(task.servaddr) return err } // // GetParentID - get parentID // func (task *clientTask) GetParentID() string { // if task.msg == nil { // return task.addr // } // return "" // } type clientInfo2 struct { conn *grpc.ClientConn client pb.JarvisCoreServClient servAddr string } // jarvisClient2 - type jarvisClient2 struct { poolMsg jarvisbase.L2RoutinePool poolConn jarvisbase.RoutinePool node *jarvisNode mapClient sync.Map fsa *failservaddr mapConnServAddr sync.Map } func newClient2(node *jarvisNode) *jarvisClient2 { return &jarvisClient2{ node: node, poolConn: jarvisbase.NewRoutinePool(), poolMsg: jarvisbase.NewL2RoutinePool(), fsa: newFailServAddr(), } } // BuildStatus - build status func (c *jarvisClient2) BuildNodeStatus(ns *pb.JarvisNodeStatus) { ns.MsgPool = c.poolMsg.BuildStatus() c.mapClient.Range(func(key, v interface{}) bool { addr, keyok := key.(string) // ci, vok := v.(*clientInfo2) if keyok { ni := c.node.GetCoreDB().GetNode(addr) if ni != nil { nbi := &pb.NodeBaseInfo{ ServAddr: ni.ServAddr, Addr: ni.Addr, Name: ni.Name, NodeTypeVersion: ni.NodeTypeVersion, NodeType: ni.NodeType, CoreVersion: ni.CoreVersion, } ns.LstConnected = append(ns.LstConnected, nbi) } } return true }) } // start - start goroutine to proc client task func (c *jarvisClient2) start(ctx context.Context) error { go c.poolConn.Start(ctx, 128) go c.poolMsg.Start(ctx, 128) <-ctx.Done() return nil } // onConnTaskEnd - on ConnTask end func (c *jarvisClient2) onConnTaskEnd(servaddr string) { c.mapConnServAddr.Delete(servaddr) } // addConnTask - add a client task func (c *jarvisClient2) addConnTask(servaddr string, node *coredbpb.NodeInfo, funcOnResult FuncOnProcMsgResult) { _, ok := c.mapConnServAddr.Load(servaddr) if ok { return } c.mapConnServAddr.Store(servaddr, 0) task := &clientTask{ servaddr: servaddr, client: c, node: node, funcOnResult: funcOnResult, } c.poolConn.SendTask(task) } // addSendMsgTask - add a client send message task func (c *jarvisClient2) addSendMsgTask(msg *pb.JarvisMsg, addr string, funcOnResult FuncOnProcMsgResult) { task := &clientTask{ msg: msg, client: c, funcOnResult: funcOnResult, addr: addr, } task.Init(c.poolMsg, addr) c.poolMsg.SendTask(task) } // addSendMsgStreamTask - add a client send message stream task func (c *jarvisClient2) addSendMsgStreamTask(msgs []*pb.JarvisMsg, addr string, funcOnResult FuncOnProcMsgResult) { task := &clientTask{ msgs: msgs, client: c, funcOnResult: funcOnResult, addr: addr, } task.Init(c.poolMsg, addr) c.poolMsg.SendTask(task) } func (c *jarvisClient2) isConnected(addr string) bool { _, ok := c.mapClient.Load(addr) return ok } func (c *jarvisClient2) _getClientConn(addr string) *clientInfo2 { mi, ok := c.mapClient.Load(addr) if ok { ci, typeok := mi.(*clientInfo2) if typeok { return ci } } return nil } func (c *jarvisClient2) _deleteClientConn(addr string) { c.mapClient.Delete(addr) curnode := c.node.FindNode(addr) if curnode != nil { mgrConn.delConn(curnode.ServAddr) } } func (c *jarvisClient2) _getValidClientConn(addr string) (*clientInfo2, error) { ci := c._getClientConn(addr) if ci != nil { if mgrConn.isValidConn(ci.servAddr) { return ci, nil } } cn := c.node.GetCoreDB().GetNode(addr) if cn == nil { jarvisbase.Warn("jarvisClient2.getValidClientConn:GetNode", zap.Error(ErrCannotFindNodeWithAddr)) return nil, ErrCannotFindNodeWithAddr } conn, err := mgrConn.getConn(cn.ServAddr) if err != nil { jarvisbase.Warn("jarvisClient2.getValidClientConn", zap.Error(err)) return nil, err } nci := &clientInfo2{ conn: conn, client: pb.NewJarvisCoreServClient(conn), servAddr: cn.ServAddr, } c.mapClient.Store(addr, nci) return nci, nil } func (c *jarvisClient2) _sendMsg(ctx context.Context, smsg *pb.JarvisMsg, funcOnResult FuncOnProcMsgResult) error { // var lstResult []*JarvisMsgInfo newsendmsgid := c._getNewSendMsgID(smsg.DestAddr) destaddr := smsg.DestAddr if funcOnResult != nil { // jarvisbase.Info("jarvisClient2._sendMsg:OnClientProcMsg", // JSONMsg2Zap("msg", smsg), // zap.Int64("newsendmsgid", newsendmsgid)) err := c.node.OnClientProcMsg(destaddr, newsendmsgid, funcOnResult) if err != nil { jarvisbase.Warn("jarvisClient2._sendMsg:OnClientProcMsg", zap.Error(err), JSONMsg2Zap("msg", smsg), zap.Int64("newsendmsgid", newsendmsgid)) } c.node.OnReplyProcMsg(ctx, destaddr, newsendmsgid, JarvisResultTypeSend, nil, nil) } _, ok := c.mapClient.Load(smsg.DestAddr) if !ok { jarvisbase.Warn("jarvisClient2._sendMsg:mapClient", zap.Error(ErrNotConnectedNode), JSONMsg2Zap("msg", smsg)) if funcOnResult != nil { c.node.OnReplyProcMsg(ctx, destaddr, newsendmsgid, JarvisResultTypeLocalError, nil, ErrNotConnectedNode) } } jarvisbase.Debug("jarvisClient2._sendMsg", JSONMsg2Zap("msg", smsg)) ci2, err := c._getValidClientConn(smsg.DestAddr) if err != nil { jarvisbase.Warn("jarvisClient2._sendMsg:getValidClientConn", zap.Error(err)) if funcOnResult != nil { c.node.OnReplyProcMsg(ctx, destaddr, newsendmsgid, JarvisResultTypeLocalErrorEnd, nil, err) } return err } err = c._signJarvisMsg(smsg, newsendmsgid, 0) if err != nil { jarvisbase.Warn("jarvisClient2._sendMsg:_signJarvisMsg", zap.Error(err)) if funcOnResult != nil { c.node.OnReplyProcMsg(ctx, destaddr, newsendmsgid, JarvisResultTypeLocalErrorEnd, nil, err) } return err } stream, err := ci2.client.ProcMsg(ctx, smsg) if err != nil { grpcerr, ok := status.FromError(err) if ok && grpcerr.Code() == codes.Unimplemented { jarvisbase.Warn("jarvisClient2._sendMsg:ProcMsg:Unimplemented", zap.Error(err)) destnode := c.node.FindNode(destaddr) if destnode != nil { c.node.mgrEvent.onNodeEvent(ctx, EventOnDeprecateNode, destnode) } if funcOnResult != nil { c.node.OnReplyProcMsg(ctx, destaddr, newsendmsgid, JarvisResultTypeLocalErrorEnd, nil, err) } c._deleteClientConn(destaddr) return err } jarvisbase.Warn("jarvisClient2._sendMsg:ProcMsg", zap.Error(err)) if funcOnResult != nil { c.node.OnReplyProcMsg(ctx, destaddr, newsendmsgid, JarvisResultTypeLocalErrorEnd, nil, err) } return err } for { getmsg, err := stream.Recv() if err == io.EOF { jarvisbase.Debug("jarvisClient2._sendMsg:stream eof") break } if err != nil { jarvisbase.Warn("jarvisClient2._sendMsg:stream", zap.Error(err)) if funcOnResult != nil { c.node.OnReplyProcMsg(ctx, destaddr, newsendmsgid, JarvisResultTypeLocalErrorEnd, nil, err) } break } else { jarvisbase.Debug("jarvisClient2._sendMsg:stream", JSONMsg2Zap("msg", getmsg)) c.node.PostMsg(&NormalMsgTaskInfo{ Msg: getmsg, }, nil) if funcOnResult != nil { c.node.OnReplyProcMsg(ctx, destaddr, newsendmsgid, JarvisResultTypeReply, getmsg, nil) } } } return nil } func (c *jarvisClient2) _broadCastMsg(ctx context.Context, msg *pb.JarvisMsg) error { jarvisbase.Debug("jarvisClient2._broadCastMsg", JSONMsg2Zap("msg", msg)) // c.mapClient.Range(func(key, v interface{}) bool { // ci, ok := v.(*clientInfo2) // if ok { // stream, err := ci.client.ProcMsg(ctx, msg) // if err != nil { // jarvisbase.Warn("jarvisClient2._broadCastMsg:ProcMsg", zap.Error(err)) // return true // } // for { // msg, err := stream.Recv() // if err == io.EOF { // jarvisbase.Debug("jarvisClient2._broadCastMsg:stream eof") // break // } // if err != nil { // jarvisbase.Warn("jarvisClient2._broadCastMsg:stream", zap.Error(err)) // break // } else { // jarvisbase.Debug("jarvisClient2._broadCastMsg:stream", jarvisbase.JSON("msg", msg)) // c.node.mgrJasvisMsg.sendMsg(msg, nil, nil) // } // } // } // return true // }) return nil } func (c *jarvisClient2) _connectNode(ctx context.Context, servaddr string, node *coredbpb.NodeInfo, funcOnResult FuncOnProcMsgResult) error { var lstResult []*JarvisMsgInfo if node != nil { if node.Addr == c.node.myinfo.Addr { jarvisbase.Warn("jarvisClient2._connectNode:checkNodeAddr", zap.Error(ErrServAddrIsMe), zap.String("addr", c.node.myinfo.Addr), zap.String("bindaddr", c.node.myinfo.BindAddr), zap.String("servaddr", c.node.myinfo.ServAddr)) if funcOnResult != nil { lstResult = append(lstResult, &JarvisMsgInfo{ JarvisResultType: JarvisResultTypeLocalErrorEnd, Err: ErrServAddrIsMe, }) funcOnResult(ctx, c.node, lstResult) } return ErrServAddrIsMe } if coredb.IsDeprecatedNode(node) { jarvisbase.Warn("jarvisClient2._connectNode:IsDeprecatedNode", zap.Error(ErrDeprecatedNode), zap.String("addr", c.node.myinfo.Addr), zap.String("bindaddr", c.node.myinfo.BindAddr), zap.String("servaddr", c.node.myinfo.ServAddr)) if funcOnResult != nil { lstResult = append(lstResult, &JarvisMsgInfo{ JarvisResultType: JarvisResultTypeLocalErrorEnd, Err: ErrDeprecatedNode, }) funcOnResult(ctx, c.node, lstResult) } return ErrDeprecatedNode } } if !IsValidServAddr(servaddr) { jarvisbase.Warn("jarvisClient2._connectNode", zap.Error(ErrInvalidServAddr), zap.String("addr", c.node.myinfo.Addr), zap.String("servaddr", servaddr)) if funcOnResult != nil { lstResult = append(lstResult, &JarvisMsgInfo{ JarvisResultType: JarvisResultTypeLocalErrorEnd, Err: ErrInvalidServAddr, }) funcOnResult(ctx, c.node, lstResult) } return ErrInvalidServAddr } if IsMyServAddr(servaddr, c.node.myinfo.BindAddr) { jarvisbase.Warn("jarvisClient2._connectNode", zap.Error(ErrServAddrIsMe), zap.String("addr", c.node.myinfo.Addr), zap.String("bindaddr", c.node.myinfo.BindAddr), zap.String("servaddr", c.node.myinfo.ServAddr)) if funcOnResult != nil { lstResult = append(lstResult, &JarvisMsgInfo{ JarvisResultType: JarvisResultTypeLocalErrorEnd, Err: ErrServAddrIsMe, }) funcOnResult(ctx, c.node, lstResult) } return ErrServAddrIsMe } conn, err := mgrConn.getConn(servaddr) if err != nil { jarvisbase.Warn("jarvisClient2._connectNode", zap.Error(err)) if funcOnResult != nil { lstResult = append(lstResult, &JarvisMsgInfo{ JarvisResultType: JarvisResultTypeLocalErrorEnd, Err: err, }) funcOnResult(ctx, c.node, lstResult) } return err } if c.fsa.isFailServAddr(servaddr) { return ErrServAddrConnFail } curctx, cancel := context.WithCancel(ctx) defer cancel() ci := &clientInfo2{ conn: conn, client: pb.NewJarvisCoreServClient(conn), servAddr: servaddr, } nbi := &pb.NodeBaseInfo{ ServAddr: c.node.GetMyInfo().ServAddr, Addr: c.node.GetMyInfo().Addr, Name: c.node.GetMyInfo().Name, NodeType: c.node.GetMyInfo().NodeType, NodeTypeVersion: c.node.GetMyInfo().NodeTypeVersion, CoreVersion: c.node.GetMyInfo().CoreVersion, } msg, err := BuildConnNode(c.node, c.node.GetMyInfo().Addr, "", servaddr, nbi) if err != nil { jarvisbase.Warn("jarvisClient2._connectNode:BuildConnNode", zap.Error(err)) if funcOnResult != nil { lstResult = append(lstResult, &JarvisMsgInfo{ JarvisResultType: JarvisResultTypeLocalErrorEnd, Err: err, }) funcOnResult(ctx, c.node, lstResult) } return err } err = c._signJarvisMsg(msg, 0, 0) if err != nil { jarvisbase.Warn("jarvisClient2._connectNode:_signJarvisMsg", zap.Error(err)) if funcOnResult != nil { lstResult = append(lstResult, &JarvisMsgInfo{ JarvisResultType: JarvisResultTypeLocalErrorEnd, Err: err, }) funcOnResult(ctx, c.node, lstResult) } return err } stream, err1 := ci.client.ProcMsg(curctx, msg) if err1 != nil { jarvisbase.Warn("jarvisClient2._connectNode:ProcMsg", zap.Error(err1)) if funcOnResult != nil { lstResult = append(lstResult, &JarvisMsgInfo{ JarvisResultType: JarvisResultTypeLocalErrorEnd, Err: err1, }) funcOnResult(ctx, c.node, lstResult) } // err := conn.Close() // if err != nil { // jarvisbase.Warn("jarvisClient2._connectNode:Close", zap.Error(err1)) // } mgrConn.delConn(servaddr) c.fsa.onConnFail(servaddr) return err1 } for { msg, err := stream.Recv() if err == io.EOF { jarvisbase.Debug("jarvisClient2._connectNode:stream eof") // if funcOnResult != nil { // lstResult = append(lstResult, &JarvisMsgInfo{ // JarvisResultType: JarvisResultTypeReplyStreamEnd, // }) // funcOnResult(ctx, c.node, lstResult) // } break } if err != nil { grpcerr, ok := status.FromError(err) if ok && grpcerr.Code() == codes.Unimplemented { jarvisbase.Warn("jarvisClient2._connectNode:ProcMsg:Unimplemented", zap.Error(err)) if node != nil { c.node.mgrEvent.onNodeEvent(ctx, EventOnDeprecateNode, node) } if funcOnResult != nil { lstResult = append(lstResult, &JarvisMsgInfo{ JarvisResultType: JarvisResultTypeLocalErrorEnd, Err: err, }) funcOnResult(ctx, c.node, lstResult) } // err1 := conn.Close() // if err1 != nil { // jarvisbase.Warn("jarvisClient2._connectNode:Close", zap.Error(err)) // } mgrConn.delConn(servaddr) c.fsa.onConnFail(servaddr) return err } jarvisbase.Warn("jarvisClient2._connectNode:stream", zap.Error(err), zap.String("servaddr", servaddr)) if funcOnResult != nil { lstResult = append(lstResult, &JarvisMsgInfo{ JarvisResultType: JarvisResultTypeLocalErrorEnd, Err: err, }) funcOnResult(ctx, c.node, lstResult) } return err } jarvisbase.Debug("jarvisClient2._connectNode:stream", JSONMsg2Zap("msg", msg)) if msg.MsgType == pb.MSGTYPE_REPLY_CONNECT { ni := msg.GetNodeInfo() c.mapClient.Store(ni.Addr, ci) } c.node.PostMsg(&NormalMsgTaskInfo{ Msg: msg, }, nil) if funcOnResult != nil { lstResult = append(lstResult, &JarvisMsgInfo{ JarvisResultType: JarvisResultTypeReply, Msg: msg, }) funcOnResult(ctx, c.node, lstResult) } } return nil } func (c *jarvisClient2) _getNewSendMsgID(destaddr string) int64 { return c.node.GetCoreDB().GetNewSendMsgID(destaddr) } func (c *jarvisClient2) _signJarvisMsg(msg *pb.JarvisMsg, newsendmsgid int64, streamMsgIndex int) error { // if isstream { // msg.StreamMsgID = newsendmsgid // } else { msg.MsgID = newsendmsgid // } msg.StreamMsgIndex = int32(streamMsgIndex) msg.CurTime = time.Now().Unix() msg.LastMsgID = c.node.GetCoreDB().GetCurRecvMsgID(msg.DestAddr) return SignJarvisMsg(c.node.GetCoreDB().GetPrivateKey(), msg) } func (c *jarvisClient2) _procRecvMsgStream(ctx context.Context, stream pb.JarvisCoreServ_ProcMsgStreamClient, funcOnResult FuncOnProcMsgResult, chanEnd chan int, destaddr string, newsendmsgid int64) { for { getmsg, err := stream.Recv() if err == io.EOF { jarvisbase.Debug("jarvisClient2._procRecvMsgStream:stream eof") // if funcOnResult != nil { // c.node.OnReplyProcMsg(ctx, destaddr, newsendmsgid, JarvisResultTypeReplyStreamEnd, nil, nil) // } break } if err != nil { grpcerr, ok := status.FromError(err) if ok && grpcerr.Code() == codes.Unimplemented { jarvisbase.Warn("jarvisClient2._procRecvMsgStream:stream:Unimplemented", zap.Error(err)) destnode := c.node.FindNode(destaddr) if destnode != nil { c.node.mgrEvent.onNodeEvent(ctx, EventOnDeprecateNode, destnode) } if funcOnResult != nil { c.node.OnReplyProcMsg(ctx, destaddr, newsendmsgid, JarvisResultTypeLocalErrorEnd, nil, err) } c._deleteClientConn(destaddr) break // err1 := conn.Close() // if err1 != nil { // jarvisbase.Warn("jarvisClient2._procRecvMsgStream:stream:Close", zap.Error(err)) // } // mgrConn.delConn(servaddr) // c.fsa.onConnFail(servaddr) // return err } jarvisbase.Warn("jarvisClient2._procRecvMsgStream:stream", zap.Error(err)) if funcOnResult != nil { c.node.OnReplyProcMsg(ctx, destaddr, newsendmsgid, JarvisResultTypeLocalErrorEnd, nil, err) } break } else { jarvisbase.Debug("jarvisClient2._procRecvMsgStream:stream", JSONMsg2Zap("msg", getmsg)) c.node.PostMsg(&NormalMsgTaskInfo{ Msg: getmsg, }, nil) if funcOnResult != nil { c.node.OnReplyProcMsg(ctx, destaddr, newsendmsgid, JarvisResultTypeReply, getmsg, nil) } } } chanEnd <- 0 } func (c *jarvisClient2) _sendMsgStream(ctx context.Context, destAddr string, smsgs []*pb.JarvisMsg, funcOnResult FuncOnProcMsgResult) error { newsendmsgid := c._getNewSendMsgID(destAddr) destaddr := smsgs[0].DestAddr if funcOnResult != nil { // jarvisbase.Info("jarvisClient2._sendMsgStream:OnClientProcMsg", // zap.String("destaddr", destaddr), // zap.Int64("newsendmsgid", newsendmsgid)) err := c.node.OnClientProcMsg(destaddr, newsendmsgid, funcOnResult) if err != nil { jarvisbase.Warn("jarvisClient2._sendMsgStream:OnClientProcMsg", zap.Error(err), zap.String("destaddr", destaddr), zap.Int64("newsendmsgid", newsendmsgid)) } } // var lstResult []*JarvisMsgInfo _, ok := c.mapClient.Load(destAddr) if !ok { jarvisbase.Warn("jarvisClient2._sendMsgStream:mapClient", zap.Error(ErrNotConnectedNode), zap.String("destAddr", destAddr), zap.String("myaddr", c.node.GetMyInfo().Addr)) if funcOnResult != nil { c.node.OnReplyProcMsg(ctx, destaddr, newsendmsgid, JarvisResultTypeLocalError, nil, ErrNotConnectedNode) } } ci2, err := c._getValidClientConn(destAddr) if err != nil { jarvisbase.Warn("jarvisClient2._sendMsgStream:getValidClientConn", zap.Error(err)) if funcOnResult != nil { c.node.OnReplyProcMsg(ctx, destaddr, newsendmsgid, JarvisResultTypeLocalErrorEnd, nil, err) } return err } chanEnd := make(chan int) stream, err := ci2.client.ProcMsgStream(ctx) if err != nil { jarvisbase.Warn("jarvisClient2._sendMsgStream:ProcMsgStream", zap.Error(err)) if funcOnResult != nil { c.node.OnReplyProcMsg(ctx, destaddr, newsendmsgid, JarvisResultTypeLocalErrorEnd, nil, err) } return err } if stream == nil { jarvisbase.Warn("jarvisClient2._sendMsgStream:ProcMsgStream", zap.Error(ErrProcMsgStreamNil)) if funcOnResult != nil { c.node.OnReplyProcMsg(ctx, destaddr, newsendmsgid, JarvisResultTypeLocalErrorEnd, nil, ErrProcMsgStreamNil) } return err } go c._procRecvMsgStream(ctx, stream, funcOnResult, chanEnd, destaddr, newsendmsgid) for i := 0; i < len(smsgs); i++ { err := c._signJarvisMsg(smsgs[i], newsendmsgid, i) if err != nil { jarvisbase.Warn("jarvisClient2._sendMsgStream:_signJarvisMsg", zap.Error(err)) if funcOnResult != nil { c.node.OnReplyProcMsg(ctx, destaddr, newsendmsgid, JarvisResultTypeLocalErrorEnd, nil, err) } return err } err = stream.Send(smsgs[i]) if err != nil { jarvisbase.Warn("jarvisClient2._sendMsgStream:ProcMsg", zap.Error(err)) if funcOnResult != nil { c.node.OnReplyProcMsg(ctx, destaddr, newsendmsgid, JarvisResultTypeLocalErrorEnd, nil, err) } return err } } err = stream.CloseSend() if err != nil { jarvisbase.Warn("jarvisClient2._sendMsgStream:CloseSend", zap.Error(err)) if funcOnResult != nil { c.node.OnReplyProcMsg(ctx, destaddr, newsendmsgid, JarvisResultTypeLocalErrorEnd, nil, err) } return err } <-chanEnd return nil }
package request import "quan/model" type SysDictionarySearch struct { model.SysDictionary PageInfo }
/* Copyright 2023 MediaExchange.io 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. */ // The config package provides a simple application configuration system with // strongly-typed objects. Configuration is read from either a YAML or JSON // file and returned to the application. package config import ( "bytes" "encoding/json" "fmt" "io/ioutil" "os" "path/filepath" "reflect" "strconv" "strings" "github.com/ghodss/yaml" ) // FromFile reads application configuration from a file found at path, then // returns the decoded data to the application-supplied object, konf. // // Errors reading the file, decoding the file, or if the file is of an // unexpected type are returned. func FromFile(path string, konf interface{}) error { buf, err := ioutil.ReadFile(path) if err != nil { return err } t := strings.ToLower(filepath.Ext(path)) if t == ".json" { return fromJson(buf, konf) } else if t == ".yaml" || t == ".yml" { return fromYaml(buf, konf) } else { return fmt.Errorf("unexpected file format: %s", t) } } // Decodes a JSON file into the configuration object. func fromJson(buf []byte, konf interface{}) error { decoder := json.NewDecoder(bytes.NewReader(buf)) if err := decoder.Decode(&konf); err != nil { return fmt.Errorf("config: while decoding JSON: %v", err) } return fromEnvironment(konf) } // Decodes a YAML file into the configuration object. func fromYaml(buf []byte, konf interface{}) error { err := yaml.Unmarshal(buf, &konf) if err != nil { return fmt.Errorf("config: while decoding YAML: %v", err) } return fromEnvironment(konf) } func fromEnvironment(konf interface{}) error { valueOfKonf := reflect.ValueOf(konf).Elem() typeOfKonf := reflect.TypeOf(konf).Elem() for i := 0; i < valueOfKonf.NumField(); i++ { valueOfField := valueOfKonf.Field(i) if valueOfField.Kind() == reflect.Struct && valueOfField.CanInterface() { // Depth-first search for fields. err := fromEnvironment(valueOfField.Addr().Interface()) if err != nil { return err } } // If the field contains an `env` tag, attempt to load the value from the environment. typeOfField := typeOfKonf.Field(i) tag, ok := typeOfField.Tag.Lookup("env") if ok { val, ok := os.LookupEnv(tag) if ok { // Convert the value to match the field and set it. switch valueOfField.Kind() { case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: x, err := strconv.ParseInt(val, 10, 64) if err != nil { return err } valueOfField.SetInt(x) case reflect.Bool: x, err := strconv.ParseBool(val) if err != nil { return err } valueOfField.SetBool(x) case reflect.Float32, reflect.Float64: x, err := strconv.ParseFloat(val, 64) if err != nil { return err } valueOfField.SetFloat(x) case reflect.String: valueOfField.SetString(val) } } } } return nil }
package main import ( "fmt" "math/rand" ) func main() { fmt.Print(rand.Intn(100), ",") fmt.Print(rand.Intn(100)) fmt.Println() fmt.Println(rand.Float64()) fmt.Println(int(10 * rand.Float64())) }
package graphkb import "github.com/clems4ever/go-graphkb/internal/schema" type AssetType = schema.AssetType type RelationKeyType = schema.RelationKeyType type RelationType = schema.RelationType
package main import ( "fmt" //"strings" "crypto/md5" //"strconv" "io" "encoding/hex" "strconv" "strings" ) func in_array(a string, list [8]string) bool { for _, b := range list { if b == a { return true } } return false } func main() { door_id := "abc" found := false const pw_len = 8 counter := 3231928 var pw [pw_len]string for !found{ data:= strconv.Itoa(counter) data = door_id + data h := md5.New() io.WriteString(h, data) hexrep := hex.EncodeToString(h.Sum(nil)) if strings.HasPrefix(hexrep, "00000"){ ind := string(hexrep[5]) i, err := strconv.Atoi(ind) if err != nil{ //fmt.Println("String conversion error") continue } if i < pw_len{ if string(pw[i]) == ""{ pw[i] = string(hexrep[6]) fmt.Println(string(hexrep[6])) } } } if !in_array("", pw){ found =true fmt.Println(pw) } if counter == 5017308{ found =true fmt.Println(pw) } counter += 1 } }
package client import ( "github.com/json-iterator/go" "errors" ) var json = jsoniter.ConfigCompatibleWithStandardLibrary type Client struct { server_addr string acid string } var WxClient = &Client{ "", "", } func InitClient(addr string, acid string) { (*WxClient).server_addr = addr (*WxClient).acid = acid } func SetAddr(addr string) *Client { (*WxClient).server_addr = addr return WxClient } func (client *Client) SetAcid(acid string) *Client { (*client).acid = acid return client } func (client *Client) WxappOauth(code string) (map[string]interface{}, error) { return GetData(post((*client).server_addr, map[string]string{ "accountId" : (*client).acid, "method" : "WxappOauth", "jsCode" : code, })) } func (client *Client) DecodeWxappData(sessionKey string, iv string, encryptedData string) (map[string]interface{}, error) { data, err := post((*client).server_addr, map[string]string{ "accountId" : (*client).acid, "method" : "DecodeWxappData", "sessionKey" : sessionKey, "iv" : iv, "encryptedData" : encryptedData, }) if data["code"].(float64) != 200 { return map[string]interface{}{}, errors.New(data["msg"].(string)) } return data["data"].(map[string]interface{}), err } func GetData(olddata map[string]interface{}, err error) (map[string]interface{}, error) { if err != nil { return map[string]interface{}{}, err } if olddata["code"].(float64) != 200 { return map[string]interface{}{}, errors.New(olddata["msg"].(string)) } wechatRes := olddata["data"].(map[string]interface{}) errcode, ok := wechatRes["errcode"] if ok && errcode.(float64) != 0 { return map[string]interface{}{}, errors.New(wechatRes["errmsg"].(string)) } return olddata["data"].(map[string]interface{}), nil }
package goSolution import "testing" func TestKInversePairs(t *testing.T) { AssertEqual(t, 2, kInversePairs(3, 1)) }
package sqls // InsResult is SQL. const InsResult = ` INSERT INTO results ( competition_id , user_id , user_name , url , ttl_ns_per_op , ttl_alloced_bytes_per_op , ttl_allocs_per_op , file_path , created_at , updated_at ) VALUES ( ? , ? , ? , ? , ? , ? , ? , ? , CURRENT_TIMESTAMP , CURRENT_TIMESTAMP ) `
package point import ( "testing" "github.com/go-gl/mathgl/mgl32" ) type testShader struct { } func (t testShader) Use() { } func (t testShader) SetUniformMat4(s string, m mgl32.Mat4) { } func (t testShader) DrawPoints(i int32) { } func (t testShader) Close(i int) { } func (t testShader) VertexAttribPointer(i uint32, c int32, s int32, o int) { } func (t testShader) BindVertexArray() { } func (t testShader) BindBufferData(d []float32) { } var shader testShader func getPoint() *Point { return &Point{ coordinate: mgl32.Vec3{0, 0, 0}, color: mgl32.Vec3{0, 0, 1}, size: 1.0, direction: mgl32.Vec3{0, 0, 0}, speed: 0.0, } } func TestNew(t *testing.T) { points := New(shader) if len(points.vao.Get()) != 0.0 { t.Error("Vao should be empty") } if len(points.points) != 0.0 { t.Error("Points should be empty") } } func TestSetColor(t *testing.T) { point := getPoint() color := mgl32.Vec3{1, 1, 1} point.SetColor(color) if point.color != color { t.Error("Color should be updated") } } func TestSetSpeed(t *testing.T) { point := getPoint() speed := float32(5.0) point.SetSpeed(speed) if point.speed != speed { t.Error("Speed should be updated") } } func TestSetDirection(t *testing.T) { point := getPoint() dir := mgl32.Vec3{0, 1, 0} point.SetDirection(dir) if point.direction != dir { t.Error("Direction should be updated") } } func TestSetIndexDirection(t *testing.T) { point := getPoint() expectedDir := mgl32.Vec3{0, 1, 0} point.SetIndexDirection(1, 1) if point.direction != expectedDir { t.Error("Direction should be updated") } } func TestAdd(t *testing.T) { points := New(shader) coords := mgl32.Vec3{1, 1, 1} col := mgl32.Vec3{1, 0, 0} size := float32(3.0) insertedPoint := points.Add(coords, col, size) if insertedPoint.coordinate != coords { t.Error("Coordinate mismatch") } if insertedPoint.color != col { t.Error("Color mismatch") } if insertedPoint.size != size { t.Error("Size mismatch") } } func TestUpdate(t *testing.T) { points := New(shader) coords := mgl32.Vec3{0, 0, 0} col := mgl32.Vec3{1, 0, 0} size := float32(3.0) points.Update(10.0) point := points.Add(coords, col, size) if point.coordinate.Y() != 0.0 || point.coordinate.X() != 0.0 || point.coordinate.Z() != 0.0 { t.Error("Invalid coordinates after Update - not moving") } point.SetSpeed(2.0) point.SetDirection(mgl32.Vec3{0, 1, 0}) points.Update(10.0) if point.coordinate.Y() != float32(20.0) || point.coordinate.X() != 0.0 || point.coordinate.Z() != 0.0 { t.Error("Invalid coordinates after Update - moving") t.Log(point) t.Log(points) } } func TestLog(t *testing.T) { points := New(shader) log := points.Log() if len(log) < 6 { t.Error("Log too short") } coords := mgl32.Vec3{0, 0, 0} col := mgl32.Vec3{1, 0, 0} size := float32(3.0) points.Add(coords, col, size) log = points.Log() if len(log) < 16 { t.Error("Log too short") } } func TestSetupVao(t *testing.T) { points := New(shader) points.setupVao() if len(points.vao.Get()) != 0 { t.Error("Invalid vao length") } coords := mgl32.Vec3{0, 0, 0} col := mgl32.Vec3{1, 0, 0} size := float32(3.0) points.Add(coords, col, size) points.setupVao() if len(points.vao.Get()) != 7 { t.Error("Invalid vao length") } } func TestBuildVao(t *testing.T) { points := New(shader) points.setupVao() if len(points.vao.Get()) != 0 { t.Error("Invalid vao length") } coords := mgl32.Vec3{0, 0, 0} col := mgl32.Vec3{1, 0, 0} size := float32(3.0) points.Add(coords, col, size) points.buildVao() if len(points.vao.Get()) != 7 { t.Error("Invalid vao length") } } func TestDrawWithUniforms(t *testing.T) { points := New(shader) points.setupVao() if len(points.vao.Get()) != 0 { t.Error("Invalid vao length") } coords := mgl32.Vec3{0, 0, 0} col := mgl32.Vec3{1, 0, 0} size := float32(3.0) points.Add(coords, col, size) points.DrawWithUniforms(mgl32.Ident4(), mgl32.Ident4()) if len(points.vao.Get()) != 7 { t.Error("Invalid vao length") } } func TestDraw(t *testing.T) { points := New(shader) points.setupVao() if len(points.vao.Get()) != 0 { t.Error("Invalid vao length") } coords := mgl32.Vec3{0, 0, 0} col := mgl32.Vec3{1, 0, 0} size := float32(3.0) points.Add(coords, col, size) points.Draw() if len(points.vao.Get()) != 7 { t.Error("Invalid vao length") } } func TestCount(t *testing.T) { points := New(shader) if points.Count() != 0 { t.Error("Invalid points count") } coords := mgl32.Vec3{0, 0, 0} col := mgl32.Vec3{1, 0, 0} size := float32(3.0) points.Add(coords, col, size) if points.Count() != 1 { t.Error("Invalid points count") } }
package main import "fmt" func ascOrder(num1 int, num2 int) []int { if num1 < num2 { return []int{num1, num2} } return []int{num2, num1} } func main() { fmt.Println(ascOrder(2, 7)) fmt.Println(ascOrder(7, 2)) }
package parser_test import ( "errors" "testing" parser "github.com/romshark/llparser" "github.com/romshark/llparser/misc" "github.com/stretchr/testify/require" ) type FragKind = parser.FragmentKind const ( _ FragKind = misc.FrSign + iota TestFrFoo TestFrBar ) func rncmp(a, b []rune) bool { for i, x := range b { if a[i] != x { return false } } return true } // Basic terminal types var ( testR_foo = &parser.Rule{ Designation: "keyword foo", Pattern: parser.Checked{ Designation: "keyword foo", Fn: func(src []rune) bool { return rncmp(src, []rune("foo")) }, }, Kind: TestFrFoo, } testR_bar = &parser.Rule{ Designation: "keyword bar", Pattern: parser.Checked{ Designation: "keyword bar", Fn: func(src []rune) bool { return rncmp(src, []rune("bar")) }, }, Kind: TestFrBar, } ) func newLexer(src string) parser.Lexer { return misc.NewLexer(&parser.SourceFile{ Name: "test.txt", Src: []rune(src), }) } type C struct { line uint column uint } // CheckCursor checks a cursor relative to the lexer func CheckCursor( t *testing.T, lexer parser.Lexer, cursor parser.Cursor, line, column uint, ) { require.Equal(t, lexer.Position().File, cursor.File) require.Equal(t, line, cursor.Line) require.Equal(t, column, cursor.Column) if column > 1 || line > 1 { require.True(t, cursor.Index > 0) } else if column == 1 && line == 1 { require.Equal(t, uint(0), cursor.Index) } } func checkFrag( t *testing.T, lexer parser.Lexer, frag parser.Fragment, kind parser.FragmentKind, begin C, end C, elements int, ) { require.Equal(t, kind, frag.Kind()) CheckCursor(t, lexer, frag.Begin(), begin.line, begin.column) CheckCursor(t, lexer, frag.End(), end.line, end.column) require.Len(t, frag.Elements(), elements) } func TestTokenString(t *testing.T) { lx := newLexer("abcdefg") tk, matched, err := lx.ReadExact([]rune("abc"), parser.FragmentKind(100)) require.NoError(t, err) require.True(t, matched) require.Equal(t, "100(test.txt: 1:1-1:4 'abc')", tk.String()) tk, matched, err = lx.ReadExact([]rune("defg"), parser.FragmentKind(101)) require.NoError(t, err) require.True(t, matched) require.Equal(t, "101(test.txt: 1:4-1:8 'defg')", tk.String()) } func TestParserSequence(t *testing.T) { t.Run("SingleLevel", func(t *testing.T) { pr := parser.NewParser() lx := newLexer("foo bar") expectedKind := parser.FragmentKind(100) mainFrag, err := pr.Parse(lx, &parser.Rule{ Designation: "foobar", Pattern: parser.Sequence{ parser.Term(misc.FrWord), parser.Term(misc.FrSpace), parser.Term(misc.FrWord), }, Kind: expectedKind, }) require.NoError(t, err) checkFrag(t, lx, mainFrag, expectedKind, C{1, 1}, C{1, 10}, 3) // Check elements elems := mainFrag.Elements() checkFrag(t, lx, elems[0], misc.FrWord, C{1, 1}, C{1, 4}, 0) checkFrag(t, lx, elems[1], misc.FrSpace, C{1, 4}, C{1, 7}, 0) checkFrag(t, lx, elems[2], misc.FrWord, C{1, 7}, C{1, 10}, 0) }) t.Run("TwoLevels", func(t *testing.T) { pr := parser.NewParser() lx := newLexer("foo bar") expectedKind := parser.FragmentKind(100) mainFrag, err := pr.Parse(lx, &parser.Rule{ Designation: "foobar", Pattern: parser.Sequence{ testR_foo, parser.Term(misc.FrSpace), testR_bar, }, Kind: expectedKind, }) require.NoError(t, err) checkFrag(t, lx, mainFrag, expectedKind, C{1, 1}, C{1, 10}, 3) // Check elements elems := mainFrag.Elements() checkFrag(t, lx, elems[0], TestFrFoo, C{1, 1}, C{1, 4}, 1) checkFrag(t, lx, elems[1], misc.FrSpace, C{1, 4}, C{1, 7}, 0) checkFrag(t, lx, elems[2], TestFrBar, C{1, 7}, C{1, 10}, 1) }) } // TestParserSequenceErr tests sequence parsing errors func TestParserSequenceErr(t *testing.T) { t.Run("UnexpectedTokenTermExact", func(t *testing.T) { pr := parser.NewParser() lx := newLexer("foo") expectedKind := parser.FragmentKind(100) mainFrag, err := pr.Parse(lx, &parser.Rule{ Designation: "foobar", Pattern: parser.Sequence{ parser.TermExact{ Kind: TestFrBar, Expectation: []rune("bar"), }, testR_foo, }, Kind: expectedKind, }) require.Error(t, err) require.Equal( t, "unexpected token 'f', expected {'bar'} at test.txt:1:1", err.Error(), ) require.Nil(t, mainFrag) }) t.Run("UnexpectedTokenChecked", func(t *testing.T) { pr := parser.NewParser() lx := newLexer("foo foo") expectedKind := parser.FragmentKind(100) mainFrag, err := pr.Parse(lx, &parser.Rule{ Designation: "foobar", Pattern: parser.Sequence{ testR_foo, parser.Term(misc.FrSpace), parser.Checked{ Designation: "checked token", Fn: func(str []rune) bool { return rncmp(str, []rune("bar")) }, }, }, Kind: expectedKind, }) require.Error(t, err) require.Equal( t, "unexpected token 'foo', expected {checked token} at test.txt:1:5", err.Error(), ) require.Nil(t, mainFrag) }) } func TestParserOptionalInSequence(t *testing.T) { t.Run("Missing", func(t *testing.T) { pr := parser.NewParser() lx := newLexer("bar") expectedKind := parser.FragmentKind(100) mainFrag, err := pr.Parse(lx, &parser.Rule{ Designation: "?foo bar", Pattern: parser.Sequence{ parser.Optional{parser.Sequence{ testR_foo, parser.Term(misc.FrSpace), }}, testR_bar, }, Kind: expectedKind, }) require.NoError(t, err) checkFrag(t, lx, mainFrag, expectedKind, C{1, 1}, C{1, 4}, 1) // Check elements elems := mainFrag.Elements() checkFrag(t, lx, elems[0], TestFrBar, C{1, 1}, C{1, 4}, 1) }) t.Run("Present", func(t *testing.T) { pr := parser.NewParser() lx := newLexer("foo bar") expectedKind := parser.FragmentKind(100) mainFrag, err := pr.Parse(lx, &parser.Rule{ Designation: "?foo bar", Pattern: parser.Sequence{ parser.Optional{parser.Sequence{ testR_foo, parser.Term(misc.FrSpace), }}, testR_bar, }, Kind: expectedKind, }) require.NoError(t, err) checkFrag(t, lx, mainFrag, expectedKind, C{1, 1}, C{1, 8}, 3) // Check elements elems := mainFrag.Elements() checkFrag(t, lx, elems[0], TestFrFoo, C{1, 1}, C{1, 4}, 1) checkFrag(t, lx, elems[1], misc.FrSpace, C{1, 4}, C{1, 5}, 0) checkFrag(t, lx, elems[2], TestFrBar, C{1, 5}, C{1, 8}, 1) }) } func TestParserChecked(t *testing.T) { pr := parser.NewParser() lx := newLexer("example") expectedKind := parser.FragmentKind(100) mainFrag, err := pr.Parse(lx, &parser.Rule{ Designation: "keyword 'example'", Pattern: parser.Checked{"keyword 'example'", func(str []rune) bool { return rncmp(str, []rune("example")) }}, Kind: expectedKind, }) require.NoError(t, err) checkFrag(t, lx, mainFrag, expectedKind, C{1, 1}, C{1, 8}, 1) // Check elements elems := mainFrag.Elements() checkFrag(t, lx, elems[0], misc.FrWord, C{1, 1}, C{1, 8}, 0) } // TestParserCheckedErr tests checked parsing errors func TestParserCheckedErr(t *testing.T) { pr := parser.NewParser() lx := newLexer("elpmaxe") expectedKind := parser.FragmentKind(100) mainFrag, err := pr.Parse(lx, &parser.Rule{ Designation: "keyword 'example'", Pattern: parser.Checked{"keyword 'example'", func(str []rune) bool { return rncmp(str, []rune("example")) }}, Kind: expectedKind, }) require.Error(t, err) require.Equal( t, "unexpected token 'elpmaxe', "+ "expected {keyword 'example'} at test.txt:1:1", err.Error(), ) require.Nil(t, mainFrag) } func TestParserZeroOrMore(t *testing.T) { t.Run("None", func(t *testing.T) { pr := parser.NewParser() lx := newLexer("foo") expectedKind := parser.FragmentKind(100) mainFrag, err := pr.Parse(lx, &parser.Rule{ Designation: "(space foo)*", Pattern: parser.Sequence{ parser.ZeroOrMore{ parser.Sequence{ parser.Term(misc.FrSpace), testR_foo, }, }, parser.Optional{&parser.Rule{ Designation: "?foo", Pattern: testR_foo, Kind: 200, }}, }, Kind: expectedKind, }) require.NoError(t, err) checkFrag(t, lx, mainFrag, expectedKind, C{1, 1}, C{1, 4}, 1) // Check elements elems := mainFrag.Elements() checkFrag(t, lx, elems[0], 200, C{1, 1}, C{1, 4}, 1) }) t.Run("One", func(t *testing.T) { pr := parser.NewParser() lx := newLexer(" foo") expectedKind := parser.FragmentKind(100) mainFrag, err := pr.Parse(lx, &parser.Rule{ Designation: "(space foo)*", Pattern: parser.ZeroOrMore{ parser.Sequence{ parser.Term(misc.FrSpace), testR_foo, }, }, Kind: expectedKind, }) require.NoError(t, err) checkFrag(t, lx, mainFrag, expectedKind, C{1, 1}, C{1, 5}, 2) // Check elements elems := mainFrag.Elements() checkFrag(t, lx, elems[0], misc.FrSpace, C{1, 1}, C{1, 2}, 0) checkFrag(t, lx, elems[1], TestFrFoo, C{1, 2}, C{1, 5}, 1) }) t.Run("Multiple", func(t *testing.T) { pr := parser.NewParser() lx := newLexer(" foo foo foo") expectedKind := parser.FragmentKind(100) mainFrag, err := pr.Parse(lx, &parser.Rule{ Designation: "(space foo)*", Pattern: parser.ZeroOrMore{ parser.Sequence{ parser.Term(misc.FrSpace), testR_foo, }, }, Kind: expectedKind, }) require.NoError(t, err) checkFrag(t, lx, mainFrag, expectedKind, C{1, 1}, C{1, 13}, 6) // Check elements elements := mainFrag.Elements() checkFrag(t, lx, elements[0], misc.FrSpace, C{1, 1}, C{1, 2}, 0) checkFrag(t, lx, elements[1], TestFrFoo, C{1, 2}, C{1, 5}, 1) checkFrag(t, lx, elements[2], misc.FrSpace, C{1, 5}, C{1, 6}, 0) checkFrag(t, lx, elements[3], TestFrFoo, C{1, 6}, C{1, 9}, 1) checkFrag(t, lx, elements[4], misc.FrSpace, C{1, 9}, C{1, 10}, 0) checkFrag(t, lx, elements[5], TestFrFoo, C{1, 10}, C{1, 13}, 1) }) } func TestParserOneOrMore(t *testing.T) { t.Run("None", func(t *testing.T) { pr := parser.NewParser() lx := newLexer("foo") expectedKind := parser.FragmentKind(100) mainFrag, err := pr.Parse(lx, &parser.Rule{ Designation: "(space foo)*", Pattern: parser.OneOrMore{ parser.Sequence{ parser.Term(misc.FrSpace), testR_foo, }, }, Kind: expectedKind, }) require.Error(t, err) require.Equal( t, "unexpected token 'foo', "+ "expected {terminal(1)} at test.txt:1:1", err.Error(), ) require.Nil(t, mainFrag) }) t.Run("One", func(t *testing.T) { pr := parser.NewParser() lx := newLexer(" foo") expectedKind := parser.FragmentKind(100) mainFrag, err := pr.Parse(lx, &parser.Rule{ Designation: "(space foo)*", Pattern: parser.ZeroOrMore{ parser.Sequence{ parser.Term(misc.FrSpace), testR_foo, }, }, Kind: expectedKind, }) require.NoError(t, err) checkFrag(t, lx, mainFrag, expectedKind, C{1, 1}, C{1, 5}, 2) // Check elements elems := mainFrag.Elements() checkFrag(t, lx, elems[0], misc.FrSpace, C{1, 1}, C{1, 2}, 0) checkFrag(t, lx, elems[1], TestFrFoo, C{1, 2}, C{1, 5}, 1) }) t.Run("Multiple", func(t *testing.T) { pr := parser.NewParser() lx := newLexer(" foo foo foo") expectedKind := parser.FragmentKind(100) mainFrag, err := pr.Parse(lx, &parser.Rule{ Designation: "(space foo)*", Pattern: parser.OneOrMore{ parser.Sequence{ parser.Term(misc.FrSpace), testR_foo, }, }, Kind: expectedKind, }) require.NoError(t, err) require.NotNil(t, mainFrag) checkFrag(t, lx, mainFrag, expectedKind, C{1, 1}, C{1, 13}, 6) // Check elements elements := mainFrag.Elements() checkFrag(t, lx, elements[0], misc.FrSpace, C{1, 1}, C{1, 2}, 0) checkFrag(t, lx, elements[1], TestFrFoo, C{1, 2}, C{1, 5}, 1) checkFrag(t, lx, elements[2], misc.FrSpace, C{1, 5}, C{1, 6}, 0) checkFrag(t, lx, elements[3], TestFrFoo, C{1, 6}, C{1, 9}, 1) checkFrag(t, lx, elements[4], misc.FrSpace, C{1, 9}, C{1, 10}, 0) checkFrag(t, lx, elements[5], TestFrFoo, C{1, 10}, C{1, 13}, 1) }) } func TestParserSuperfluousInput(t *testing.T) { pr := parser.NewParser() lx := newLexer("foo ") expectedKind := parser.FragmentKind(100) mainFrag, err := pr.Parse(lx, &parser.Rule{ Designation: "single foo", Pattern: testR_foo, Kind: expectedKind, }) require.Error(t, err) require.Equal(t, "unexpected token ' ' at test.txt:1:4", err.Error()) require.Nil(t, mainFrag) } func TestParserEither(t *testing.T) { t.Run("Neither", func(t *testing.T) { pr := parser.NewParser() lx := newLexer(" ") expectedKind := parser.FragmentKind(100) mainFrag, err := pr.Parse(lx, &parser.Rule{ Designation: "(Foo / Bar)", Pattern: parser.Either{ testR_foo, testR_bar, }, Kind: expectedKind, }) require.Error(t, err) require.Equal( t, "unexpected token ' ', expected {either of "+ "[keyword foo, keyword bar]} at test.txt:1:1", err.Error(), ) require.Nil(t, mainFrag) }) t.Run("First", func(t *testing.T) { pr := parser.NewParser() lx := newLexer("foo") expectedKind := parser.FragmentKind(100) mainFrag, err := pr.Parse(lx, &parser.Rule{ Designation: "(Foo / Bar)", Pattern: parser.Either{ testR_foo, testR_bar, }, Kind: expectedKind, }) require.NoError(t, err) require.NotNil(t, mainFrag) checkFrag(t, lx, mainFrag, expectedKind, C{1, 1}, C{1, 4}, 1) // Check elements elements := mainFrag.Elements() require.Len(t, elements, 1) checkFrag(t, lx, elements[0], TestFrFoo, C{1, 1}, C{1, 4}, 1) }) t.Run("Second", func(t *testing.T) { pr := parser.NewParser() lx := newLexer("bar") expectedKind := parser.FragmentKind(100) mainFrag, err := pr.Parse(lx, &parser.Rule{ Designation: "(Foo / Bar)", Pattern: parser.Either{ testR_foo, testR_bar, }, Kind: expectedKind, }) require.NoError(t, err) require.NotNil(t, mainFrag) checkFrag(t, lx, mainFrag, expectedKind, C{1, 1}, C{1, 4}, 1) // Check elements elements := mainFrag.Elements() require.Len(t, elements, 1) checkFrag(t, lx, elements[0], TestFrBar, C{1, 1}, C{1, 4}, 1) }) } func TestParserRecursiveRule(t *testing.T) { pr := parser.NewParser() lx := newLexer("foo,foo,foo,") expectedKind := parser.FragmentKind(100) recursiveRule := &parser.Rule{ Designation: "recursive", Kind: expectedKind, } recursiveRule.Pattern = parser.Sequence{ testR_foo, parser.Term(misc.FrSign), parser.Optional{recursiveRule}, } mainFrag, err := pr.Parse(lx, recursiveRule) require.NoError(t, err) checkFrag(t, lx, mainFrag, expectedKind, C{1, 1}, C{1, 13}, 3) // First level elems := mainFrag.Elements() checkFrag(t, lx, elems[0], TestFrFoo, C{1, 1}, C{1, 4}, 1) checkFrag(t, lx, elems[1], misc.FrSign, C{1, 4}, C{1, 5}, 0) checkFrag(t, lx, elems[2], expectedKind, C{1, 5}, C{1, 13}, 3) // Second levels elems2 := elems[2].Elements() checkFrag(t, lx, elems2[0], TestFrFoo, C{1, 5}, C{1, 8}, 1) checkFrag(t, lx, elems2[1], misc.FrSign, C{1, 8}, C{1, 9}, 0) checkFrag(t, lx, elems2[2], expectedKind, C{1, 9}, C{1, 13}, 2) // Second levels elems3 := elems2[2].Elements() checkFrag(t, lx, elems3[0], TestFrFoo, C{1, 9}, C{1, 12}, 1) checkFrag(t, lx, elems3[1], misc.FrSign, C{1, 12}, C{1, 13}, 0) } func TestParserAction(t *testing.T) { pr := parser.NewParser() aFrags := make([]parser.Fragment, 0, 2) bFrags := make([]parser.Fragment, 0, 2) lx := newLexer("a,b,b,a,") aKind := parser.FragmentKind(905) ruleA := &parser.Rule{ Designation: "a", Kind: aKind, Pattern: parser.TermExact{misc.FrWord, []rune("a")}, Action: func(f parser.Fragment) error { aFrags = append(aFrags, f) return nil }, } bKind := parser.FragmentKind(906) ruleB := &parser.Rule{ Designation: "b", Kind: bKind, Pattern: parser.TermExact{misc.FrWord, []rune("b")}, Action: func(f parser.Fragment) error { bFrags = append(bFrags, f) return nil }, } mainFrag, err := pr.Parse(lx, &parser.Rule{ Designation: "list", Pattern: parser.OneOrMore{&parser.Rule{ Designation: "list item", Pattern: parser.Sequence{ parser.Either{ruleA, ruleB}, parser.Term(misc.FrSign), }, }}, }) require.NoError(t, err) require.NotNil(t, mainFrag) require.Len(t, aFrags, 2) checkFrag(t, lx, aFrags[0], aKind, C{1, 1}, C{1, 2}, 1) checkFrag(t, lx, aFrags[1], aKind, C{1, 7}, C{1, 8}, 1) require.Len(t, bFrags, 2) checkFrag(t, lx, bFrags[0], bKind, C{1, 3}, C{1, 4}, 1) checkFrag(t, lx, bFrags[1], bKind, C{1, 5}, C{1, 6}, 1) } func TestParserActionErr(t *testing.T) { pr := parser.NewParser() lx := newLexer("a") expectedErr := errors.New("custom error") mainFrag, err := pr.Parse(lx, &parser.Rule{ Designation: "a", Kind: 900, Pattern: parser.TermExact{misc.FrWord, []rune("a")}, Action: func(f parser.Fragment) error { return expectedErr }, }) require.Error(t, err) require.IsType(t, &parser.Err{}, err) er := err.(*parser.Err) require.Equal(t, expectedErr, er.Err) require.Equal(t, uint(0), er.At.Index) require.Equal(t, uint(1), er.At.Line) require.Equal(t, uint(1), er.At.Column) require.Nil(t, mainFrag) } func TestParserLexed(t *testing.T) { fn := func(crs parser.Cursor) uint { rn := crs.File.Src[crs.Index] if (rn >= 0x0410 && rn <= 0x044F) || rn == '\n' { return 1 } return 0 } expectedKind := parser.FragmentKind(100) pr := parser.NewParser() lx := newLexer("абв\nгде") mainFrag, err := pr.Parse(lx, &parser.Rule{ Pattern: parser.Lexed{ Kind: expectedKind, Designation: "lexed token", Fn: fn, }, Kind: expectedKind, }) require.NoError(t, err) checkFrag(t, lx, mainFrag, expectedKind, C{1, 1}, C{2, 4}, 1) // Check elements elems := mainFrag.Elements() checkFrag(t, lx, elems[0], expectedKind, C{1, 1}, C{2, 4}, 0) } func TestParserLexedErr(t *testing.T) { fn := func(crs parser.Cursor) uint { rn := crs.File.Src[crs.Index] if (rn >= 0x0410 && rn <= 0x044F) || rn == '\n' { return 1 } return 0 } expectedKind := parser.FragmentKind(100) pr := parser.NewParser() lx := newLexer("abc") mainFrag, err := pr.Parse(lx, &parser.Rule{ Pattern: parser.Lexed{ Kind: expectedKind, Designation: "lexed token", Fn: fn, }, Kind: expectedKind, }) require.Error(t, err) require.Nil(t, mainFrag) }
package http import ( "errors" "github.com/spiral/roadrunner" "github.com/spiral/roadrunner/service" "strings" "time" ) // Config configures RoadRunner HTTP server. type Config struct { // Enable enables http svc. Enable bool // Address and port to handle as http server. Address string // MaxRequest specified max size for payload body in megabytes, set 0 to unlimited. MaxRequest int64 // Uploads configures uploads configuration. Uploads *UploadsConfig // Workers configures roadrunner server and worker pool. Workers *roadrunner.ServerConfig } // Hydrate must populate Config values using given Config source. Must return error if Config is not valid. func (c *Config) Hydrate(cfg service.Config) error { if err := cfg.Unmarshal(c); err != nil { return err } if err := c.Valid(); err != nil { return err } if c.Workers.Relay == "" { c.Workers.Relay = "pipes" } if c.Workers.RelayTimeout < time.Microsecond { c.Workers.RelayTimeout = time.Second * time.Duration(c.Workers.RelayTimeout.Nanoseconds()) } if c.Workers.Pool.AllocateTimeout < time.Microsecond { c.Workers.Pool.AllocateTimeout = time.Second * time.Duration(c.Workers.Pool.AllocateTimeout.Nanoseconds()) } if c.Workers.Pool.DestroyTimeout < time.Microsecond { c.Workers.Pool.DestroyTimeout = time.Second * time.Duration(c.Workers.Pool.DestroyTimeout.Nanoseconds()) } return nil } // Valid validates the configuration. func (c *Config) Valid() error { if c.Uploads == nil { return errors.New("mailformed uploads config") } if c.Workers == nil { return errors.New("mailformed workers config") } if c.Workers.Pool == nil { return errors.New("mailformed workers config (pool config is missing)") } if err := c.Workers.Pool.Valid(); err != nil { return err } if !strings.Contains(c.Address, ":") { return errors.New("mailformed server address") } return nil }
package service import "github.com/saravase/golang_echo_api/entity" type PlantService interface { Save(entity.Plant) entity.Plant FindAll() []entity.Plant } type service struct { plants []entity.Plant } func New() PlantService { return &service{ plants: []entity.Plant{}, } } func (service *service) Save(plant entity.Plant) entity.Plant { service.plants = append(service.plants, plant) return plant } func (service *service) FindAll() []entity.Plant { return service.plants }
package rp import ( "bytes" "encoding/json" "net/http" ) type TestItemType string type ExecutionStatus string type LogLevel string type Mode string const ( // TimestampLayout can be used with time.Parse to create time.Time values from strings. TimestampLayout = "2006-01-02T15:04:05.000Z" // TestItemTypeSuite - SUITE TestItemTypeSuite TestItemType = "SUITE" // TestItemTypeStep - STEP TestItemTypeStep TestItemType = "STEP" // TestItemTypeStory - STORY TestItemTypeStory TestItemType = "STORY" // TestItemTypeTest - TEST TestItemTypeTest TestItemType = "TEST" // TestItemTypeScenario - SCENARIO TestItemTypeScenario TestItemType = "SCENARIO" // ExecutionStatusPassed - PASSED ExecutionStatusPassed ExecutionStatus = "PASSED" // ExecutionStatusFailed - FAILED ExecutionStatusFailed ExecutionStatus = "FAILED" // ExecutionStatusSkipped - SKIPPED ExecutionStatusSkipped ExecutionStatus = "SKIPPED" // LogLevelTrace - TRACE LogLevelTrace LogLevel = "TRACE" // LogLevelDebug - DEBUG LogLevelDebug LogLevel = "DEBUG" // LogLevelInfo - INFO LogLevelInfo LogLevel = "INFO" // LogLevelWarn - WARN LogLevelWarn LogLevel = "WARN" // LogLevelError - ERROR LogLevelError LogLevel = "ERROR" // ModeDebug - DEBUG ModeDebug Mode = "DEBUG" // ModeDefault - DEFAULT ModeDefault Mode = "DEFAULT" ) // NewClient creates a RP Client for specified project and user unique id func NewClient(apiURL, project, uuid string) Client { if len(project) == 0 { log.Error("project could not be empty") } if len(uuid) == 0 { log.Error("uuid could not be empty") } return Client{ baseURL: joinURL(apiURL, project), authBearer: "Bearer " + uuid, http: new(http.Client), } } // createNewRequest is used for building new http.Request to RP API with default headers // apiUrl should start from "/" e.g. '/launch' func (c *Client) createNewRequest(method string, apiURL string, payload []byte) (*http.Request, error) { req, err := http.NewRequest(method, joinURL(c.baseURL, apiURL), bytes.NewBuffer(payload)) req.Header.Add("Authorization", c.authBearer) req.Header.Add("Content-Type", "application/json;charset=utf-8") return req, err } // request is used to send api request to rp func (c *Client) request(method, apiURL string, payload []byte) (*http.Response, error) { req, err := c.createNewRequest(method, apiURL, payload) if err != nil { return nil, err } log.Debugf("rp request: %v", req) resp, err := c.http.Do(req) log.Debugf("rp responce: %v", resp) return resp, err } // post request func (c *Client) post(apiURL string, body interface{}) (*http.Response, error) { payload, err := json.Marshal(body) if err != nil { return nil, err } return c.request("POST", apiURL, payload) } // put request func (c *Client) put(apiURL string, body interface{}) (*http.Response, error) { payload, err := json.Marshal(body) if err != nil { return nil, err } return c.request("PUT", apiURL, payload) }
/* The generalised harmonic number of order m of n is H(n,m)=sum[k, n] 1/k^m For example, the harmonic numbers are H(n, 1) and H(∞,2)=π^2/6. These are related to the Riemann zeta function as ζ(m)=lim n→∞ H(n,m) Given two positive integers n>0, m>0, output the exact rational number H(n,m). The fraction should be reduced to its simplest term (i.e. if it is ab, gcd(a,b)=1). You may output as a numerator/denominator pair, a rational number or any clear value that distinguishes itself as a rational number. You may not output as a floating point number. This is code-golf, so the shortest code in bytes wins Test cases n, m -> Hₙ,ₘ 3, 7 -> 282251/279936 6, 4 -> 14011361/12960000 5, 5 -> 806108207/777600000 4, 8 -> 431733409/429981696 3, 1 -> 11/6 8, 3 -> 78708473/65856000 7, 2 -> 266681/176400 6, 7 -> 940908897061/933120000000 2, 8 -> 257/256 5, 7 -> 2822716691183/2799360000000 */ package main import ( "fmt" "math/big" ) func main() { tab := []struct { n, m int64 r string }{ {3, 7, "282251/279936"}, {6, 4, "14011361/12960000"}, {5, 5, "806108207/777600000"}, {4, 8, "431733409/429981696"}, {3, 1, "11/6"}, {8, 3, "78708473/65856000"}, {7, 2, "266681/176400"}, {6, 7, "940908897061/933120000000"}, {2, 8, "257/256"}, {5, 7, "2822716691183/2799360000000"}, } for _, p := range tab { v := H(p.n, p.m) fmt.Println(p.n, p.m, v) assert(v.String() == p.r) } } func assert(x bool) { if !x { panic("assertion failed") } } func H(n, m int64) *big.Rat { r := new(big.Rat) p := big.NewInt(m) for k := int64(1); k <= n; k++ { x := big.NewInt(k) x.Exp(x, p, nil) u := new(big.Rat) u.SetInt(x) u.Inv(u) r.Add(r, u) } return r }
package model type PlayerLicenseAnalytics struct { // Analytics License Key AnalyticsKey string `json:"analyticsKey,omitempty"` }
package Problem0275 // a 为升序排列 func hIndex(a []int) int { size := len(a) // 二分查找法 lo, hi := 0, size-1 // lo, miD, hi 都是降序切片 d 中的序列号 // 因为 a 是 d 的逆序,即 a 是升序切片 // d[miD] , a[miA] 是同一个数 // 所以,存在数量关系,miD + miA +1 == size var miD, miA int for lo <= hi { miD = (lo + hi) / 2 miA = size - miD - 1 if a[miA] > miD { lo = miD + 1 } else { hi = miD - 1 } } return lo }
package main import ( "log" "net/http" ) func handleCategoryOverview(w http.ResponseWriter, r *http.Request) { if r.URL.Path != "/categories/" { handleNotFound(w, r) return } session, _ := store.Get(r, "session") ctx, err := createContextFromSession(db, session) if !err.Empty() { err.AddTraceback("handleCategoryOverview()", "Error while creating the context.") log.Println("[ERROR]", err) http.Redirect(w, r, "/index/", http.StatusSeeOther) return } w.Header().Set("Content-Type", "text/html; chartset=utf-8") ctx["Title"] = "Categories" e := tmpl.ExecuteTemplate(w, "categories.html", ctx) if e != nil { err.Init("handleCategoryOverview()", e.Error()) log.Println("[ERROR]", err) } }
package tameshigiri import "testing" // func ExampleAssertion() { var t = &testing.T{} var assertion = Assertion{ T: t } var expected = 123 var actual = 123 assertion.IsTrue(expected == actual, "Ye") assertion.IsFalse(expected != actual, "Ne") assertion.Equals(expected, actual, "Eh?") // This example shows all passed assertions. }
package apimodels type ApiResult struct { Success bool `json:"success"` Msgs []string `json:"msgs"` }
package starwars_test import ( "encoding/json" "net/http" "net/http/httptest" "testing" golangtraining "github.com/julianjca/julian-golang-training-beginner" "github.com/julianjca/julian-golang-training-beginner/internal/starwars" "github.com/stretchr/testify/require" ) func TestGetCharacters(t *testing.T) { expectedRes := &golangtraining.StarWarsResponse{ Results: []golangtraining.Characters{ { Name: "Luke", }, }, } jsonResp, err := json.Marshal(expectedRes) require.NoError(t, err) handler := func() (res http.Handler) { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) _, err = w.Write(jsonResp) require.NoError(t, err) }) }() mockServer := httptest.NewServer(handler) defer mockServer.Close() starwarsClient := starwars.NewStarWarsClient(http.DefaultClient, mockServer.URL) res, err := starwarsClient.GetCharacters() require.NoError(t, err) require.Equal(t, expectedRes.Results[0], res.Results[0]) }
package log import ( "encoding/json" "reflect" "testing" ) func TestFixFieldsConflict(t *testing.T) { m := map[string]interface{}{ "request_id": "request_id", "time": "time", "field.time": "field.time", "level": "level", "field.level": "field.level", "field.level.2": "field.level.2", } fixFieldsConflict(m, []string{"request_id", "field.level", "field.level.3"}) want := map[string]interface{}{ "field.request_id": "request_id", "field.time.2": "time", "field.time": "field.time", "field.field.level.3": "level", "field.field.level": "field.level", "field.level.2": "field.level.2", } if !reflect.DeepEqual(m, want) { t.Errorf("\nhave:%v\nwant:%v", m, want) return } } func TestFixFieldsConflictAndHandleErrorFields(t *testing.T) { var nilErr error fields := map[string]interface{}{ "user_id": 123456, // integer "name": "jack", // string "nil_error": nilErr, // nil error "error": testError{}, // error "context_error1": testContextError1{}, // error with ErrorContext "context_error2": testContextError2{}, // error with ErrorContextJSON "context_error3": testContextError3{}, // error with ErrorContext and ErrorContextJSON "context_not_error": testContextWithoutError{X: "test"}, // not error with ErrorContext and ErrorContextJSON "context_error1_context": "context_error1_context_value", // conflict with context_error1.context } fixFieldsConflictAndHandleErrorFields(fields) want := map[string]interface{}{ "user_id": 123456, "name": "jack", "nil_error": nil, "error": "test_error_123456789", "context_error1": "context_error1_error_123456789", "context_error1_context": "context_error1_context_123456789", "context_error2": "context_error2_error_123456789", "context_error2_context": json.RawMessage(`{"key":"context_error2_context_json_123456789"}`), "context_error3": "context_error3_error_123456789", "context_error3_context": json.RawMessage(`{"key":"context_error3_context_json_123456789"}`), "context_not_error": testContextWithoutError{X: "test"}, "field.context_error1_context": "context_error1_context_value", } if !reflect.DeepEqual(fields, want) { t.Errorf("\nhave:%v\nwant:%v", fields, want) return } } type testError struct{} func (testError) Error() string { return "test_error_123456789" } type testContextError1 struct{} func (testContextError1) Error() string { return "context_error1_error_123456789" } func (testContextError1) ErrorContext() string { return "context_error1_context_123456789" } type testContextError2 struct{} func (testContextError2) Error() string { return "context_error2_error_123456789" } func (testContextError2) ErrorContextJSON() json.RawMessage { return []byte(`{"key":"context_error2_context_json_123456789"}`) } type testContextError3 struct{} func (testContextError3) Error() string { return "context_error3_error_123456789" } func (testContextError3) ErrorContext() string { return "context_error3_context_123456789" } func (testContextError3) ErrorContextJSON() json.RawMessage { return []byte(`{"key":"context_error3_context_json_123456789"}`) } type testContextWithoutError struct { X string `json:"x"` } func (testContextWithoutError) ErrorContext() string { return "context_not_error_context_123456789" } func (testContextWithoutError) ErrorContextJSON() json.RawMessage { return []byte(`{"key":"context_not_error_context_json_123456789"}`) }
package model import ( "fmt" ) type Employee struct { ID int32 FirstName string LastName string BadgeNumber int32 } // Demo2 print hello func Demo2() { fmt.Println("hello model") }
package tenant import ( "github.com/imsilence/gocmdb/server/cloud" "github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common" "github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common/profile" cvm "github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/cvm/v20170312" ) type TenantCloud struct { Addr string Key string Secrect string Region string credential *common.Credential profile *profile.ClientProfile } func (t *TenantCloud) Name() string { return "tenantyun" } func (t *TenantCloud) Init(addr string, key string, secrect string, region string) { t.Addr = addr t.Key = key t.Secrect = secrect t.Region = region t.credential = common.NewCredential(key, secrect) t.profile = profile.NewClientProfile() t.profile.HttpProfile.Endpoint = addr } func (t *TenantCloud) TestConnect() error { client, err := cvm.NewClient(t.credential, t.Region, t.profile) if err == nil { request := cvm.NewDescribeRegionsRequest() _, err = client.DescribeRegions(request) } return err } func (t *TenantCloud) statusTransform(status string) string { statusMap := map[string]string{ "PENDING": cloud.Pending, "LAUNCH_FAILED": cloud.LaunchFailed, "RUNNING": cloud.Running, "STOPPED": cloud.Stopped, "STARTING": cloud.Starting, "STOPPING": cloud.Stopping, "REBOOTING": cloud.Rebooting, "SHUTDOWN": cloud.ShutDown, "TERMINATING": cloud.Terminating, } if text, ok := statusMap[status]; ok { return text } return cloud.Unknow } func (t *TenantCloud) GetInstances() []*cloud.Instance { var limit int64 = 100 client, err := cvm.NewClient(t.credential, t.Region, t.profile) if err != nil { return nil } request := cvm.NewDescribeInstancesRequest() request.Limit = &limit response, err := client.DescribeInstances(request) if err != nil { return nil } instances := make([]*cloud.Instance, *response.Response.TotalCount) for index, instance := range response.Response.InstanceSet { publicAddrs := make([]string, len(instance.PublicIpAddresses)) privateAddrs := make([]string, len(instance.PrivateIpAddresses)) for i, addr := range instance.PublicIpAddresses { publicAddrs[i] = *addr } for i, addr := range instance.PrivateIpAddresses { privateAddrs[i] = *addr } instances[index] = &cloud.Instance{ Key: *instance.InstanceId, UUID: *instance.Uuid, Name: *instance.InstanceName, OS: *instance.OsName, CPU: int(*instance.CPU), Memory: int(*instance.Memory), PublicAddrs: publicAddrs, PrivateAddrs: privateAddrs, Status: t.statusTransform(*instance.InstanceState), CreatedTime: *instance.CreatedTime, ExpiredTime: *instance.ExpiredTime, } } return instances } func (t *TenantCloud) StartInstance(uuid string) error { client, err := cvm.NewClient(t.credential, t.Region, t.profile) if err == nil { request := cvm.NewStartInstancesRequest() request.InstanceIds = []*string{&uuid} _, err = client.StartInstances(request) } return err } func (t *TenantCloud) StopInstance(uuid string) error { client, err := cvm.NewClient(t.credential, t.Region, t.profile) if err == nil { request := cvm.NewStopInstancesRequest() request.InstanceIds = []*string{&uuid} _, err = client.StopInstances(request) } return err } func (t *TenantCloud) RestartInstance(uuid string) error { client, err := cvm.NewClient(t.credential, t.Region, t.profile) if err == nil { request := cvm.NewRebootInstancesRequest() request.InstanceIds = []*string{&uuid} _, err = client.RebootInstances(request) } return err } func init() { cloud.DefaultManager.Register(new(TenantCloud)) }
package sql import ( "bufio" "strconv" "strings" "unicode" ) var eof = rune(0) var bufSizeHint = 32 type Lexeme struct { Token Token Lit string } type Scanner struct { r *bufio.Reader } func NewScanner(r *strings.Reader) *Scanner { s := Scanner{r: bufio.NewReader(r)} return &s } func (s *Scanner) Scan() Lexeme { var ch rune ch = s.read() var lex Lexeme switch { case isWhitespace(ch): s.unread() s.skipWhitespaces() lex = s.Scan() case unicode.IsLetter(ch): s.unread() lit := s.scanLiterals() tok := tokenizeLiteral(lit) lex = Lexeme{tok, lit} case isComparisonOperator(ch): s.unread() lit := s.scanOperators() tok := tokenizeOperators(lit) lex = Lexeme{tok, lit} case unicode.IsDigit(ch) || isSign(ch): s.unread() lit := s.scanNumerics() tok := tokenizeNumerics(lit) lex = Lexeme{tok, lit} case isQuotationMark(ch): s.unread() lit := s.scanStringLiterals() lex = Lexeme{STRING, lit} case ch == eof: lex = Lexeme{EOF, ""} case ch == '*': lex = Lexeme{ASTERISK, "*"} case ch == ',': lex = Lexeme{COMMA, ","} case ch == ';': lex = Lexeme{SEMICOLON, ";"} default: lex = Lexeme{ILLEGAL, string(ch)} } return lex } func (s *Scanner) read() rune { ch, _, err := s.r.ReadRune() if err != nil { return eof } return ch } func (s *Scanner) unread() { _ = s.r.UnreadRune() } func (s *Scanner) peek() rune { ch := s.read() s.unread() return ch } func (s *Scanner) scanLiterals() string { var sb strings.Builder sb.Grow(bufSizeHint) for { ch := s.read() if !isAlphanumeric(ch) { // Special cases: // - underscore in identifiers names are acceptable // - dot for table qualified name, ex. db.schema.table if (ch == '_') || (ch == '.' && s.peek() != '.') { sb.WriteRune(ch) continue } s.unread() return sb.String() } sb.WriteRune(ch) } } func (s *Scanner) scanWhitespaces() Lexeme { var sb strings.Builder sb.Grow(bufSizeHint) for { ch := s.read() if !isWhitespace(ch) { s.unread() return Lexeme{WS, sb.String()} } sb.WriteRune(ch) } } func (s *Scanner) scanNumerics() string { var sb strings.Builder sb.Grow(bufSizeHint) ch := s.read() sb.WriteRune(ch) for { ch := s.read() if !unicode.IsDigit(ch) { // Special cases: // SI notation exponent // floats dot decimal separator if (unicode.ToUpper(ch) == 'E') || (ch == '.' && s.peek() != '.') { sb.WriteRune(ch) continue } s.unread() return sb.String() } sb.WriteRune(ch) } } func (s *Scanner) scanStringLiterals() string { var sb strings.Builder sb.Grow(bufSizeHint) ch := s.read() sb.WriteRune(ch) for { ch := s.read() sb.WriteRune(ch) if isQuotationMark(ch) { return sb.String() } } } func (s *Scanner) scanOperators() string { var sb strings.Builder sb.Grow(bufSizeHint) ch1 := s.read() sb.WriteRune(ch1) ch2 := s.read() if (ch1 == '<' && (ch2 == '>' || ch2 == '=')) || (ch1 == '>' && ch2 == '=') { sb.WriteRune(ch2) } else { s.unread() } return sb.String() } func (s *Scanner) skipWhitespaces() { for { ch := s.read() if !isWhitespace(ch) { s.unread() return } } } func isWhitespace(ch rune) bool { return unicode.Is(unicode.White_Space, ch) } func isQuotationMark(ch rune) bool { return unicode.Is(unicode.Quotation_Mark, ch) } func isAlphanumeric(ch rune) bool { return unicode.IsLetter(ch) || unicode.IsDigit(ch) } func isSign(ch rune) bool { return ch == '-' || ch == '+' } func isComparisonOperator(ch rune) bool { return ch == '=' || ch == '>' || ch == '<' } func tokenizeLiteral(lit string) Token { if kw, ok := keywords[strings.ToUpper(lit)]; ok { return kw } return IDENT } func tokenizeOperators(lit string) Token { var tok Token switch lit { case "=": tok = EQ case "<>": tok = NEQ case ">": tok = GT case ">=": tok = GTE case "<": tok = LT case "<=": tok = LTE default: tok = ILLEGAL } return tok } func tokenizeNumerics(lit string) Token { if _, err := strconv.ParseInt(lit, 10, 64); err == nil { return INT } if _, err := strconv.ParseFloat(lit, 64); err == nil { return FLOAT } return ILLEGAL }
package main import ( "fmt" ) func main() { test([]int{}, 0, []int{}) test([]int{1}, 1, []int{1}) test([]int{1, 1, 2}, 3, []int{1, 1, 2}) test([]int{1, 1, 1, 2, 2}, 4, []int{1, 1, 2, 2}) test([]int{1, 1, 1, 2, 2, 2, 3}, 5, []int{1, 1, 2, 2, 3}) test([]int{1, 1, 1, 1, 3, 3}, 4, []int{1, 1, 3, 3}) } func test(nums []int, count int, r []int) { if count != removeDuplicates(nums) { fmt.Println(nums, count, r) } for i := 0; i < count; i++ { if nums[i] != r[i] { fmt.Println(nums, count, r) } } } func removeDuplicates(nums []int) int { if len(nums) <= 2 { return len(nums) } res := 1 count := 1 for i := 1; i < len(nums); i++ { if nums[i] == nums[i-1] { count++ if count <= 2 { nums[res] = nums[i] res++ } } else { count = 1 nums[res] = nums[i] res++ } } return res }
package main import ( "fmt" "log" "encoding/json" "github.com/go-resty/resty/v2" . "github.com/logrusorgru/aurora" ) // Refer to this. // https://github.com/steadylearner/Rust-Full-Stack/blob/master/bots/teloxide/src/community-bots/models/subreddit.rs type Post struct { Title string Url string } type Child struct { Data Post } type Children struct { Children []Child } type Response struct { Data Children } func main() { target := "https://www.reddit.com/r/golang/new/.json?limit=10" client := resty.New() // https://github.com/go-resty/resty#simple-get response, err := client.R().Get(target) if err != nil { log.Fatal(err) } else { // fmt.Printf("%s\n", response) // body bodyBytes := response.Body() response := Response{} err := json.Unmarshal(bodyBytes, &response) if err != nil { log.Fatal(err) } // fmt.Println(response.Data) for index, post := range response.Data.Children { num := index + 1 stdoutLink := fmt.Sprintf("%d. %s(%s)", num, post.Data.Title, Blue(post.Data.Url)) fmt.Println(stdoutLink) } } }
// Copyright 2017 Gruppe 12 IS-105. All rights reserved. package main import ( "fmt" "net" "./Crypt" ) func sendResponse(conn *net.UDPConn, addr *net.UDPAddr) { _,err := conn.WriteToUDP([]byte("From server: Hello I got your mesage "), addr) if err != nil { fmt.Printf("Couldn't send response %v", err) } } const key = "HeiIS105" func main() { listenAndReceive() } func listenAndReceive(){ p := make([]byte, 2048) addr := net.UDPAddr{ Port: 8009, IP: net.ParseIP("0.0.0.0"), } ser, err := net.ListenUDP("udp", &addr) if err != nil { fmt.Printf("Some error %v\n", err) return } for { _, remoteaddr, err := ser.ReadFromUDP(p) var msg, _ = Crypt.AesDecrypt([]byte(p), []byte(key)) fmt.Printf("Read a message from %v %s \n", remoteaddr, string(msg)) if err != nil { fmt.Printf("Some error %v", err) continue } go sendResponse(ser, remoteaddr) } } // Kode fra https://gist.github.com/iwanbk/2295233, https://coderwall.com/p/wohavg/creating-a-simple-tcp-server-in-go - // - https://systembash.com/a-simple-go-tcp-server-and-tcp-client/ og http://stackoverflow.com/questions/27176523/udp-in-golang-listen-not-a-blocking-call delvis gjennbrukt her.
/** * @Author: korei * @Description: * @File: VirtualCoinBox * @Version: 1.0.0 * @Date: 2020/11/18 下午7:08 */ package virtualHardWare import ( "fmt" "sync" ) type VirtualCoinBox struct { count float32 countMutex sync.Mutex } func (v *VirtualCoinBox) Cost(count float32) bool { v.countMutex.Lock() defer v.countMutex.Unlock() if count<=v.count { v.count-=count v.updateMonitor() return true }else { return false } } func (v *VirtualCoinBox) updateMonitor() { fmt.Printf("monitor show : %v \n",v.count) } func (v *VirtualCoinBox) Work() { var wg sync.WaitGroup wg.Add(1) go func() { wg.Done() var input uint32 v.count = 0 v.updateMonitor() fmt.Printf("Enter\n\t0 : change\n\t1 : enter 1¥\n\t5 : enter 0.5¥\n") for { fmt.Scan(&input) switch input { case 0: v.change() case 1: v.enter(1) case 5: v.enter(0.5) default: fmt.Printf("please input 0 / 1 / 5 / ^C \n") } } }() wg.Wait() } func (v *VirtualCoinBox) change() { v.countMutex.Lock() defer v.countMutex.Unlock() fmt.Printf("change %v¥\n",v.count) v.count = 0 v.updateMonitor() } func (v *VirtualCoinBox) enter(count float32) { v.countMutex.Lock() defer v.countMutex.Unlock() v.count += count v.updateMonitor() }
package main import ( "github.com/DanielRenne/mangosNode/push" "log" "time" ) const url = "tcp://127.0.0.1:600" func main() { var node push.Node err := node.Connect(url) if err != nil { log.Printf("Error: %v", err.Error) } //Code a forever loop to stop main from exiting. for { time.Sleep(3 * time.Second) go node.Push([]byte("Pushing Data")) } }
package main import ( "fmt" ) func main() { msg1 := make(chan int, 3) msg2 := make(chan int, 3) defer close(msg1) defer close(msg2) go func (){ // msg1 <- 2 }() var result int select { case result=<-msg1: fmt.Println("msg1") case result=<-msg2: fmt.Println("msg2") default: fmt.Println("default") } fmt.Println(result) }
package repo import ( "fmt" "strings" "github.com/kyma-incubator/compass/components/director/pkg/apperrors" "github.com/jmoiron/sqlx" "github.com/pkg/errors" ) func getAllArgs(conditions Conditions) []interface{} { var allArgs []interface{} for _, cond := range conditions { if argVal, ok := cond.GetQueryArgs(); ok { allArgs = append(allArgs, argVal...) } } return allArgs } func writeEnumeratedConditions(builder *strings.Builder, conditions Conditions) error { if builder == nil { return apperrors.NewInternalError("builder cannot be nil") } var conditionsToJoin []string for _, cond := range conditions { conditionsToJoin = append(conditionsToJoin, cond.GetQueryPart()) } builder.WriteString(fmt.Sprintf(" %s", strings.Join(conditionsToJoin, " AND "))) return nil } // TODO: Refactor builder func buildSelectQuery(tableName string, selectedColumns string, conditions Conditions, orderByParams OrderByParams) (string, []interface{}, error) { var stmtBuilder strings.Builder stmtBuilder.WriteString(fmt.Sprintf("SELECT %s FROM %s", selectedColumns, tableName)) if len(conditions) > 0 { stmtBuilder.WriteString(" WHERE") } err := writeEnumeratedConditions(&stmtBuilder, conditions) if err != nil { return "", nil, errors.Wrap(err, "while writing enumerated conditions.") } err = writeOrderByPart(&stmtBuilder, orderByParams) if err != nil { return "", nil, errors.Wrap(err, "while writing order by part") } allArgs := getAllArgs(conditions) return getQueryFromBuilder(stmtBuilder), allArgs, nil } const anyKeyExistsOp = "?|" const anyKeyExistsOpPlaceholder = "{{anyKeyExistsOp}}" const allKeysExistOp = "?&" const allKeysExistOpPlaceholder = "{{allKeysExistOp}}" const singleKeyExistsOp = "] ? " const singleKeyExistsOpPlaceholder = "{{singleKeyExistsOp}}" var tempReplace = []string{ anyKeyExistsOp, anyKeyExistsOpPlaceholder, allKeysExistOp, allKeysExistOpPlaceholder, singleKeyExistsOp, singleKeyExistsOpPlaceholder, } var reverseTempReplace = []string{ anyKeyExistsOpPlaceholder, anyKeyExistsOp, allKeysExistOpPlaceholder, allKeysExistOp, singleKeyExistsOpPlaceholder, singleKeyExistsOp, } // sqlx doesn't detect ?| and ?& operators properly func getQueryFromBuilder(builder strings.Builder) string { strToRebind := strings.NewReplacer(tempReplace...).Replace(builder.String()) strAfterRebind := sqlx.Rebind(sqlx.DOLLAR, strToRebind) query := strings.NewReplacer(reverseTempReplace...).Replace(strAfterRebind) return query } func writeOrderByPart(builder *strings.Builder, orderByParams OrderByParams) error { if builder == nil { return apperrors.NewInternalError("builder cannot be nil") } if orderByParams == nil || len(orderByParams) == 0 { return nil } builder.WriteString(" ORDER BY") for idx, orderBy := range orderByParams { if idx > 0 { builder.WriteString(",") } builder.WriteString(fmt.Sprintf(" %s %s", orderBy.Field, orderBy.Dir)) } return nil }
package main import ( "flag" "github.com/garyburd/redigo/redis" "github.com/gorilla/websocket" "log" "os" ) type Live struct { connections []*connection `json:"-"` silentusers []string `json:"-"` chatrecord []byte `json:"-"` online int `json:"-"` } type connection struct { // The websocket connection. ws *websocket.Conn // Buffered channel of outbound messages. send chan []byte // The Mainhub. h *Mainhub // name, channel name string userid string liveid string silent bool login bool // a normal user or an anonymous client } type User struct { Name string `json:"name"` Userid string `json:"userid"` } type Userlist struct { Creator User `json:"creator"` Userlist []*User `json:"userlist"` } type Mainhub struct { // Register requests from the connections. register chan *connection // Unregister requests from connections. unregister chan *connection } const ( ERR_SUCCESS int32 = iota ERR_PARAMETERS ERR_NOLIVEID ERR_REPEATLOGIN ) var ERROR_MAP = map[int32]string{ ERR_SUCCESS: "success", ERR_PARAMETERS: "parameters wrong", ERR_NOLIVEID: "no such live", ERR_REPEATLOGIN: "repeat login", } const ( VERSION string = "1.0.0" MAIN_VERSION uint8 = 1 MID_VERSION uint8 = 0 LAST_VERSION uint8 = 0 CHAT_BUFF_MAX int = 10000 ThriftAddr string = ":9090" yq_redishost string = "192.168.1.17:6379" ) var ( addr = flag.String("addr", ":8080", "websocket chat service address") live_map map[string]*Live logfile *os.File logger *log.Logger chat_rdspool *redis.Pool )
package pet // todo 写入文件 const ( WEAPON_ATTR_CRIT = 1 // 暴击 WEAPON_ATTR_FLASH = 2 // 闪避 WEAPON_ATTR_REST = 3 // 休息 WEAPON_ATTR_LOCK = 4 // 必中 WEAPON_ATTR_CONT = 5 // 连续 WEAPON_ATTR_DODGE = 6 // 闪避 KIND_S = 0 KIND_M = 1 KIND_L = 2 KIND_T = 3 // 投掷类 ) var Skills = []Skill{ { Id: 0, Name: "胶水", Effect: Glue, }, } var Weapons = []Weapon{ { Id: 0, Name: "平底锅 :fried_egg: ", MinAttack: 18, MaxAttack: 22, Kind: KIND_S, }, { Id: 1, Name: "板砖", MinAttack: 3, MaxAttack: 8, Kind: KIND_M, }, { Id: 2, Name: "接力棒", MinAttack: 6, MaxAttack: 10, Kind: KIND_S, }, { Id: 3, Name: "汽水罐", MinAttack: 4, MaxAttack: 6, Kind: KIND_T, }, { Id: 4, Name: "短剑", MinAttack: 3, MaxAttack: 8, Kind: KIND_S, }, { Id: 5, Name: "木剑", MinAttack: 10, MaxAttack: 25, Kind: KIND_S, }, { Id: 6, Name: "判官笔", MinAttack: 5, MaxAttack: 8, Kind: KIND_S, }, { Id: 7, Name: "流星球", MinAttack: 15, MaxAttack: 24, Kind: KIND_T, }, { Id: 8, Name: "老鼠 :rat:", MinAttack: 5, MaxAttack: 8, Kind: KIND_T, }, { Id: 9, Name: "小李飞刀", MinAttack: 5, MaxAttack: 10, Kind: KIND_T, }, { Id: 10, Name: "折凳", MinAttack: 11, MaxAttack: 13, Kind: KIND_M, }, { Id: 11, Name: "铁铲", MinAttack: 12, MaxAttack: 18, Kind: KIND_M, }, { Id: 12, Name: "环扣刀", MinAttack: 12, MaxAttack: 13, Kind: KIND_M, }, { Id: 13, Name: "红缨枪", MinAttack: 15, MaxAttack: 30, Kind: KIND_M, }, { Id: 14, Name: "双截棍", MinAttack: 9, MaxAttack: 13, Kind: KIND_M, }, { Id: 15, Name: "宽刃剑", MinAttack: 6, MaxAttack: 10, Kind: KIND_M, }, { Id: 16, Name: "幻影枪", MinAttack: 20, MaxAttack: 40, Kind: KIND_L, }, { Id: 17, Name: "木槌", MinAttack: 7, MaxAttack: 12, Kind: KIND_L, }, { Id: 18, Name: "棒球棒", MinAttack: 15, MaxAttack: 20, Kind: KIND_L, }, { Id: 19, Name: "狂魔镰", MinAttack: 15, MaxAttack: 25, Kind: KIND_L, }, { Id: 20, Name: "关刀", MinAttack: 20, MaxAttack: 35, Kind: KIND_L, }, { Id: 21, Name: "开山斧", MinAttack: 12, MaxAttack: 18, Kind: KIND_L, }, { Id: 22, Name: "充气锤子", MinAttack: 20, MaxAttack: 35, Kind: KIND_L, }, { Id: 23, Name: "三叉戟", MinAttack: 25, MaxAttack: 50, Kind: KIND_L, }, { Id: 24, Name: "青龙戟", MinAttack: 15, MaxAttack: 20, Kind: KIND_M, }, }
package timeline import ( "encoding/json" "fmt" "github.com/xeipuuv/gojsonschema" "io/ioutil" "strings" "time" ) func ProcessFile(inputPath string, ch chan<- ShortResult) { start := time.Now() buffer, err := ioutil.ReadFile(inputPath) if err != nil { ch <- ShortResult{fmt.Sprintf("can't read input file: %v\n", err), 1} return } err = preflightAsset(&buffer, inputPath) if err != nil { ch <- ShortResult{fmt.Sprintf("input failed preflight check: %v\n", err), 1} return } result := ProcessBytes(buffer) //output filename bare := strings.Replace(strings.ToLower(inputPath), ".json", "", -1) ext := ".png" outputPath := strings.Join([]string{bare, ext}, "") if result.Code > 0 { fmt.Printf("%s\n", result.Message) ch <- ShortResult{fmt.Sprintf("%s: %s\n", outputPath, result.Message), 1} return } //save to file result.Context.SavePNG(outputPath) secs := time.Since(start).Seconds() ch <- ShortResult{fmt.Sprintf("%s: %.2fs", outputPath, secs), 0} return } func ProcessBytes(bytes []byte) Result { start := time.Now() i18n, msg := getI18n() if msg != "" { return Result{fmt.Sprintf("Can't read i18n table: %s\n", msg), 1, nil} } //staticTimelineSchemaJsonBytes func taken from bindata.go; if function name doesn't match, go get -u helps schemaBytes, err := staticTimelineSchemaJsonBytes() if err != nil { return Result{fmt.Sprintf("Can't read schema file: %v\n", err), 1, nil} } schemaLoader := gojsonschema.NewStringLoader(string(schemaBytes)) documentLoader := gojsonschema.NewStringLoader(string(bytes)) result, err := gojsonschema.Validate(schemaLoader, documentLoader) if err != nil { return Result{fmt.Sprintf("Can't validate JSON: %s\n", err.Error()), 1, nil} } if !result.Valid() { //fmt.Printf("Invalid JSON:\n") //for _, desc := range result.Errors() { // fmt.Printf("- %s\n", desc) //} //return Result{fmt.Sprintf("Invalid JSON: %s\n", result.Errors()[0]), 1, nil} } var data Data if err := json.Unmarshal(bytes, &data); err != nil { return Result{fmt.Sprintf("JSON unmarshaling failed: %s\n", err), 1, nil} } enrichData(&data) errNo, errString := validateData(&data) if errNo > 0 { return Result{fmt.Sprintf(errString), 1, nil} } ctx := drawScene(&data, i18n) w := ctx.Width() h := ctx.Height() secs := time.Since(start).Seconds() return Result{fmt.Sprintf("Image dimensions %d✕%d: %.2fs", w, h, secs), 0, ctx} }
/* NOTE : - there's MANUAL cleaning data in input ex: b4 : 128 x 128pixels a4 : 128 x 128 pixels b4 : pixels| a4 : pixel b4 : 6 lines| 101 x 67 pixels a4 : 101 x 67 pixels - 1 chars = 8 pixels */ package display_size import ( util "github.com/verlandz/clustering-phone/utility" "os" "strconv" "strings" ) const ( DEFAULT_PATH = "display_size/display_size" INPUT_PATH = DEFAULT_PATH + ".in" OUTPUT_PATH = DEFAULT_PATH + ".out" ) type display struct { length, width float64 } var ( arr []display mean display valid = 0.00 def = -1.00 ) func Clean() { // data preparation data := strings.Split(util.GetData(INPUT_PATH), "\n") for i, v := range data { // skip header if i == 0 { continue } temp := strings.Fields(v) x := display{def, def} if len(temp) >= 4 { isErr := false length, err := strconv.ParseFloat(temp[0], 64) if err != nil { isErr = true } width, err := strconv.ParseFloat(temp[2], 64) if err != nil { isErr = true } c := temp[3] if !isErr { if strings.Contains(c, "chars") { length *= 8 width *= 8 } x.length = length x.width = width mean.length += length mean.width += width valid++ } } arr = append(arr, x) } // if there's invalid data , we will use mean from all valid data mean.length /= valid mean.width /= valid // data output f, err := os.Create(OUTPUT_PATH) util.Check(err) defer f.Close() f.WriteString("Dis length(px),Dis width(px)") for _, v := range arr { s := "" if v.length == def || v.width == def { s += strconv.FormatFloat(mean.length, 'f', -1, 64) + "," + strconv.FormatFloat(mean.width, 'f', -1, 64) } else { s += strconv.FormatFloat(v.length, 'f', -1, 64) + "," + strconv.FormatFloat(v.width, 'f', -1, 64) } f.WriteString("\n" + s) } }
package mathutil_test import ( "fmt" "github.com/AdguardTeam/golibs/mathutil" ) func ExampleBoolToNumber() { fmt.Println(mathutil.BoolToNumber[int](true)) fmt.Println(mathutil.BoolToNumber[int](false)) type flag float64 fmt.Println(mathutil.BoolToNumber[flag](true)) fmt.Println(mathutil.BoolToNumber[flag](false)) // Output: // 1 // 0 // 1 // 0 } func ExampleMax() { fmt.Println(mathutil.Max(1, 2)) fmt.Println(mathutil.Max(2, 1)) // Output: // 2 // 2 } func ExampleMin() { fmt.Println(mathutil.Min(1, 2)) fmt.Println(mathutil.Min(2, 1)) // Output: // 1 // 1 }
package main import ( "context" "database/sql" "flag" "github.com/go-chi/chi" "github.com/go-chi/chi/middleware" "github.com/go-chi/cors" article2 "github.com/hardstylez72/bblog/internal/api/controller/article" objectstorage2 "github.com/hardstylez72/bblog/internal/api/controller/objectstorage" user2 "github.com/hardstylez72/bblog/internal/api/controller/user" "github.com/hardstylez72/bblog/internal/auth" "github.com/hardstylez72/bblog/internal/logger" "github.com/hardstylez72/bblog/internal/objectstorage" "github.com/hardstylez72/bblog/internal/storage" "github.com/hardstylez72/bblog/internal/storage/article" "github.com/hardstylez72/bblog/internal/storage/user" "github.com/hardstylez72/bblog/internal/tracer" ad "github.com/hardstylez72/bblog/pkg/ad/storage" "github.com/spf13/viper" "go.uber.org/zap" "gorm.io/driver/postgres" "gorm.io/gorm" "log" "net/http" "time" ) type Server struct { log *zap.SugaredLogger router chi.Router services *Services } type Services struct { userStorage user.Storage articleStorage article.Storage objectStorage objectstorage.Storage } func main() { log, err := logger.New() errCheck(err, "can't load config") defer log.Sync() configPath := flag.String("config", "cmd/server/config.yaml", "path to config file") flag.Parse() err = Load(*configPath) errCheck(err, "can't load config") err = tracer.New(viper.GetString("tracer.jaeger.collectorEndpoint"), viper.GetString("tracer.jaeger.serviceName")) errCheck(err, "can't load config") services, err := initServices() errCheck(err, "can't init internal services") err = NewServer(services, log).Run() errCheck(err, "can't run server") } func errCheck(err error, errorText string) { if err == nil { return } log.Fatal(errorText, ": ", err) } func initServices() (*Services, error) { pgConn, err := storage.NewPGConnection(viper.GetString("databases.postgres")) if err != nil { return nil, err } pgUpgraded, err := storage.WrapPgConnWithSqlx(pgConn) if err != nil { return nil, err } userStorage := user.NewPGStorage(pgUpgraded) adConn, err := gorm.Open(postgres.New(postgres.Config{Conn: pgConn}), &gorm.Config{}) if err != nil { return nil, err } err = ad.NewStorage(adConn).Init() //resolveDefaultAdminUser() articleStorage := article.NewPgStorage(pgUpgraded) minioClient, err := objectstorage.NewMinioClient(objectstorage.Config{ Host: viper.GetString("objectStorage.minio.host"), AccessKeyID: viper.GetString("objectStorage.minio.accessKeyID"), SecretAccessKey: viper.GetString("objectStorage.minio.secretAccessKey"), UseSSL: viper.GetBool("objectStorage.minio.useSSL"), }) if err != nil { return nil, err } objectStorage := objectstorage.NewMinioStorage(minioClient) return &Services{ userStorage: userStorage, articleStorage: articleStorage, objectStorage: objectStorage, }, nil } func resolveDefaultAdminUser(userStorage user.Storage) error { ctx, cancel := context.WithTimeout(context.Background(), time.Second*10) defer cancel() userAmount, err := userStorage.GetUsersAmount(ctx) if err != nil { return err } if userAmount == 0 { userStorage.SaveUser(ctx, &user.User{ Id: 1, Email: sql.NullString{}, Login: sql.NullString{ String: "", Valid: false, }, }) } return nil } func NewServer(services *Services, log *zap.SugaredLogger) *Server { return &Server{ router: chi.NewRouter(), log: log, services: services, } } func (s *Server) Run() error { httpServer := &http.Server{ Addr: viper.GetString("port"), Handler: s.Handler(), } return httpServer.ListenAndServe() } func (s *Server) Handler() chi.Router { const ( apiPathPrefix = "/api" ) r := s.router c := cors.Handler(cors.Options{ AllowedMethods: []string{"GET", "POST", "PUT", "DELETE", "OPTIONS"}, AllowedHeaders: []string{"*"}, AllowedOrigins: []string{"http://localhost:*"}, AllowCredentials: true, Debug: true, }) r.Use(c) r.Use(middleware.RequestID) r.Use(logger.Inject(s.log)) r.Use(middleware.Timeout(60 * time.Second)) r.Use(auth.GuestSession) r.Use(auth.GetUser) r.Mount(apiPathPrefix, r) s.log.Info("app is successfully running") oauthCfg := auth.Oauth{ Google: auth.Config{ RedirectURL: viper.GetString("oauth.google.redirectURL"), ClientID: viper.GetString("oauth.google.clientID"), ClientSecret: viper.GetString("oauth.google.clientSecret"), Scopes: viper.GetStringSlice("oauth.google.scopes"), UserInfoURL: viper.GetString("oauth.google.userInfoURL"), UserRedirects: auth.UserRedirects{ OnSuccess: viper.GetString("oauth.google.userRedirects.onSuccess"), OnFailure: viper.GetString("oauth.google.userRedirects.onFailure"), }, }, Github: auth.Config{ RedirectURL: viper.GetString("oauth.github.redirectURL"), ClientID: viper.GetString("oauth.github.clientID"), ClientSecret: viper.GetString("oauth.github.clientSecret"), Scopes: viper.GetStringSlice("oauth.github.scopes"), UserInfoURL: viper.GetString("oauth.github.userInfoURL"), UserRedirects: auth.UserRedirects{ OnSuccess: viper.GetString("oauth.github.userRedirects.onSuccess"), OnFailure: viper.GetString("oauth.github.userRedirects.onFailure"), }, }, SessionCookieConfig: auth.SessionCookieConfig{ Name: viper.GetString("oauth.sessionCookie.name"), Domain: viper.GetString("oauth.sessionCookie.domain"), Path: viper.GetString("oauth.sessionCookie.path"), MaxAge: viper.GetInt("oauth.sessionCookie.maxAge"), Secure: viper.GetBool("oauth.sessionCookie.secure"), }, } auth.NewAuthController(oauthCfg).Mount(s.router) article2.NewArticleController(s.services.articleStorage).Mount(s.router) objectstorage2.NewObjectStorageController(s.services.objectStorage).Mount(s.router) user2.NewUserController(s.services.userStorage).Mount(s.router) return r }
package model import ( "fmt" "mvc-app/util" "net/http" ) var person = map[uint64]*User{ 123: &User{ FName: "Diwakar", LName: "Singh", Email: "diwakar@gmail.com", }, 124: &User{ FName: "Ravi", LName: "Kumar", Email: "ravi@gmail.com", }, } type userService struct{} var UserService userService func (us *userService) GetUser(userId uint64) (*User, *util.ApplicationError) { u := person[userId] if u != nil { return u, nil } return nil, &util.ApplicationError{ Message: fmt.Sprintf("User Not Found with user id %v", userId), StatusCode: http.StatusNotFound, Code: "not_found", } }
// ------------------------------------------------------------------- // // salter: Tool for bootstrap salt clusters in EC2 // // Copyright (c) 2013-2014 Orchestrate, Inc. All Rights Reserved. // // This file is provided to you under the Apache License, // Version 2.0 (the "License"); you may not use this file // except in compliance with the License. You may obtain // a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. // // ------------------------------------------------------------------- package main import ( "strings" "sync" "github.com/mitchellh/goamz/aws" "github.com/mitchellh/goamz/ec2" ) type Region struct { Keys map[string]Key // Key name -> Key (key.go) Conn ec2.EC2 SGroups map[string]RegionalSGroup // SG name -> Info dataDir string } type RegionalSGroup struct { ec2.SecurityGroupInfo RegionId string } type regionCacheRequest struct { Name string Region *Region Chan chan error } var G_REGION_CACHE chan *regionCacheRequest func init() { G_REGION_CACHE = make(chan *regionCacheRequest) } func StartRegionCache(config *Config) { go regionCacheLoop(config.AwsAuth, config.DataDir) } func GetRegion(name string) (*Region, error) { req := regionCacheRequest{ Name: name, Chan: make(chan error), } defer close(req.Chan) G_REGION_CACHE <- &req err := <-req.Chan return req.Region, err } func regionCacheLoop(awsAuth aws.Auth, dataDir string) { regions := make(map[string]*Region) for { req := <-G_REGION_CACHE region, found := regions[req.Name] if !found { conn := ec2.New(awsAuth, aws.Regions[req.Name]) region = &Region{ Conn: *conn, dataDir: dataDir, } err := region.Refresh() if err != nil { req.Chan <- err continue } regions[req.Name] = region } req.Region = region req.Chan <- nil } } func RegionKeyExists(name string, regionId string) bool { region, _ := GetRegion(regionId) _, found := region.Keys[name] return found } func RegionKey(name string, regionId string) Key { region, _ := GetRegion(regionId) key, _ := region.Keys[name] return key } func RegionSGExists(name string, regionId string) bool { region, _ := GetRegion(regionId) _, found := region.SGroups[name] return found } func RegionSG(name string, regionId string) RegionalSGroup { region, _ := GetRegion(regionId) sg := region.SGroups[name] return sg } func RegionSGEnsureExists(name string, regionId string) (*RegionalSGroup, error) { region, _ := GetRegion(regionId) var sg RegionalSGroup sg, found := region.SGroups[name] if !found { // Create the SG // TODO: Need to add support for VPC here? sg.Name = name sg.SecurityGroup.Description = name sgResp, err := region.Conn.CreateSecurityGroup(sg.SecurityGroup) if err != nil { return nil, err } debugf("Created security group %s-%s\n", regionId, name) sg.RegionId = regionId sg.SecurityGroup = sgResp.SecurityGroup region.SGroups[name] = sg return &sg, nil } return &sg, nil } func (r *Region) Refresh() error { rKeys := make(map[string]Key) rSgroups := make(map[string]RegionalSGroup) var lastErr *error = nil wg := new(sync.WaitGroup) // Grab keys from this connection wg.Add(1) go func() { defer wg.Done() keys, err := r.Conn.KeyPairs(nil, nil) if err != nil { lastErr = &err return } for _, keyPair := range keys.Keys { // Normalize the fingerprint by removing colons fingerprint := strings.Replace(keyPair.Fingerprint, ":", "", -1) // If the key is already present in r.Keys with the same // fingerprint, we can re-use that entry and avoid a bunch of // parsing/hashing key, found := r.Keys[keyPair.Name] if found && key.Fingerprint == fingerprint { rKeys[keyPair.Name] = key continue } // Load the local portion of the key, if it's present keyPtr, err := LoadKey(keyPair.Name, r.dataDir, fingerprint) if err != nil { errorf("Unable to load local copy of %s: %+v\n", keyPair.Name, err) continue } rKeys[keyPair.Name] = *keyPtr } }() // Grab all security groups wg.Add(1) go func() { defer wg.Done() sgroupResp, err := r.Conn.SecurityGroups(nil, nil) if err != nil { lastErr = &err return } for _, group := range sgroupResp.Groups { // If the group is associated with a VPC we ignore it //if group.VpcId != "" { // continue //} rSgroups[group.Name] = RegionalSGroup{group, r.Conn.Region.Name} } // Insert amazon-elb as a valid group //amazonElbSg := RegionalSGroup{RegionId: r.Conn.Region.Name} //amazonElbSg.Name = "amazon-elb-sg" //amazonElbSg.OwnerId = "amazon-elb" //rSgroups["amazon-elb-sg"] = amazonElbSg }() wg.Wait() if lastErr != nil { return *lastErr } // All data was pulled back successfully, overwrite current entries in // region r.Keys = rKeys r.SGroups = rSgroups return nil } func findTag(tags []ec2.Tag, name string) (string, bool) { for _, tag := range tags { if tag.Key == name { return tag.Value, true } } return "", false }
package main import ( "context" "fmt" "github.com/spf13/cobra" cmder "github.com/yaegashi/cobra-cmder" msgraph "github.com/yaegashi/msgraph.go/beta" V "github.com/yaegashi/msgraph.go/val" ) type AppSP struct { *App SpID string ServicePrincipalList []msgraph.ServicePrincipal ServicePrincipal *msgraph.ServicePrincipal SynchronizationRB *msgraph.SynchronizationRequestBuilder } func (app *App) AppSPComder() cmder.Cmder { return &AppSP{App: app} } func (app *AppSP) Cmd() *cobra.Command { cmd := &cobra.Command{ Use: "sp", Short: "Service principal commands", SilenceUsage: true, } cmd.PersistentFlags().StringVarP(&app.SpID, "sp-id", "", "", "service principal ID / display name") return cmd } func (app *AppSP) GetServicePrincipalList(ctx context.Context) error { if app.GraphClient == nil { err := app.GetGraphClient(ctx) if err != nil { return err } } spList, err := app.GraphClient.ServicePrincipals().Request().Get(ctx) if err != nil { return err } app.ServicePrincipalList = spList return nil } func (app *AppSP) GetServicePrincipal(ctx context.Context) error { if app.SpID == "" { return fmt.Errorf("Specify service principal ID (--sp-id)") } if app.ServicePrincipalList == nil { err := app.GetServicePrincipalList(ctx) if err != nil { return err } } for _, sp := range app.ServicePrincipalList { if V.String(sp.AppID) == app.SpID || V.String(sp.DisplayName) == app.SpID { app.ServicePrincipal = &sp break } } if app.ServicePrincipal == nil { return fmt.Errorf("Service principal for app ID %q is not found", app.SpID) } app.SynchronizationRB = app.GraphClient.ServicePrincipals().ID(*app.ServicePrincipal.ID).Synchronization() return nil }
package line_segment import ( "../basic" "../gfx" "github.com/go-gl/gl/v4.1-core/gl" "github.com/lucasb-eyer/go-colorful" ) type Bezier struct { p0, p1, p2, p3 *basic.Point q0, q1, q2, q3 *basic.Point b1, b2 *bead } func NewBezier(p0, p1, p2, p3 *basic.Point) *Bezier { vertShader, err := gfx.NewShaderFromFile("line_segment/shaders/basic.vert", gl.VERTEX_SHADER) if err != nil { panic(err) } fragShader, err := gfx.NewShaderFromFile("line_segment/shaders/basic.frag", gl.FRAGMENT_SHADER) if err != nil { panic(err) } program, err := gfx.NewProgram(vertShader, fragShader) if err != nil { panic(err) } program.Use() q0 := p0 q1 := p0.Mult(-3).Add(p1.Mult(3)) q2 := p0.Mult(3).Add(p1.Mult(-6)).Add(p2.Mult(3)) q3 := p0.Mult(-1).Add(p1.Mult(3)).Add(p2.Mult(-3)).Add(p3) b1 := NewBead(p0, p0.Add(p0.Sub(p1).Normalized().Mult(0.01)), &colorful.Color{1.0, 0.0, 0.0}) b2 := NewBead(p3, p3.Add(p3.Sub(p2).Normalized().Mult(0.01)), &colorful.Color{0.0, 0.0, 1.0}) return &Bezier{p0, p1, p2, p3, q0, q1, q2, q3, b1, b2} } func (b *Bezier) Point(t float32) *basic.Point { return b.p0.Mult((1-t)*(1-t)*(1-t)).Add(b.p1.Mult(3*(1-t)*(1-t)*t)).Add(b.p2.Mult(3*(1-t)*t*t)).Add(b.p3.Mult(t*t*t)) } func (b *Bezier) color() (float32, float32, float32, float32) { return 1.0, 1.0, 0.0, 1.0 } func (b *Bezier) Draw() { VertexCount := 256 points := make([]float32, 7*VertexCount, 7*VertexCount) for i := 0; i < VertexCount; i++ { t := float32(i)/float32(VertexCount-1) p := b.Point(t) points[i*7 + 0], points[i*7 + 1], points[i*7 + 2] = p.Elements() points[i*7 + 3], points[i*7 + 4], points[i*7 + 5], points[i*7 + 6] = b.color() } VAO := makeVao(points) gl.BindVertexArray(VAO) gl.DrawArrays(gl.LINE_STRIP, 0, int32(VertexCount)) b.b1.Draw() b.b2.Draw() } func (bez *Bezier) modify(b *bead) { c := b.current a0 := 3*bez.q3.Product(bez.q3) a1 := 5*bez.q3.Product(bez.q2) a2 := 4*bez.q3.Product(bez.q1) + 2*bez.q2.Product(bez.q2) a3 := 3*bez.q2.Product(bez.q1) + 3*bez.q3.Product(bez.q0.Sub(c)) a4 := bez.q1.Product(bez.q1) + 2*bez.q2.Product(bez.q0.Sub(c)) a5 := bez.q1.Product(bez.q0.Sub(c)) s := NewSturm(float64(a0), float64(a1), float64(a2), float64(a3), float64(a4), float64(a5)) roots := s.Root(0.0, 1.0, make([]float64, 0, 5)) length := func(t float32) float32 { return bez.Point(t).Sub(c).Product(bez.Point(t).Sub(c)) } minT := float32(0.0) if length(minT) > length(1.0) { minT = 1.0 } for _, root := range roots { if length(minT) > length(float32(root)) { minT = float32(root) } } b.current = bez.Point(minT) } func (b *Bezier) Update() { b.b1.Update(0.01) b.modify(b.b1) b.b2.Update(0.01) b.modify(b.b2) dir := b.b2.current.Sub(b.b1.current) if dir.Length() <= radius*2 { d := radius*2 - dir.Length() b.b1.current = b.b1.current.Add(dir.Normalized().Mult(-d/2.0)) b.b2.current = b.b2.current.Add(dir.Normalized().Mult(d/2.0)) b1Impuls := dir.Normalized().Mult(dir.Normalized().Product(b.b1.velocity())) b2Impuls := dir.Normalized().Mult(dir.Normalized().Product(b.b2.velocity())) b.b1.prev = b.b1.current.Sub(b.b1.velocity().Add(b2Impuls).Sub(b1Impuls)) b.b2.prev = b.b2.current.Sub(b.b2.velocity().Add(b1Impuls).Sub(b2Impuls)) } } func makeVao(array []float32) uint32 { var vbo uint32 gl.GenBuffers(1, &vbo) gl.BindBuffer(gl.ARRAY_BUFFER, vbo) gl.BufferData(gl.ARRAY_BUFFER, 4*len(array), gl.Ptr(array), gl.STATIC_DRAW) var vao uint32 gl.GenVertexArrays(1, &vao) gl.BindVertexArray(vao) gl.EnableVertexAttribArray(0) gl.EnableVertexAttribArray(1) gl.BindBuffer(gl.ARRAY_BUFFER, vbo) gl.VertexAttribPointer(0, 3, gl.FLOAT, false, 7*4, gl.PtrOffset(0)) gl.VertexAttribPointer(1, 4, gl.FLOAT, false, 7*4, gl.PtrOffset(3*4)) return vao }
package util import "bitbucket.org/inehealth/idonia-common/filter" //Ascendant sql string const Ascendant = "ASC" //Descendant sql string const Descendant = "DESC" //PageResult pagination struct type PageResult struct { CurrentPage int `json:"current_page"` TotalPages int `json:"total_pages"` ResultPerPageCount int `json:"result_per_page_count"` ResultTotalCount int `json:"result_total_count"` Orders []Order `json:"order"` Filter filter.SearchFilter `json:"filter"` } //Order pagination struct type Order struct { Field string `json:"field"` Type string `json:"type"` }
package handler import ( "context" "errors" "path/filepath" "testing" proto "github.com/jinmukeji/proto/v3/gen/micro/idl/partner/xima/user/v1" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/suite" ) // UnsetSecureEmailTestSuite 通过密保问题重置密码测试 type UnsetSecureEmailTestSuite struct { suite.Suite JinmuIDService *JinmuIDService Account *Account } // UnsetSecureEmailTestSuite 设置测试环境 func (suite *UnsetSecureEmailTestSuite) SetupSuite() { envFilepath := filepath.Join("testdata", "local.svc-jinmuid.env") suite.JinmuIDService = newJinmuIDServiceForTest() suite.Account = newTestingAccountFromEnvFile(envFilepath) } // TestUnsetSecureEmail 测试解绑安全邮箱 func (suite *UnsetSecureEmailTestSuite) TestUnsetSecureEmail() { t := suite.T() ctx := context.Background() // 发送通知 serialNumber := getUnSetEmailSerialNumber(suite.JinmuIDService, *suite.Account) // 获取最新验证码 mvc := getEmailVerificationCode(suite.JinmuIDService, *suite.Account) ctx, userID, err := mockSigninByPhonePassword(ctx, suite.JinmuIDService, suite.Account.phone, suite.Account.phonePassword, suite.Account.seed, suite.Account.nationCode) assert.NoError(t, err) req := new(proto.UnsetSecureEmailRequest) req.UserId = userID req.VerificationCode = mvc req.SerialNumber = serialNumber req.Email = suite.Account.email resp := new(proto.UnsetSecureEmailResponse) err = suite.JinmuIDService.UnsetSecureEmail(ctx, req, resp) assert.NoError(t, err) } // TestUnsetSecureEmailUserIdIsNull 设置安全邮箱userid为空 func (suite *UnsetSecureEmailTestSuite) TestUnsetSecureEmailUserIdIsNull() { t := suite.T() ctx := context.Background() // 发送通知 serialNumber := getUnSetEmailSerialNumber(suite.JinmuIDService, *suite.Account) // 获取最新验证码 mvc := getEmailVerificationCode(suite.JinmuIDService, *suite.Account) resp := new(proto.UnsetSecureEmailResponse) req := new(proto.UnsetSecureEmailRequest) req.UserId = suite.Account.userID req.VerificationCode = mvc req.SerialNumber = serialNumber req.Email = suite.Account.email err := suite.JinmuIDService.UnsetSecureEmail(ctx, req, resp) assert.Error(t, errors.New("[errcode:25000] secure email has been set"), err) } // TestUnsetSecureEmailVCIsNull verificationCode为空 func (suite *UnsetSecureEmailTestSuite) TestUnsetSecureEmailVCIsNull() { t := suite.T() ctx := context.Background() // 发送通知 serialNumber := getUnSetEmailSerialNumber(suite.JinmuIDService, *suite.Account) ctx, userID, err := mockSigninByPhonePassword(ctx, suite.JinmuIDService, suite.Account.phone, suite.Account.phonePassword, suite.Account.seed, suite.Account.nationCode) assert.NoError(t, err) req := new(proto.UnsetSecureEmailRequest) req.UserId = userID req.VerificationCode = suite.Account.mvcIsNull req.SerialNumber = serialNumber req.Email = suite.Account.email resp := new(proto.UnsetSecureEmailResponse) err = suite.JinmuIDService.UnsetSecureEmail(ctx, req, resp) assert.Error(t, errors.New("[errcode:31000] invalid vc record"), err) } // TestUnsetSecureEmailVCError verificationCode错误,过期 func (suite *UnsetSecureEmailTestSuite) TestUnsetSecureEmailVCError() { t := suite.T() ctx := context.Background() // 发送通知 serialNumber := getUnSetEmailSerialNumber(suite.JinmuIDService, *suite.Account) ctx, userID, err := mockSigninByPhonePassword(ctx, suite.JinmuIDService, suite.Account.phone, suite.Account.phonePassword, suite.Account.seed, suite.Account.nationCode) assert.NoError(t, err) req := new(proto.UnsetSecureEmailRequest) req.UserId = userID req.VerificationCode = suite.Account.mvcError req.SerialNumber = serialNumber req.Email = suite.Account.email resp := new(proto.UnsetSecureEmailResponse) err = suite.JinmuIDService.UnsetSecureEmail(ctx, req, resp) assert.Error(t, errors.New("[errcode:31000] invalid vc record"), err) } // TestUnsetSecureEmailSerialNumberIsNull serialnumber为空 func (suite *SetSecureEmailTestSuite) TestUnsetSecureEmailSerialNumberIsNull() { t := suite.T() ctx := context.Background() // 获取最新验证码 mvc := getEmailVerificationCode(suite.JinmuIDService, *suite.Account) ctx, userID, err := mockSigninByPhonePassword(ctx, suite.JinmuIDService, suite.Account.phone, suite.Account.phonePassword, suite.Account.seed, suite.Account.nationCode) assert.NoError(t, err) req := new(proto.UnsetSecureEmailRequest) req.UserId = userID req.VerificationCode = mvc req.SerialNumber = suite.Account.serialNumberIsNull req.Email = suite.Account.email resp := new(proto.UnsetSecureEmailResponse) err = suite.JinmuIDService.UnsetSecureEmail(ctx, req, resp) assert.Error(t, errors.New("[errcode:31000] invalid vc record"), err) } // TestUnsetSecureEmailIsNull email为空 func (suite *SetSecureEmailTestSuite) TestUnsetSecureEmailIsNull() { t := suite.T() ctx := context.Background() // 发送通知 serialNumber := getUnSetEmailSerialNumber(suite.JinmuIDService, *suite.Account) // 获取最新验证码 mvc := getEmailVerificationCode(suite.JinmuIDService, *suite.Account) ctx, userID, err := mockSigninByPhonePassword(ctx, suite.JinmuIDService, suite.Account.phone, suite.Account.phonePassword, suite.Account.seed, suite.Account.nationCode) assert.NoError(t, err) req := new(proto.UnsetSecureEmailRequest) req.UserId = userID req.VerificationCode = mvc req.SerialNumber = serialNumber req.Email = suite.Account.emailNull resp := new(proto.UnsetSecureEmailResponse) err = suite.JinmuIDService.UnsetSecureEmail(ctx, req, resp) assert.Error(t, errors.New("[errcode:23000] invalid email format"), err) } // TestUnsetSecureEmailFormatError email格式错误 func (suite *SetSecureEmailTestSuite) TestUnsetSecureEmailFormatError() { t := suite.T() ctx := context.Background() // 发送通知 serialNumber := getUnSetEmailSerialNumber(suite.JinmuIDService, *suite.Account) // 获取最新验证码 mvc := getEmailVerificationCode(suite.JinmuIDService, *suite.Account) ctx, userID, err := mockSigninByPhonePassword(ctx, suite.JinmuIDService, suite.Account.phone, suite.Account.phonePassword, suite.Account.seed, suite.Account.nationCode) assert.NoError(t, err) req := new(proto.UnsetSecureEmailRequest) req.UserId = userID req.VerificationCode = mvc req.SerialNumber = serialNumber req.Email = suite.Account.emailError resp := new(proto.UnsetSecureEmailResponse) err = suite.JinmuIDService.UnsetSecureEmail(ctx, req, resp) assert.Error(t, errors.New("[errcode:23000] invalid email format"), err) } // TestUnsetSecureEmailExist 邮箱已被其他用户使用 func (suite *SetSecureEmailTestSuite) TestUnsetSecureEmailExist() { t := suite.T() ctx := context.Background() // 发送通知 serialNumber := getUnSetEmailSerialNumber(suite.JinmuIDService, *suite.Account) // 获取最新验证码 mvc := getEmailVerificationCode(suite.JinmuIDService, *suite.Account) ctx, userID, err := mockSigninByPhonePassword(ctx, suite.JinmuIDService, suite.Account.phone, suite.Account.phonePassword, suite.Account.seed, suite.Account.nationCode) assert.NoError(t, err) req := new(proto.UnsetSecureEmailRequest) req.UserId = userID req.VerificationCode = mvc req.SerialNumber = serialNumber req.Email = suite.Account.email resp := new(proto.UnsetSecureEmailResponse) err = suite.JinmuIDService.UnsetSecureEmail(ctx, req, resp) assert.NoError(t, err) assert.Error(t, errors.New("[errcode:25000] secure email has been set"), err) } func (suite *UnsetSecureEmailTestSuite) TearDownSuite() { ctx := context.Background() suite.JinmuIDService.datastore.SafeCloseDB(ctx) } func TestUnsetSecureEmailTestSuite(t *testing.T) { suite.Run(t, new(UnsetSecureEmailTestSuite)) }
package environment import ( "context" "fmt" "os" "sync/atomic" "time" gomegaConfig "github.com/onsi/ginkgo/config" "github.com/onsi/gomega" "github.com/pkg/errors" "github.com/spf13/afero" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/client-go/kubernetes" _ "k8s.io/client-go/plugin/pkg/client/auth/oidc" //from https://github.com/kubernetes/client-go/issues/345 "k8s.io/client-go/rest" "code.cloudfoundry.org/quarks-operator/pkg/kube/client/clientset/versioned" "code.cloudfoundry.org/quarks-operator/pkg/kube/operator" "code.cloudfoundry.org/quarks-operator/testing" qstsclient "code.cloudfoundry.org/quarks-statefulset/pkg/kube/client/clientset/versioned" "code.cloudfoundry.org/quarks-utils/pkg/config" utils "code.cloudfoundry.org/quarks-utils/testing/integration" "code.cloudfoundry.org/quarks-utils/testing/machine" ) // Environment starts our operator and handles interaction with the k8s // cluster used in the tests type Environment struct { *utils.Environment Machine testing.Catalog } var ( namespaceCounter int32 ) const ( defaultTestMeltdownDuration = 10 defaultTestMeltdownRequeueAfter = 1 testPerNode = 200 portPerTest = 3 ) // testPerNode=200, portPerTest=1 // id = 200 * node + i + 1 // // namespaceCounter ParallelNode namespaceID conflict // 0 0 1 // 0 1 201 * // 0 2 401 * // 1 0 2 // 1 1 202 // 1 2 402 // 20 0 21 // 20 1 221 // 20 2 421 // 200 0 201 * // 200 1 401 * // 200 5 1201 // testPerNode=200, portPerTest=3 // // namespaceCounter ParallelNode namespaceID conflict // 600 0 603 * // 0 3 603 * // conflict at: 603, 803, 1003, 1203, ... // For testPerNode=198, portPerTest=3 // conflict at: 201, 204, 207, ... // NewEnvironment returns a new struct func NewEnvironment(kubeConfig *rest.Config) *Environment { atomic.AddInt32(&namespaceCounter, portPerTest) namespaceID := gomegaConfig.GinkgoConfig.ParallelNode*testPerNode + int(namespaceCounter) // the single namespace used by this test ns := utils.GetNamespaceName(namespaceID) env := &Environment{ Environment: &utils.Environment{ ID: namespaceID, Namespace: ns, KubeConfig: kubeConfig, Config: &config.Config{ CtxTimeOut: 10 * time.Second, MeltdownDuration: defaultTestMeltdownDuration * time.Second, MeltdownRequeueAfter: defaultTestMeltdownRequeueAfter * time.Second, MonitoredID: ns, OperatorNamespace: ns, Fs: afero.NewOsFs(), }, }, Machine: Machine{ Machine: machine.NewMachine(), }, } gomega.SetDefaultEventuallyTimeout(env.PollTimeout) gomega.SetDefaultEventuallyPollingInterval(env.PollInterval) return env } // SetupClientsets initializes kube clientsets func (e *Environment) SetupClientsets() error { var err error e.Clientset, err = kubernetes.NewForConfig(e.KubeConfig) if err != nil { return err } e.VersionedClientset, err = versioned.NewForConfig(e.KubeConfig) if err != nil { return err } e.QuarksStatefulSetClient, err = qstsclient.NewForConfig(e.KubeConfig) return err } // NodeIP returns a public IP of a node func (e *Environment) NodeIP() (string, error) { if override, ok := os.LookupEnv("CF_OPERATOR_NODE_IP"); ok { // The user has specified a particular node IP to use; return that. return override, nil } nodes, err := e.Clientset.CoreV1().Nodes().List(context.Background(), metav1.ListOptions{}) if err != nil { return "", errors.Wrap(err, "getting the list of nodes") } if len(nodes.Items) == 0 { return "", fmt.Errorf("got an empty list of nodes") } addresses := nodes.Items[0].Status.Addresses if len(addresses) == 0 { return "", fmt.Errorf("node has an empty list of addresses") } return addresses[0].Address, nil } // ApplyCRDs applies the CRDs to the cluster func ApplyCRDs(kubeConfig *rest.Config) error { err := operator.ApplyCRDs(context.Background(), kubeConfig) if err != nil { return err } return nil }