text
stringlengths
11
4.05M
package index import ( "math" "fmt" "strings" ) type Posting struct { docId int offsets []int termFrequency int } func (p Posting) String() string { return fmt.Sprintf("<DocId: %d, offsets:%v>", p.docId, p.offsets) } func NewPosting(docId int, offsets []int) *Posting { return &Posting{ docId: docId, termFrequency: len(offsets), offsets: offsets, } } type PostingsList []*Posting func (pl PostingsList) String() string { str := make([]string, len(pl)) for i, p := range pl { str[i] = p.String() } return strings.Join(str, " ") } func (pl PostingsList) length() int { n := 0 for _, p := range pl { n += len(p.offsets) } return n } func (pl PostingsList) get(i int) *Position { var sum int for j, p := range pl { if sum+p.termFrequency > i { return &Position{ pl[j].docId, pl[j].offsets[i-sum], } } sum += p.termFrequency } return nil } func (pl PostingsList) getByDocId(docId int) *Posting { // TODO: binary search for _, posting := range pl { if posting.docId == docId { return posting } } return nil } func (pl PostingsList) FirstPosition() *Position { if len(pl) == 0 { return nil } return &Position{ pl[0].docId, pl[0].offsets[0], } } func (pl PostingsList) LastPosition() *Position { length := len(pl) if length == 0 { return nil } lastPosting := pl[length-1] return &Position{ lastPosting.docId, lastPosting.offsets[len(lastPosting.offsets)-1], } } func (pl PostingsList) tf(docId int) float64 { if p := pl.getByDocId(docId); p != nil && p.termFrequency > 0 { return math.Log2(float64(p.termFrequency)) + 1 } return 0 }
package service import ( "encoding/json" "fmt" "io/mariomang/github/consts" "io/mariomang/github/domain" "io/mariomang/github/snowflake" ) func GenrateIDService(request *domain.RequestDomain) string { sf := snowflake.NewSnowFlake(request.WorkID, request.MachineID) id := sf.GetID() response, err := json.Marshal(domain.NewSuccessResponse("Success", request.WorkID, id)) if err != nil { emsg := fmt.Sprintf(consts.JSONMarshalErrorMsg, err) fmt.Println(emsg) return emsg } return string(response) }
package keys import ( "fmt" "strings" "testing" sdktestutil "github.com/cosmos/cosmos-sdk/testutil" "github.com/stretchr/testify/require" "github.com/cosmos/cosmos-sdk/crypto/hd" "github.com/ovrclk/akcmd/testutil" "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/crypto/keyring" sdk "github.com/cosmos/cosmos-sdk/types" ) func Test_runExportCmd(t *testing.T) { cmd := ExportKeyCommand() mockIn, mockOut := testutil.ApplyMockIO(cmd) defer mockIn.Cleanup() defer mockOut.Cleanup() // Now add a temporary keybase kbHome := t.TempDir() // create a key kb, err := keyring.New(sdk.KeyringServiceName(), keyring.BackendTest, kbHome, mockIn) require.NoError(t, err) t.Cleanup(func() { kb.Delete("keyname1") // nolint:errcheck }) path := sdk.GetConfig().GetFullBIP44Path() _, err = kb.NewAccount("keyname1", sdktestutil.TestMnemonic, "", path, hd.Secp256k1) require.NoError(t, err) // Now enter password args := []string{ fmt.Sprintf("--%s=%s", flags.FlagHome, kbHome), fmt.Sprintf("--%s=%s", flags.FlagKeyringBackend, keyring.BackendTest), fmt.Sprintf("--%s=%s", flags.FlagKeyringDir, kbHome), "keyname1", } mockIn.Reset("123456789\n123456789\n") require.NoError(t, cmd.Run(args)) resetExportOpts() argsUnsafeOnly := append([]string{"--unsafe"}, args...) require.Error(t, cmd.Run(argsUnsafeOnly)) resetExportOpts() argsUnarmoredHexOnly := append([]string{"--unarmored-hex"}, args...) require.Error(t, cmd.Run(argsUnarmoredHexOnly)) resetExportOpts() argsUnsafeUnarmoredHex := append([]string{"--unsafe", "--unarmored-hex"}, args...) runCmd := func() { defer func() { if err := recover().(error); err != nil { require.Error(t, err) require.Equal(t, "EOF", err.Error()) } }() err = cmd.Run(argsUnsafeUnarmoredHex) require.Error(t, err) require.Equal(t, "EOF", err.Error()) } runCmd() resetExportOpts() mockIn1, mockOut1 := testutil.ApplyMockIO(cmd) defer mockIn1.Cleanup() defer mockOut1.Cleanup() mockIn1.Reset("y\n") require.NoError(t, cmd.Run(argsUnsafeUnarmoredHex)) require.True(t, strings.HasSuffix(mockOut1.String(), "2485e33678db4175dc0ecef2d6e1fc493d4a0d7f7ce83324b6ed70afe77f3485\n")) //require.Equal(t, "2485e33678db4175dc0ecef2d6e1fc493d4a0d7f7ce83324b6ed70afe77f3485\n", // mockOut1.String()) } func resetExportOpts() { exportOpts.UnarmoredHex = false exportOpts.Unsafe = false }
package server import ( "fmt" "github.com/superboy724/wechatmessage/processer" "io/ioutil" "net/http" "strconv" ) type Server struct { port int processer processer.Processer } func (t *Server) Run() { portStr := strconv.Itoa(t.port) http.HandleFunc("/", t.read) http.ListenAndServe(":"+portStr, nil) } func (t *Server) SetProcesser(p processer.Processer) { t.processer = p } func NewServer(port int) *Server { server := &Server{ port: port, } return server } func (t *Server) read(w http.ResponseWriter, r *http.Request) { method := r.Method if method == "GET" { r.ParseForm() values := make(map[string]string, len(r.Form)) for key, value := range r.Form { values[key] = value[0] } res := t.processer.GetRequest(values) fmt.Fprintln(w, res) } if method == "POST" { r.ParseForm() values := make(map[string]string, len(r.Form)) for key, value := range r.Form { values[key] = value[0] } body, err := ioutil.ReadAll(r.Body) if err != nil { fmt.Fprintln(w, "") } res := t.processer.PostRequest(values, body) fmt.Fprintln(w, res) } }
package bloom func (filter *Filter) Probe(key string) bool { hashedKey := [][]byte{} value := false; for _, fn := range filter.Functions { hashedKey = append(hashedKey, fn([]byte(key))) } for _, hashBytes := range hashedKey { halfArr := (len(hashBytes)/2)-1; part := 0; for j := 0; j <= halfArr; j++ { part += int(hashBytes[j]) } value = filter.Hash[part] || value; part = 0; for j := halfArr; j <= (len(hashBytes)-1); j++ { part += int(hashBytes[j]) } value = filter.Hash[part] || value; } return value }
package testdata import ( "github.com/frk/gosql" "github.com/frk/gosql/internal/testdata/common" ) type UpdateFromblockJoinSingleQuery struct { User *common.User4 `rel:"test_user:u"` From struct { _ gosql.Relation `sql:"test_post:p"` _ gosql.LeftJoin `sql:"test_join1:j1,j1.post_id = p.id"` _ gosql.RightJoin `sql:"test_join2:j2,j2.join1_id = j1.id"` _ gosql.FullJoin `sql:"test_join3:j3,j3.join2_id = j2.id"` _ gosql.CrossJoin `sql:"test_join4:j4"` } Where struct { _ gosql.Column `sql:"u.id=p.user_id"` _ gosql.Column `sql:"p.is_spam"` } }
package main import ( "bytes" "encoding/csv" "flag" "fmt" "io" "io/ioutil" "os" "text/template" ) var funcMap = template.FuncMap{ "repeat": func(ctr int) (r []int) { for i := 0; i < ctr; i++ { r = append(r, i) } return }, } func main() { var headerFileName, footerFileName, bodyFileName, dataFileName string flag.StringVar(&headerFileName, "header", "", "header file name") flag.StringVar(&footerFileName, "footer", "", "footer file name") flag.StringVar(&bodyFileName, "body", "", "body file name") flag.StringVar(&dataFileName, "data", "", "data file name") flag.Parse() var headerTemplate, footerTemplate, bodyTemplate *template.Template var headerFile, footerFile, bodyFile []byte var err error var output string if headerFileName != "" { if headerFile, err = ioutil.ReadFile(headerFileName); err != nil { panic(fmt.Sprintf("error reading header template: %s", err)) } if headerTemplate, err = template.New(headerFileName).Funcs(funcMap).Parse(string(headerFile)); err != nil { panic(fmt.Sprintf("error parsing header template: %s", err)) } var headerDoc bytes.Buffer if err = headerTemplate.Execute(&headerDoc, nil); err != nil { panic(fmt.Sprintf("error executing header template: %s", err)) } output += headerDoc.String() } if bodyFileName != "" { if bodyFile, err = ioutil.ReadFile(bodyFileName); err != nil { panic(fmt.Sprintf("error reading body template: %s", err)) } if bodyTemplate, err = template.New(bodyFileName).Funcs(funcMap).Parse(string(bodyFile)); err != nil { panic(fmt.Sprintf("error parsing body template: %s", err)) } csvFile, err := os.Open(dataFileName) if err != nil { panic(fmt.Sprintf("error opening data file: %s", err)) } defer csvFile.Close() csvReader := csv.NewReader(csvFile) columns, err := csvReader.Read() if err != nil { panic(fmt.Sprintf("error reading columns line: %s", err)) } for { line, err := csvReader.Read() if err != nil { if err == io.EOF { break } continue } if len(line) == 0 { continue } data := map[string]string{} for i := range columns { data[columns[i]] = line[i] } var bodyDoc bytes.Buffer if err = bodyTemplate.Execute(&bodyDoc, data); err != nil { panic(fmt.Sprintf("error executing body template: %s", err)) } output += bodyDoc.String() } } if footerFileName != "" { if footerFile, err = ioutil.ReadFile(footerFileName); err != nil { panic(fmt.Sprintf("error reading footer template: %s", err)) } if footerTemplate, err = template.New(footerFileName).Funcs(funcMap).Parse(string(footerFile)); err != nil { panic(fmt.Sprintf("error parsing footer template: %s", err)) } var footerDoc bytes.Buffer if err = footerTemplate.Execute(&footerDoc, nil); err != nil { panic(fmt.Sprintf("error executing footer template: %s", err)) } output += output + footerDoc.String() } fmt.Println(output) }
/* Copyright 2015 The Kubernetes Authors 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 dockertools import ( "strconv" "github.com/golang/glog" "k8s.io/kubernetes/pkg/api" ) // This file contains all docker label related constants and functions, including: // * label setters and getters // * label filters (maybe in the future) const ( kubernetesPodNameLabel = "io.kubernetes.pod.name" kubernetesPodNamespaceLabel = "io.kubernetes.pod.namespace" kubernetesPodUID = "io.kubernetes.pod.uid" kubernetesPodLabel = "io.kubernetes.pod.data" kubernetesTerminationGracePeriodLabel = "io.kubernetes.pod.terminationGracePeriod" kubernetesContainerLabel = "io.kubernetes.container.name" kubernetesContainerRestartCountLabel = "io.kubernetes.container.restartCount" ) func newLabels(container *api.Container, pod *api.Pod, restartCount int) map[string]string { // TODO (random-liu) Move more label initialization here labels := map[string]string{} labels[kubernetesPodNameLabel] = pod.Name labels[kubernetesPodNamespaceLabel] = pod.Namespace labels[kubernetesPodUID] = string(pod.UID) labels[kubernetesContainerRestartCountLabel] = strconv.Itoa(restartCount) return labels } func getRestartCountFromLabel(labels map[string]string) (restartCount int, err error) { if restartCountString, found := labels[kubernetesContainerRestartCountLabel]; found { restartCount, err = strconv.Atoi(restartCountString) if err != nil { // This really should not happen. Just set restartCount to 0 to handle this abnormal case restartCount = 0 } } else { // Get restartCount from docker label. If there is no restart count label in a container, // it should be an old container or an invalid container, we just set restart count to 0. // Do not report error, because there should be many old containers without this label now glog.V(3).Infof("Container doesn't have label %s, it may be an old or invalid container", kubernetesContainerRestartCountLabel) } return restartCount, err }
package database import ( "reflect" "testing" "time" "github.com/ubclaunchpad/pinpoint/protobuf/models" ) func TestDatabase_AddNewUser_GetUser(t *testing.T) { type args struct { u *models.User e *models.EmailVerification } type errs struct { addUser bool getUser bool getVerify bool } tests := []struct { name string args args err errs }{ {"invalid", args{ &models.User{}, &models.EmailVerification{ Email: "asdf@ghi.com", Hash: "asdf", Expiry: time.Now().Add(time.Hour).Unix(), }, }, errs{true, true, true}}, {"valid", args{ &models.User{ Email: "abc@def.com", Name: "Bob Ross", Hash: "qwer1234", }, &models.EmailVerification{ Email: "abc@def.com", Hash: "asdf", Expiry: time.Now().Add(time.Hour).Unix(), }, }, errs{false, false, false}}, {"expired", args{ &models.User{ Email: "abc@def.com", Name: "Bob Ross", Hash: "qwer1234", }, &models.EmailVerification{ Email: "abc@def.com", Hash: "asdf", Expiry: time.Now().Add(-time.Hour).Unix(), }, }, errs{false, false, true}}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { db, _ := newTestDB(t) defer db.DeleteUser(tt.args.u.Email) if err := db.AddNewUser(tt.args.u, tt.args.e); (err != nil) != tt.err.addUser { t.Errorf("Database.AddNewUser() error = %v, wantErr %v", err, tt.err.addUser) } u, err := db.GetUser(tt.args.u.Email) if (err != nil) != tt.err.getUser { t.Errorf("Database.GetUser() error = %v, wantErr %v", err, tt.err.getUser) return } if !tt.err.getUser && !reflect.DeepEqual(tt.args.u, u) { t.Errorf("expected: %+v, actual %+v", tt.args.u, u) return } v, err := db.GetEmailVerification(tt.args.e.Email, tt.args.e.Hash) if (err != nil) != tt.err.getVerify { t.Errorf("Database.GetEmailVerification() error = %v, wantErr %v", err, tt.err.getVerify) return } if !tt.err.getVerify && (v.Hash != tt.args.e.Hash || v.Email != tt.args.e.Email) { t.Errorf("expected: %+v, actual %+v", tt.args.e, v) return } }) } } func TestDatabase_AddNewClub_GetClub(t *testing.T) { type args struct { c *models.Club cu *models.ClubUser } type errs struct { addClub bool getClub bool getClubUsers bool } tests := []struct { name string args args err errs }{ {"valid", args{ &models.Club{ ClubID: "1234", Description: "1337 h4x0r", }, &models.ClubUser{ ClubID: "1234", Email: "abc@def.com", Role: "President", }, }, errs{false, false, false}}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { db, _ := newTestDB(t) defer db.DeleteClub(tt.args.c.ClubID) if err := db.AddNewClub(tt.args.c, tt.args.cu); (err != nil) != tt.err.addClub { t.Errorf("Database.AddNewClub() error = %v, wantErr %v", err, tt.err.addClub) } club, err := db.GetClub(tt.args.c.ClubID) if (err != nil) != tt.err.getClub { t.Errorf("Database.GetClub() error = %v, wantErr %v", err, tt.err.getClub) } if !reflect.DeepEqual(tt.args.c, club) { t.Errorf("Failed to get expect club, expected: %+v, actual %+v", tt.args.c, club) return } _, err = db.GetAllClubUsers(tt.args.c.ClubID) if (err != nil) != tt.err.getClubUsers { t.Errorf("Database.GetAllClubUsers() error = %v, wantErr %v", err, tt.err.getClubUsers) } }) } }
package main import ( "errors" "fmt" ) func echo(request string) (string, error) { if request == "" { return "", errors.New("empty request") } return request, nil } func main() { requests := []string{"", "hello"} for _, r := range requests { if resp, err := echo(r); err != nil { continue } else { fmt.Printf("response : %s\n", resp) } } }
package content import ( "errors" "fmt" ) type Ranger struct { numHunks int } func NewRanger(hunks int) Ranger { return Ranger{ numHunks: hunks, } } func (r Ranger) BuildRange(contentLength int64) ([]string, error) { if contentLength == 0 { return []string{}, errors.New("content length cannot be zero") } var ranges []string hunkSize := contentLength / int64(r.numHunks) if hunkSize == 0 { hunkSize = 2 } iterations := (contentLength / hunkSize) remainder := contentLength % int64(hunkSize) for i := int64(0); i < int64(iterations); i++ { lowerByte := i * hunkSize upperByte := ((i + 1) * hunkSize) - 1 if i == int64(iterations-1) { upperByte += remainder } bytes := fmt.Sprintf("%d-%d", lowerByte, upperByte) ranges = append(ranges, bytes) } return ranges, nil }
package 滑动窗口 const ( inf = 1000000000 ) func balancedString(s string) int { hash := make(map[uint8]int) hash['Q'], hash['W'], hash['E'], hash['R'] = 0, 1, 2, 3 wholeCount := make([]int, 4) // 字符串的字符信息 for i := 0; i < len(s); i++ { wholeCount[hash[s[i]]]++ } windowNeedCount := make([]int, 4) // 窗口所需要的字符信息 for i := 0; i < len(windowNeedCount); i++ { windowNeedCount[i] = wholeCount[i] - len(s)/4 } windowOwnCount := make([]int, 4) // 窗口当前拥有的字符信息 first, last := 0, 0 ans := inf for last < len(s) { windowOwnCount[hash[s[last]]]++ for first < len(s) && isFull(windowNeedCount, windowOwnCount) { ans = min(ans, last-first+1) windowOwnCount[hash[s[first]]]-- first++ } last++ } return ans } func min(a, b int) int { if a > b { return b } return a } // 判断窗口内的字符 满足 窗口所需要的字符 func isFull(windowNeedCount []int, windowOwnCount []int) bool { for i := 0; i < len(windowNeedCount); i++ { if windowNeedCount[i] > windowOwnCount[i] { return false } } return true } /* 总结 1. 这题是滑动窗口的变形版。 2. 这题和之前的滑动串口不太一样的就是: (1) 需要先获得窗口所需要的信息,在这里所需要的信息就是: 子串至少包含哪些字符,才能使字符串转为平衡字符串。 */
package http import ( "net" "net/http" ) func NewClient(options *Options) *http.Client { tr := &http.Transport{ Proxy: http.ProxyFromEnvironment, DialContext: (&net.Dialer{ Timeout: options.Timeout, KeepAlive: options.KeepAlive, DualStack: options.DualStack, }).DialContext, TLSHandshakeTimeout: options.TLSHandshakeTimeout, DisableKeepAlives: options.DisableKeepAlives, MaxIdleConns: options.MaxIdleConn, MaxIdleConnsPerHost: options.MaxIdleConnPerHost, MaxConnsPerHost: options.MaxConnsPerHost, IdleConnTimeout: options.IdleConnTimeout, ForceAttemptHTTP2: options.HTTP2, ExpectContinueTimeout: options.ExpectContinueTimeout, } return &http.Client{Transport: tr} }
package oracle import ( sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" "github.com/irisnet/irismod/modules/oracle/keeper" "github.com/irisnet/irismod/modules/oracle/types" ) // NewHandler returns a handler for all the "oracle" type messages func NewHandler(k keeper.Keeper) sdk.Handler { return func(ctx sdk.Context, msg sdk.Msg) (*sdk.Result, error) { ctx = ctx.WithEventManager(sdk.NewEventManager()) switch msg := msg.(type) { case *types.MsgCreateFeed: return handleMsgCreateFeed(ctx, k, msg) case *types.MsgStartFeed: return handleMsgStartFeed(ctx, k, msg) case *types.MsgPauseFeed: return handleMsgPauseFeed(ctx, k, msg) case *types.MsgEditFeed: return handleMsgEditFeed(ctx, k, msg) default: return nil, sdkerrors.Wrapf(sdkerrors.ErrUnknownRequest, "unrecognized %s message type: %T", types.ModuleName, msg) } } } // handleMsgCreateFeed handles MsgCreateFeed func handleMsgCreateFeed(ctx sdk.Context, k keeper.Keeper, msg *types.MsgCreateFeed) (*sdk.Result, error) { err := k.CreateFeed(ctx, msg) if err != nil { return nil, err } ctx.EventManager().EmitEvents(sdk.Events{ sdk.NewEvent( sdk.EventTypeMessage, sdk.NewAttribute(sdk.AttributeKeyModule, types.AttributeValueCategory), sdk.NewAttribute(sdk.AttributeKeySender, msg.Creator.String()), ), }) return &sdk.Result{Events: ctx.EventManager().ABCIEvents()}, nil } // handleMsgStartFeed handles MsgStartFeed func handleMsgStartFeed(ctx sdk.Context, k keeper.Keeper, msg *types.MsgStartFeed) (*sdk.Result, error) { if err := k.StartFeed(ctx, msg); err != nil { return nil, err } ctx.EventManager().EmitEvents(sdk.Events{ sdk.NewEvent( sdk.EventTypeMessage, sdk.NewAttribute(sdk.AttributeKeyModule, types.AttributeValueCategory), sdk.NewAttribute(sdk.AttributeKeySender, msg.Creator.String()), ), }) return &sdk.Result{Events: ctx.EventManager().ABCIEvents()}, nil } // handleMsgPauseFeed handles MsgPauseFeed func handleMsgPauseFeed(ctx sdk.Context, k keeper.Keeper, msg *types.MsgPauseFeed) (*sdk.Result, error) { if err := k.PauseFeed(ctx, msg); err != nil { return nil, err } ctx.EventManager().EmitEvents(sdk.Events{ sdk.NewEvent( sdk.EventTypeMessage, sdk.NewAttribute(sdk.AttributeKeyModule, types.AttributeValueCategory), sdk.NewAttribute(sdk.AttributeKeySender, msg.Creator.String()), ), }) return &sdk.Result{Events: ctx.EventManager().ABCIEvents()}, nil } // handleMsgEditFeed handles MsgEditFeed func handleMsgEditFeed(ctx sdk.Context, k keeper.Keeper, msg *types.MsgEditFeed) (*sdk.Result, error) { if err := k.EditFeed(ctx, msg); err != nil { return nil, err } ctx.EventManager().EmitEvents(sdk.Events{ sdk.NewEvent( sdk.EventTypeMessage, sdk.NewAttribute(sdk.AttributeKeyModule, types.AttributeValueCategory), sdk.NewAttribute(sdk.AttributeKeySender, msg.Creator.String()), ), }) return &sdk.Result{Events: ctx.EventManager().ABCIEvents()}, nil }
package hub import ( "log" "strings" "sync" "github.com/desertbit/glue" "github.com/garyburd/redigo/redis" ) var ( sockets = map[*glue.Socket]map[string]bool{} topics = map[string]map[*glue.Socket]bool{} pubconn redis.Conn subconn redis.PubSubConn l sync.RWMutex ) func InitHub(url string) error { c, err := redis.DialURL(url) if err != nil { return err } pubconn = c c, err = redis.DialURL(url) if err != nil { return err } subconn = redis.PubSubConn{c} go func() { for { switch v := subconn.Receive().(type) { case redis.Message: EmitLocal(v.Channel, string(v.Data)) case error: panic(v) } } }() return nil } func Subscribe(s *glue.Socket, t string) error { l.Lock() defer l.Unlock() _, ok := sockets[s] if !ok { sockets[s] = map[string]bool{} } sockets[s][t] = true _, ok = topics[t] if !ok { topics[t] = map[*glue.Socket]bool{} err := subconn.Subscribe(t) if err != nil { return err } } topics[t][s] = true return nil } func UnsubscribeAll(s *glue.Socket) error { l.Lock() defer l.Unlock() for t := range sockets[s] { delete(topics[t], s) if len(topics[t]) == 0 { delete(topics, t) err := subconn.Unsubscribe(t) if err != nil { return err } } } delete(sockets, s) return nil } func Emit(t string, m string) error { _, err := pubconn.Do("PUBLISH", t, m) return err } func EmitLocal(t string, m string) { l.RLock() defer l.RUnlock() for s := range topics[t] { s.Write(m) } } func HandleSocket(s *glue.Socket) { s.OnClose(func() { err := UnsubscribeAll(s) if err != nil { log.Print(err) } }) s.OnRead(func(data string) { fields := strings.Fields(data) if len(fields) == 0 { return } switch fields[0] { case "watch": if len(fields) != 2 { return } err := Subscribe(s, fields[1]) if err != nil { log.Print(err) } case "touch": if len(fields) != 4 { return } err := Emit(fields[1], "touch:"+fields[2]+","+fields[3]) if err != nil { log.Print(err) } } }) }
package pn532 import ( "errors" ) var ( ErrAuthentificationFailed = errors.New("authentification failed") ) // Mifare Classic methods func MifareClassicIsFirstBlock(b uint32) bool { if b < 128 { return b%4 == 0 } return b%16 == 0 } func MifareClassicIsTrailerBlock(b uint32) bool { if b < 128 { return (b+1)%4 == 0 } return (b+1)%16 == 0 } // Tries to authenticate a block of memory on a MIFARE card using the INDATAEXCHANGE command. func MifareClassicAuthenticateBlock(device Device, uid []byte, blockNumber uint8, keyType uint8, key []byte) error { // COPY uid & key into device? p := make([]byte, len(uid)+10) p[0] = COMMAND_INDATAEXCHANGE /* Data Exchange Header */ p[1] = 1 /* Max card numbers */ p[2] = MIFARE_CMD_AUTH_A + (keyType & 0x01) p[3] = blockNumber /* Block Number (1K = 0..63, 4K = 0..255 */ copy(p[4:10], key) copy(p[10:], uid) if !SendCommandCheckAck(device, p, defaultTimeoutMs) { return ErrNoResponse } p = make([]byte, 12) device.ReadData(p) if p[7] != 0x00 { return ErrAuthentificationFailed } return nil } // Tries to read an entire 16-byte data block at the specified block address func MifareClassicReadDataBlock(device Device, blockNumber uint8) ([]byte, error) { p := []byte{ COMMAND_INDATAEXCHANGE, 1, /* Card number */ MIFARE_CMD_READ, /* Mifare Read command = 0x30 */ blockNumber, /* Block Number (0..63 for 1K, 0..255 for 4K) */ } if !SendCommandCheckAck(device, p, defaultTimeoutMs) { return nil, ErrNoResponse } p = make([]byte, 26) device.ReadData(p) if p[7] != 0x00 { return nil, ErrInvalidResponse } return p[8:24], nil } // Tries to write an entire 16-byte data block at the specified block address func MifareClassicWriteDataBlock(device Device, blockNumber uint8, data []byte) error { if len(data) != 16 { return ErrInvalidDataLen } p := make([]byte, 26) p[0] = COMMAND_INDATAEXCHANGE p[1] = 1 /* Card number */ p[2] = MIFARE_CMD_WRITE /* Mifare Write command = 0xA0 */ p[3] = blockNumber /* Block Number (0..63 for 1K, 0..255 for 4K) */ copy(p[4:20], data) if !SendCommandCheckAck(device, p[:20], defaultTimeoutMs) { return ErrNoResponse } device.ReadData(p) return nil } // Formats a Mifare Classic card to store NDEF Records func MifareClassicFormatNDEF(device Device) (err error) { // Note 0xA0 0xA1 0xA2 0xA3 0xA4 0xA5 must be used for key A for the MAD sector in NDEF records (sector 0) if err = MifareClassicWriteDataBlock(device, 1, []byte{0x14, 0x01, 0x03, 0xE1, 0x03, 0xE1, 0x03, 0xE1, 0x03, 0xE1, 0x03, 0xE1, 0x03, 0xE1, 0x03, 0xE1}); err != nil { return } if err = MifareClassicWriteDataBlock(device, 2, []byte{0x03, 0xE1, 0x03, 0xE1, 0x03, 0xE1, 0x03, 0xE1, 0x03, 0xE1, 0x03, 0xE1, 0x03, 0xE1, 0x03, 0xE1}); err != nil { return } return MifareClassicWriteDataBlock(device, 3, []byte{0xA0, 0xA1, 0xA2, 0xA3, 0xA4, 0xA5, 0x78, 0x77, 0x88, 0xC1, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF}) } // Writes an NDEF URI Record to the specified sector (1..15) // Note that this function assumes that the Mifare Classic card is // already formatted to work as an "NFC Forum Tag" and uses a MAD1 // file system. You can use the NXP TagWriter app on Android to // properly format cards for this func MifareClassicWriteNDEFURI(device Device, sectorNumber uint8, id uint8, url string) (err error) { if sectorNumber < 1 || sectorNumber > 15 { err = errors.New("invalid sector number") return } length := byte(len(url)) if length < 1 || length > 38 { err = ErrInvalidDataLen return } // Note 0xD3 0xF7 0xD3 0xF7 0xD3 0xF7 must be used for key A in NDEF records // Setup the sector buffer (w/pre-formatted TLV wrapper and NDEF message) sectorbuffer1 := []byte{0x00, 0x00, 0x03, length + 5, 0xD1, 0x01, length + 1, 0x55, id, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00} sectorbuffer2 := []byte{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00} sectorbuffer3 := []byte{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00} sectorbuffer4 := []byte{0xD3, 0xF7, 0xD3, 0xF7, 0xD3, 0xF7, 0x7F, 0x07, 0x88, 0x40, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF} if length <= 6 { copy(sectorbuffer1[9:], url) sectorbuffer1[length+9] = 0xFE } else if length == 7 { // 0xFE needs to be wrapped around to next block copy(sectorbuffer1[9:], url) sectorbuffer2[0] = 0xFE } else if (length > 7) && (length <= 22) { // Url fits in two blocks copy(sectorbuffer1[9:], url[:7]) copy(sectorbuffer2, url[7:]) sectorbuffer2[length-7] = 0xFE } else if length == 23 { // 0xFE needs to be wrapped around to final block copy(sectorbuffer1[9:], url[:7]) copy(sectorbuffer2, url[7:]) sectorbuffer3[0] = 0xFE } else { // Url fits in three blocks copy(sectorbuffer1[9:], url[:7]) copy(sectorbuffer2, url[7:23]) copy(sectorbuffer3, url[23:]) sectorbuffer3[length-22] = 0xFE } sectorNumber *= 4 if err = MifareClassicWriteDataBlock(device, sectorNumber, sectorbuffer1); err != nil { return } if err = MifareClassicWriteDataBlock(device, sectorNumber+1, sectorbuffer2); err != nil { return } if err = MifareClassicWriteDataBlock(device, sectorNumber+2, sectorbuffer3); err != nil { return } return MifareClassicWriteDataBlock(device, sectorNumber+3, sectorbuffer4) } // Mifare Ultralight methods // Tries to read an entire 4-byte page at the specified address func MifareUltralightReadPage(device Device, page uint8) (data []byte, err error) { if page >= 64 { err = ErrPageOutOfRange return } p := []byte{ COMMAND_INDATAEXCHANGE, 1, /* Card number */ MIFARE_CMD_READ, /* Mifare Read command = 0x30 */ page, } if !SendCommandCheckAck(device, p, defaultTimeoutMs) { err = ErrNoResponse return } p = make([]byte, 26) if p[7] != 0x00 { err = ErrInvalidResponse return } // Copy the 4 data bytes to the output buffer Block // content starts at byte 9 of a valid response // Note that the command actually reads 16 byte or 4 // pages at a time ... simply discard the last 12 bytes data = p[8:14] return } // Tries to write an entire 4-byte page at the specified block address func MifareUltralightWritePage(device Device, page uint8, data []byte) (err error) { if page >= 64 { err = ErrPageOutOfRange return } if len(data) != 4 { err = ErrInvalidDataLen return } p := []byte{ COMMAND_INDATAEXCHANGE, 1, /* Card number */ MIFARE_ULTRALIGHT_CMD_WRITE, /* Mifare Ultralight Write command = 0xA2 */ page, /* Page Number (0..63 for most cases) */ data[0], data[1], data[2], data[3], } if !SendCommandCheckAck(device, p, defaultTimeoutMs) { err = ErrNoResponse return } p = make([]byte, 26) device.ReadData(p) return nil }
package entity type User struct { } func (u User) GetUserByID(id int32) { }
package entity import ( "github.com/google/uuid" ) type ForumThread struct { ID uuid.UUID `db:"id"` Title string `db:"title"` Description string `db:"description"` } type ForumPost struct { ID uuid.UUID `db:"id"` ThreadID uuid.UUID `db:"thread_id"` ThreadTitle string Title string `db:"title"` Content string `db:"content"` Count int `db:"comms_count"` } type ForumComment struct { ID uuid.UUID `db:"id"` PostID uuid.UUID `db:"post_id"` Content string `db:"content"` } type User struct { ID uuid.UUID `db:"id"` Username string `db:"username"` Password string `db:"password"` } type ThreadStore interface { Threads() ([]ForumThread, error) CreateThread(t *ForumThread) error ReadThread(id uuid.UUID) (ForumThread, error) UpdateThread(t *ForumThread) error DeleteThread(id uuid.UUID) error } type PostStore interface { CreatePost(p *ForumPost) error ReadPost(id uuid.UUID) (ForumPost, error) ReadPostsByThread(threadID uuid.UUID) ([]ForumPost, error) UpdatePost(p *ForumPost) error DeletePost(id uuid.UUID) error } type CommentStore interface { CreateComment(c *ForumComment) error ReadComment(id uuid.UUID) (ForumComment, error) ReadCommentsByPost(postID uuid.UUID) ([]ForumComment, error) UpdateComment(c *ForumComment) error DeleteComment(id uuid.UUID) error } type UserStore interface { User(id uuid.UUID) (User, error) GetUserByUsername(username string) (User, error) Create(u *User) error Update(u *User) error Delete(id uuid.UUID) error } type Store interface { ThreadStore PostStore CommentStore UserStore }
package api import ( "crypto/tls" "fmt" "io" "math/rand" "net/http" "net/url" "os" "path/filepath" "sync" "time" "github.com/apex/log" "github.com/pkg/errors" "github.com/vbauerster/mpb/v4" "github.com/vbauerster/mpb/v4/decor" ) func getProxy(proxy string) func(*http.Request) (*url.URL, error) { if len(proxy) > 0 { proxyURL, err := url.Parse(proxy) if err != nil { log.WithError(err).Error("bad proxy url") } return http.ProxyURL(proxyURL) } return http.ProxyFromEnvironment } // DownloadFile will download a url to a local file. It's efficient because it will // write as it downloads and not load the whole file into memory. We pass an io.TeeReader // into Copy() to report progress on the download. func DownloadFile(url, proxy string, insecure bool) error { client := &http.Client{ Transport: &http.Transport{ Proxy: getProxy(proxy), TLSClientConfig: &tls.Config{InsecureSkipVerify: insecure}, }, } req, err := http.NewRequest("GET", url, nil) if err != nil { return errors.Wrap(err, "cannot create http request") } resp, err := client.Do(req) if err != nil { return err } defer resp.Body.Close() if resp.StatusCode != http.StatusOK { return fmt.Errorf("server return status: %s", resp.Status) } size := resp.ContentLength // create dest destName := filepath.Base(url) dest, err := os.Create(destName) if err != nil { return errors.Wrapf(err, "cannot create %s", destName) } defer dest.Close() p := mpb.New( mpb.WithWidth(60), mpb.WithRefreshRate(180*time.Millisecond), ) bar := p.AddBar(size, mpb.BarStyle("[=>-|"), mpb.PrependDecorators( decor.CountersKibiByte("\t% 6.1f / % 6.1f"), ), mpb.AppendDecorators( decor.EwmaETA(decor.ET_STYLE_MMSS, float64(size)/2048), decor.Name(" ] "), decor.AverageSpeed(decor.UnitKiB, "% .2f"), ), ) // create proxy reader reader := bar.ProxyReader(resp.Body) // and copy from reader, ignoring errors io.Copy(dest, reader) p.Wait() return nil } func multiDownload(urls []string) { doneWg := new(sync.WaitGroup) p := mpb.New(mpb.WithWidth(64), mpb.WithWaitGroup(doneWg)) numBars := 4 var bars []*mpb.Bar var downloadWgg []*sync.WaitGroup for i := 0; i < numBars; i++ { wg := new(sync.WaitGroup) wg.Add(1) downloadWgg = append(downloadWgg, wg) task := fmt.Sprintf("Task#%02d:", i) job := "downloading" b := p.AddBar(rand.Int63n(201)+100, mpb.BarRemoveOnComplete(), mpb.PrependDecorators( decor.Name(task, decor.WC{W: len(task) + 1, C: decor.DidentRight}), decor.Name(job, decor.WCSyncSpaceR), decor.CountersNoUnit("%d / %d", decor.WCSyncWidth), ), mpb.AppendDecorators(decor.Percentage(decor.WC{W: 5})), ) go newTask(wg, b, i+1) bars = append(bars, b) } for i := 0; i < numBars; i++ { doneWg.Add(1) i := i go func() { task := fmt.Sprintf("Task#%02d:", i) job := "installing" // preparing delayed bars b := p.AddBar(rand.Int63n(101)+100, mpb.BarReplaceOnComplete(bars[i]), mpb.BarClearOnComplete(), mpb.PrependDecorators( decor.Name(task, decor.WC{W: len(task) + 1, C: decor.DidentRight}), decor.OnComplete(decor.Name(job, decor.WCSyncSpaceR), "done!"), decor.OnComplete(decor.EwmaETA(decor.ET_STYLE_MMSS, 60, decor.WCSyncWidth), "")), mpb.AppendDecorators( decor.OnComplete(decor.Percentage(decor.WC{W: 5}), ""), ), ) // waiting for download to complete, before starting install job downloadWgg[i].Wait() go newTask(doneWg, b, numBars-i) }() } p.Wait() } func newTask(wg *sync.WaitGroup, b *mpb.Bar, incrBy int) { defer wg.Done() max := 100 * time.Millisecond for !b.Completed() { start := time.Now() time.Sleep(time.Duration(rand.Intn(10)+1) * max / 10) // ewma based decorators require work duration measurement b.IncrBy(incrBy, time.Since(start)) } }
package main import ( "github.com/astaxie/beego" "github.com/astaxie/beego/logs" "tesou.io/platform/brush-parent/brush-core/common/routers" ) func init() { router := &routers.MyRouter{} router.Hello() } func main() { beeRun() } func beeRun() { beego.LoadAppConfig("ini", "conf/app.conf") logs.SetLogger(logs.AdapterConsole, `{"level":1,"color":true}`) //logs.SetLogger(logs.AdapterFile,`{"filename":"brush-web.log","level":7,"maxlines":0,"maxsize":0,"daily":true,"maxdays":10,"color":true}`) //输出文件名和行号 logs.EnableFuncCallDepth(true) //异步输出日志 //logs.Async(1e3) //启动 beego.Run() }
package main import ( "fmt" ) const ( steps = 303 rounds = 2017 ) func main() { var cur int buffer := []int{0} for i := 1; i <= rounds; i++ { cur = (cur + steps) % len(buffer) + 1 buffer = append(buffer, 0) copy(buffer[cur+1:], buffer[cur:]) buffer[cur] = i } cur = (cur + 1) % len(buffer) fmt.Println(buffer[cur]) }
package suites import ( "context" "fmt" "net/http" "testing" "time" log "github.com/sirupsen/logrus" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/suite" "github.com/valyala/fasthttp" ) type HighAvailabilityWebDriverSuite struct { *RodSuite } func NewHighAvailabilityWebDriverSuite() *HighAvailabilityWebDriverSuite { return &HighAvailabilityWebDriverSuite{ RodSuite: NewRodSuite(""), } } func (s *HighAvailabilityWebDriverSuite) SetupSuite() { s.BaseSuite.SetupSuite() browser, err := StartRod() if err != nil { log.Fatal(err) } s.RodSession = browser } func (s *HighAvailabilityWebDriverSuite) TearDownSuite() { err := s.RodSession.Stop() if err != nil { log.Fatal(err) } } func (s *HighAvailabilityWebDriverSuite) SetupTest() { s.Page = s.doCreateTab(s.T(), HomeBaseURL) s.verifyIsHome(s.T(), s.Page) } func (s *HighAvailabilityWebDriverSuite) TearDownTest() { s.collectCoverage(s.Page) s.MustClose() } func (s *HighAvailabilityWebDriverSuite) TestShouldKeepUserSessionActive() { ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second) defer func() { cancel() s.collectScreenshot(ctx.Err(), s.Page) }() secret := s.doRegisterThenLogout(s.T(), s.Context(ctx), "john", "password") err := haDockerEnvironment.Restart("redis-node-0") s.Require().NoError(err) s.doLoginTwoFactor(s.T(), s.Context(ctx), "john", "password", false, secret, "") s.verifyIsSecondFactorPage(s.T(), s.Context(ctx)) } func (s *HighAvailabilityWebDriverSuite) TestShouldKeepUserSessionActiveWithPrimaryRedisNodeFailure() { ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second) defer func() { cancel() s.collectScreenshot(ctx.Err(), s.Page) }() secret := s.doRegisterThenLogout(s.T(), s.Context(ctx), "john", "password") s.doLoginTwoFactor(s.T(), s.Context(ctx), "john", "password", false, secret, "") s.verifyIsSecondFactorPage(s.T(), s.Context(ctx)) err := haDockerEnvironment.Stop("redis-node-0") s.Require().NoError(err) defer func() { err = haDockerEnvironment.Start("redis-node-0") s.Require().NoError(err) }() s.doVisit(s.T(), s.Context(ctx), HomeBaseURL) s.verifyIsHome(s.T(), s.Context(ctx)) // Verify the user is still authenticated. s.doVisit(s.T(), s.Context(ctx), GetLoginBaseURL(BaseDomain)) s.verifyIsSecondFactorPage(s.T(), s.Context(ctx)) // Then logout and login again to check we can see the secret. s.doLogout(s.T(), s.Context(ctx)) s.verifyIsFirstFactorPage(s.T(), s.Context(ctx)) s.doLoginTwoFactor(s.T(), s.Context(ctx), "john", "password", false, secret, fmt.Sprintf("%s/secret.html", SecureBaseURL)) s.verifySecretAuthorized(s.T(), s.Context(ctx)) } func (s *HighAvailabilityWebDriverSuite) TestShouldKeepUserSessionActiveWithPrimaryRedisSentinelFailureAndSecondaryRedisNodeFailure() { ctx, cancel := context.WithTimeout(context.Background(), 90*time.Second) defer func() { cancel() s.collectScreenshot(ctx.Err(), s.Page) }() secret := s.doRegisterThenLogout(s.T(), s.Context(ctx), "john", "password") s.doLoginTwoFactor(s.T(), s.Context(ctx), "john", "password", false, secret, "") s.verifyIsSecondFactorPage(s.T(), s.Context(ctx)) err := haDockerEnvironment.Stop("redis-sentinel-0") s.Require().NoError(err) defer func() { err = haDockerEnvironment.Start("redis-sentinel-0") s.Require().NoError(err) }() err = haDockerEnvironment.Stop("redis-node-2") s.Require().NoError(err) defer func() { err = haDockerEnvironment.Start("redis-node-2") s.Require().NoError(err) }() s.doVisit(s.T(), s.Context(ctx), HomeBaseURL) s.verifyIsHome(s.T(), s.Context(ctx)) // Verify the user is still authenticated. s.doVisit(s.T(), s.Context(ctx), GetLoginBaseURL(BaseDomain)) s.verifyIsSecondFactorPage(s.T(), s.Context(ctx)) } func (s *HighAvailabilityWebDriverSuite) TestShouldKeepUserDataInDB() { ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second) defer func() { cancel() s.collectScreenshot(ctx.Err(), s.Page) }() secret := s.doRegisterThenLogout(s.T(), s.Context(ctx), "john", "password") err := haDockerEnvironment.Restart("mariadb") s.Require().NoError(err) s.doLoginTwoFactor(s.T(), s.Context(ctx), "john", "password", false, secret, "") s.verifyIsSecondFactorPage(s.T(), s.Context(ctx)) } func (s *HighAvailabilityWebDriverSuite) TestShouldKeepSessionAfterAutheliaRestart() { ctx, cancel := context.WithTimeout(context.Background(), 120*time.Second) defer func() { cancel() s.collectScreenshot(ctx.Err(), s.Page) }() secret := s.doRegisterAndLogin2FA(s.T(), s.Context(ctx), "john", "password", false, "") s.verifyIsSecondFactorPage(s.T(), s.Context(ctx)) err := haDockerEnvironment.Restart("authelia-backend") s.Require().NoError(err) err = waitUntilAutheliaBackendIsReady(haDockerEnvironment) s.Require().NoError(err) s.doVisit(s.T(), s.Context(ctx), HomeBaseURL) s.verifyIsHome(s.T(), s.Context(ctx)) // Verify the user is still authenticated. s.doVisit(s.T(), s.Context(ctx), GetLoginBaseURL(BaseDomain)) s.verifyIsSecondFactorPage(s.T(), s.Context(ctx)) // Then logout and login again to check the secret is still there. s.doLogout(s.T(), s.Context(ctx)) s.verifyIsFirstFactorPage(s.T(), s.Context(ctx)) s.doLoginTwoFactor(s.T(), s.Context(ctx), "john", "password", false, secret, fmt.Sprintf("%s/secret.html", SecureBaseURL)) s.verifySecretAuthorized(s.T(), s.Context(ctx)) } var UserJohn = "john" var UserBob = "bob" var UserHarry = "harry" var Users = []string{UserJohn, UserBob, UserHarry} var expectedAuthorizations = map[string](map[string]bool){ fmt.Sprintf("%s/secret.html", PublicBaseURL): { UserJohn: true, UserBob: true, UserHarry: true, }, fmt.Sprintf("%s/secret.html", SecureBaseURL): { UserJohn: true, UserBob: true, UserHarry: true, }, fmt.Sprintf("%s/secret.html", AdminBaseURL): { UserJohn: true, UserBob: false, UserHarry: false, }, fmt.Sprintf("%s/secret.html", SingleFactorBaseURL): { UserJohn: true, UserBob: true, UserHarry: true, }, fmt.Sprintf("%s/secret.html", MX1MailBaseURL): { UserJohn: true, UserBob: true, UserHarry: false, }, fmt.Sprintf("%s/secret.html", MX2MailBaseURL): { UserJohn: false, UserBob: true, UserHarry: false, }, fmt.Sprintf("%s/groups/admin/secret.html", DevBaseURL): { UserJohn: true, UserBob: false, UserHarry: false, }, fmt.Sprintf("%s/groups/dev/secret.html", DevBaseURL): { UserJohn: true, UserBob: true, UserHarry: false, }, fmt.Sprintf("%s/users/john/secret.html", DevBaseURL): { UserJohn: true, UserBob: false, UserHarry: false, }, fmt.Sprintf("%s/users/harry/secret.html", DevBaseURL): { UserJohn: true, UserBob: false, UserHarry: true, }, fmt.Sprintf("%s/users/bob/secret.html", DevBaseURL): { UserJohn: true, UserBob: true, UserHarry: false, }, } func (s *HighAvailabilityWebDriverSuite) TestShouldVerifyAccessControl() { verifyUserIsAuthorized := func(ctx context.Context, t *testing.T, targetURL string, authorized bool) { s.doVisit(t, s.Context(ctx), targetURL) s.verifyURLIs(t, s.Context(ctx), targetURL) if authorized { s.verifySecretAuthorized(t, s.Context(ctx)) } else { s.verifyBodyContains(t, s.Context(ctx), "403 Forbidden") } } verifyAuthorization := func(username string) func(t *testing.T) { return func(t *testing.T) { ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) defer func() { s.collectScreenshot(ctx.Err(), s.Page) cancel() }() s.doRegisterAndLogin2FA(t, s.Context(ctx), username, "password", false, "") for url, authorizations := range expectedAuthorizations { t.Run(url, func(t *testing.T) { verifyUserIsAuthorized(ctx, t, url, authorizations[username]) }) } s.doLogout(t, s.Context(ctx)) } } for _, user := range Users { s.T().Run(user, verifyAuthorization(user)) } } type HighAvailabilitySuite struct { *BaseSuite } func NewHighAvailabilitySuite() *HighAvailabilitySuite { return &HighAvailabilitySuite{ BaseSuite: &BaseSuite{ Name: highAvailabilitySuiteName, }, } } func DoGetWithAuth(t *testing.T, username, password string) int { client := NewHTTPClient() req, err := http.NewRequest(fasthttp.MethodGet, fmt.Sprintf("%s/secret.html", SingleFactorBaseURL), nil) assert.NoError(t, err) req.SetBasicAuth(username, password) res, err := client.Do(req) assert.NoError(t, err) return res.StatusCode } func (s *HighAvailabilitySuite) TestBasicAuth() { s.Assert().Equal(fasthttp.StatusOK, DoGetWithAuth(s.T(), "john", "password")) s.Assert().Equal(fasthttp.StatusFound, DoGetWithAuth(s.T(), "john", "bad-password")) s.Assert().Equal(fasthttp.StatusFound, DoGetWithAuth(s.T(), "dontexist", "password")) } func (s *HighAvailabilitySuite) Test1FAScenario() { suite.Run(s.T(), New1FAScenario()) } func (s *HighAvailabilitySuite) Test2FAScenario() { suite.Run(s.T(), New2FAScenario()) } func (s *HighAvailabilitySuite) TestRegulationScenario() { suite.Run(s.T(), NewRegulationScenario()) } func (s *HighAvailabilitySuite) TestCustomHeadersScenario() { suite.Run(s.T(), NewCustomHeadersScenario()) } func (s *HighAvailabilitySuite) TestRedirectionCheckScenario() { suite.Run(s.T(), NewRedirectionCheckScenario()) } func (s *HighAvailabilitySuite) TestHighAvailabilityWebDriverSuite() { suite.Run(s.T(), NewHighAvailabilityWebDriverSuite()) } func TestHighAvailabilityWebDriverSuite(t *testing.T) { if testing.Short() { t.Skip("skipping suite test in short mode") } suite.Run(t, NewHighAvailabilityWebDriverSuite()) } func TestHighAvailabilitySuite(t *testing.T) { if testing.Short() { t.Skip("skipping suite test in short mode") } suite.Run(t, NewHighAvailabilitySuite()) }
package template type TestClass struct { PackageName string ImportNames []string Functions []*Function } type Function struct { FunctionName string FunctionReturns map[interface{}]string // key:type, value:name FunctionParams map[interface{}]string // key:type, value:name }
package main import ( "fmt" "math/rand" ) func main() { fmt.Println("Spaceline Company Days Round-trip Price") fmt.Println("=======================================") var distance = 57600000 var count = 0 for count < 10 { var speed = rand.Intn(15) + 16 // 16-30 km/s var duration = distance / speed / 86400 // days var price = 20.0 + speed // $ millions switch rand.Intn(3) { case 0: fmt.Print("Space Adventures ") case 1: fmt.Print("SpaceX ") case 2: fmt.Print("Virgin Galactic ") } fmt.Printf("%4v ", duration) if rand.Intn(2) == 1 { fmt.Print("Round-trip ") price = price * 2 } else { fmt.Print("One-way ") } fmt.Printf("$%4v", price) fmt.Println() count = count + 1 } }
package lmqtt import ( "github.com/lab5e/lmqtt/pkg/config" "github.com/lab5e/lmqtt/pkg/persistence/queue" "github.com/lab5e/lmqtt/pkg/persistence/session" "github.com/lab5e/lmqtt/pkg/persistence/subscription" "github.com/lab5e/lmqtt/pkg/persistence/unack" ) // NewPersistence creates a new persistence layer type NewPersistence func(config config.Config) (Persistence, error) // Persistence is the storage layer type Persistence interface { Open() error NewQueueStore(config config.Config, defaultNotifier queue.Notifier, clientID string) (queue.Store, error) NewSubscriptionStore(config config.Config) (subscription.Store, error) NewSessionStore(config config.Config) (session.Store, error) NewUnackStore(config config.Config, clientID string) (unack.Store, error) Close() error }
package Employee import ( "errors" "github.com/jinzhu/gorm" "html" "log" "strings" "time" "unicode" ) type Employee struct { Id uint32 `gorm:"primary_key;auto_increment" json:"id"` Name string `json:"name"` Address string `json:"address"` PhoneNumber string `json:"phone_number"` NPWP string `json:"npwp"` CreatedAt time.Time `gorm:"default:CURRENT_TIMESTAMP" json:"created_at"` UpdatedAt time.Time `gorm:"default:CURRENT_TIMESTAMP" json:"updated_at"` } func (e *Employee) Prepare() { e.Id = 0 e.Name = html.EscapeString(strings.TrimSpace(e.Name)) e.Address = html.EscapeString(strings.TrimSpace(e.Address)) e.PhoneNumber = html.EscapeString(strings.TrimSpace(e.Address)) e.NPWP = html.EscapeString(strings.TrimSpace(e.NPWP)) e.CreatedAt = time.Now() e.UpdatedAt = time.Now() } func IsInt(s string) bool { for _, c := range s { if !unicode.IsDigit(c) { return false } } return true } func (e *Employee) Validate() error { if e.Name == "" { return errors.New("Required Title") } if e.Address == "" { return errors.New("Required Address") } if len(e.PhoneNumber) < 11 && len(e.PhoneNumber) > 13 { return errors.New("You entered Wrong Phone Number") } //if IsInt(e.PhoneNumber) == false { // return errors.New("Your input is an alphabetic. Try again") //} //if IsInt(e.NPWP) == false { // return errors.New("Your input is an alphabetic. Try again") //} return nil } func (e *Employee) SaveEmployee(db *gorm.DB) (*Employee, error) { var err error err = db.Debug().Model(&Employee{}).Create(&e).Error if err != nil { log.Fatal("error Save Employee", err.Error()) return &Employee{}, err } return e, nil } func (e *Employee) FindAllEmployee(db *gorm.DB) (*[]Employee, error){ var err error employees:= []Employee{} err = db.Debug().Model(&Employee{}).Limit(100).Find(&employees).Error if err != nil { log.Fatal("Erorr find employee", err.Error()) return &[]Employee{} ,err } return &employees, nil } func (e *Employee) FindEmployeeById(db *gorm.DB, eid uint32)(*Employee, error){ var err error err = db.Debug().Model(&Employee{}).Where("id = ?", eid).Take(&e).Error if err != nil { log.Fatal("Error find Employee by ID", err.Error()) return &Employee{}, err } return e, nil } func (e *Employee) UpdateAnEmployee(db *gorm.DB, eid uint32) (*Employee, error) { var err error err = db.Debug().Model(&Employee{}).Where("id = ?", eid).Updates(Employee{ Name: e.Name, Address: e.Address, PhoneNumber: e.PhoneNumber, NPWP: e.NPWP, UpdatedAt: time.Now(), }).Error if err != nil { log.Fatal("error update employee : ", err.Error()) return &Employee{}, err } return e, nil } func (e *Employee) DeleteAnEmployee(db *gorm.DB, eid uint32) (int64, error){ db = db.Debug().Model(&Employee{}).Where("id = ?", eid).Take(&Employee{}).Delete(&Employee{}) if db.Error != nil { if gorm.IsRecordNotFoundError(db.Error){ log.Fatal("erorr delete employee", db.Error) return 0, errors.New("Employee Not Found") } return 0,db.Error } return db.RowsAffected, nil }
// Copyright 2018 the Service Broker Project Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package client import ( "encoding/json" "errors" "fmt" "log" "net/http" "os" "sync" "time" "github.com/cloudfoundry-incubator/cloud-service-broker/pkg/broker" "github.com/pborman/uuid" "github.com/pivotal-cf/brokerapi/v8" "github.com/pivotal-cf/brokerapi/v8/domain" ) // RunExamplesForService runs all the examples for a given service name against // the service broker pointed to by client. All examples in the registry get run // if serviceName is blank. If exampleName is non-blank then only the example // with the given name is run. func RunExamplesForService(allExamples []CompleteServiceExample, client *Client, serviceName, exampleName string, jobCount int) { runExamples(jobCount, client, FilterMatchingServiceExamples(allExamples, serviceName, exampleName)) } // RunExamplesFromFile reads a json-encoded list of CompleteServiceExamples. // All examples in the list get run if serviceName is blank. If exampleName // is non-blank then only the example with the given name is run. func RunExamplesFromFile(client *Client, fileName, serviceName, exampleName string) { data, err := os.ReadFile(fileName) if err != nil { log.Fatalf("Error opening file: %v", err) } var allExamples []CompleteServiceExample json.Unmarshal(data, &allExamples) runExamples(1, client, FilterMatchingServiceExamples(allExamples, serviceName, exampleName)) } func runExamples(workers int, client *Client, examples []CompleteServiceExample) { type result struct { id, name, service string duration time.Duration err error } var results []result var resultsLock sync.Mutex addResult := func(r result) { resultsLock.Lock() defer resultsLock.Unlock() results = append(results, r) } type work struct { id string example CompleteServiceExample } queue := make(chan work) var wg sync.WaitGroup wg.Add(workers) for i := 0; i < workers; i++ { go func() { for w := range queue { start := time.Now() err := runExample(client, w.id, w.example) addResult(result{ id: w.id, name: w.example.Name, service: w.example.ServiceName, duration: time.Since(start), err: err, }) } wg.Done() }() } for i, e := range examples { queue <- work{ id: fmt.Sprintf("%03d", i), example: e, } } close(queue) wg.Wait() failed := 0 log.Println() log.Println("RESULTS:") log.Println() log.Println("id | name | service | duration | result") log.Println("-- | ---- | ------- | -------- | ------") for _, r := range results { switch r.err { case nil: log.Printf("%s | %s | %s | %s | PASS\n", r.id, r.name, r.service, r.duration) default: failed++ log.Printf("%s | %s | %s | %s | FAILED %s\n", r.id, r.name, r.service, r.duration, r.err) } } log.Println() switch failed { case 0: log.Println("Success") default: log.Fatalf("FAILED %d examples", failed) } } type CompleteServiceExample struct { broker.ServiceExample `json:",inline"` ServiceName string `json:"service_name"` ServiceId string `json:"service_id"` ExpectedOutput map[string]interface{} `json:"expected_output"` } func GetExamplesForAService(service *broker.ServiceDefinition) ([]CompleteServiceExample, error) { var examples []CompleteServiceExample for _, example := range service.Examples { serviceCatalogEntry := service.CatalogEntry() var completeServiceExample = CompleteServiceExample{ ServiceExample: example, ServiceId: serviceCatalogEntry.ID, ServiceName: service.Name, ExpectedOutput: broker.CreateJsonSchema(service.BindOutputVariables), } examples = append(examples, completeServiceExample) } return examples, nil } // FilterMatchingServiceExamples should not be run example if: // 1. The service name is specified and does not match the current example's ServiceName // 2. The service name is specified and matches the current example's ServiceName, and the example name is specified and does not match the current example's ExampleName func FilterMatchingServiceExamples(allExamples []CompleteServiceExample, serviceName, exampleName string) []CompleteServiceExample { var matchingExamples []CompleteServiceExample for _, completeServiceExample := range allExamples { if (serviceName != "" && serviceName != completeServiceExample.ServiceName) || (exampleName != "" && exampleName != completeServiceExample.ServiceExample.Name) { continue } matchingExamples = append(matchingExamples, completeServiceExample) } return matchingExamples } // RunExample runs a single example against the given service on the broker // pointed to by client. func runExample(client *Client, id string, serviceExample CompleteServiceExample) error { logger := newExampleLogger(id) executor, err := newExampleExecutor(logger, id, client, serviceExample) if err != nil { return err } executor.LogTestInfo(logger) // Cleanup the test if it fails partway through defer func() { logger.Println("Cleaning up the environment") executor.Unbind() executor.Deprovision() }() if err := executor.Provision(); err != nil { logger.Printf("Failed to provision %v: %v", serviceExample.ServiceName, err) return err } bindResponse, bindErr := executor.Bind() if bindErr != nil { if serviceExample.BindCanFail { log.Printf("WARNING: bind failed: %v, but marked 'can fail' so treated as warning.", bindErr) } else { log.Printf("Failed to bind %v: %v", serviceExample.ServiceName, bindErr) return bindErr } } else if err := executor.Unbind(); err != nil { log.Printf("Failed to unbind %v: %v", serviceExample.ServiceName, err) return err } if err := executor.Deprovision(); err != nil { log.Printf("Failed to deprovision %v: %v", serviceExample.ServiceName, err) return err } if bindErr == nil { // Check that the binding response has the same fields as expected var binding domain.Binding err = json.Unmarshal(bindResponse, &binding) if err != nil { return err } credentialsEntry := binding.Credentials.(map[string]interface{}) if err := broker.ValidateVariablesAgainstSchema(credentialsEntry, serviceExample.ExpectedOutput); err != nil { log.Printf("Error: results don't match JSON Schema: %v", err) log.Printf("Schema: %v\n, Actual: %v", serviceExample.ExpectedOutput, credentialsEntry) return err } } return nil } func retry(timeout, period time.Duration, function func() (tryAgain bool, err error)) error { to := time.After(timeout) tick := time.NewTicker(period).C if tryAgain, err := function(); !tryAgain { return err } // Keep trying until we're timed out or got a result or got an error for { select { case <-to: return errors.New("timeout while waiting for result") case <-tick: tryAgain, err := function() if !tryAgain { return err } } } } func newExampleExecutor(logger *exampleLogger, id string, client *Client, serviceExample CompleteServiceExample) (*exampleExecutor, error) { provisionParams, err := json.Marshal(serviceExample.ServiceExample.ProvisionParams) if err != nil { return nil, err } bindParams, err := json.Marshal(serviceExample.ServiceExample.BindParams) if err != nil { return nil, err } return &exampleExecutor{ Name: fmt.Sprintf("%s/%s", serviceExample.ServiceName, serviceExample.ServiceExample.Name), ServiceId: serviceExample.ServiceId, PlanId: serviceExample.ServiceExample.PlanId, InstanceId: uuid.New(), BindingId: uuid.New(), ProvisionParams: provisionParams, BindParams: bindParams, logger: logger, client: client, }, nil } type exampleExecutor struct { Name string ServiceId string PlanId string InstanceId string BindingId string ProvisionParams json.RawMessage BindParams json.RawMessage logger *exampleLogger client *Client } // Provision attempts to create a service instance from the example. // Multiple calls to provision will attempt to create a resource with the same // ServiceId and details. // If the response is an async result, Provision will attempt to wait until // the Provision is complete. func (ee *exampleExecutor) Provision() error { requestID := uuid.New() ee.logger.Printf("Provisioning %s (id: %s)\n", ee.Name, requestID) resp := ee.client.Provision(ee.InstanceId, ee.ServiceId, ee.PlanId, requestID, ee.ProvisionParams) ee.logger.Println(resp.String()) if resp.InError() { return resp.Error } switch resp.StatusCode { case http.StatusCreated: return nil case http.StatusAccepted: return ee.pollUntilFinished() default: return fmt.Errorf("unexpected response code %d", resp.StatusCode) } } func (ee *exampleExecutor) pollUntilFinished() error { return retry(45*time.Minute, 30*time.Second, func() (bool, error) { requestID := uuid.New() ee.logger.Printf("Polling for async job (id: %s)\n", requestID) resp := ee.client.LastOperation(ee.InstanceId, requestID) if resp.InError() { return false, resp.Error } if resp.StatusCode != http.StatusOK { ee.logger.Printf("Bad status code %d, needed 200", resp.StatusCode) return false, fmt.Errorf("broker responded with statuscode %v", resp.StatusCode) } var responseBody map[string]string err := json.Unmarshal(resp.ResponseBody, &responseBody) if err != nil { return false, err } state := responseBody["state"] eq := state == string(brokerapi.Succeeded) if state == string(brokerapi.Failed) { ee.logger.Printf("Last operation for %q was %q: %s\n", ee.InstanceId, state, responseBody["description"]) return false, fmt.Errorf(responseBody["description"]) } ee.logger.Printf("Last operation for %q was %q\n", ee.InstanceId, state) return !eq, nil }) } // Deprovision destroys the instance created by a call to Provision. func (ee *exampleExecutor) Deprovision() error { requestID := uuid.New() ee.logger.Printf("Deprovisioning %s (id: %s)\n", ee.Name, requestID) resp := ee.client.Deprovision(ee.InstanceId, ee.ServiceId, ee.PlanId, requestID) ee.logger.Println(resp.String()) if resp.InError() { return resp.Error } switch resp.StatusCode { case http.StatusOK: return nil case http.StatusAccepted: return ee.pollUntilFinished() default: return fmt.Errorf("unexpected response code %d", resp.StatusCode) } } // Unbind unbinds the exact binding created by a call to Bind. func (ee *exampleExecutor) Unbind() error { return retry(15*time.Minute, 15*time.Second, func() (bool, error) { requestID := uuid.New() ee.logger.Printf("Unbinding %s (id: %s)\n", ee.Name, requestID) resp := ee.client.Unbind(ee.InstanceId, ee.BindingId, ee.ServiceId, ee.PlanId, requestID) ee.logger.Println(resp.String()) if resp.InError() { return false, resp.Error } if resp.StatusCode == http.StatusOK { return false, nil } return false, fmt.Errorf("unexpected response code %d", resp.StatusCode) }) } // Bind executes the bind portion of the create, this can only be called // once successfully as subsequent binds will attempt to create bindings with // the same ID. func (ee *exampleExecutor) Bind() (json.RawMessage, error) { requestID := uuid.New() ee.logger.Printf("Binding %s (id: %s)\n", ee.Name, requestID) resp := ee.client.Bind(ee.InstanceId, ee.BindingId, ee.ServiceId, ee.PlanId, requestID, ee.BindParams) ee.logger.Println(resp.String()) if resp.InError() { return nil, resp.Error } if resp.StatusCode == http.StatusCreated { return resp.ResponseBody, nil } return nil, fmt.Errorf("unexpected response code %d", resp.StatusCode) } // LogTestInfo writes information about the running example and a manual backout // strategy if the test dies part of the way through. func (ee *exampleExecutor) LogTestInfo(logger *exampleLogger) { logger.Printf("Running Example: %s\n", ee.Name) ips := fmt.Sprintf("--instanceid %q --planid %q --serviceid %q", ee.InstanceId, ee.PlanId, ee.ServiceId) logger.Printf("cloud-service-broker client provision %s --params %q\n", ips, ee.ProvisionParams) logger.Printf("cloud-service-broker client bind %s --bindingid %q --params %q\n", ips, ee.BindingId, ee.BindParams) logger.Printf("cloud-service-broker client unbind %s --bindingid %q\n", ips, ee.BindingId) logger.Printf("cloud-service-broker client deprovision %s\n", ips) }
// 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 extension // Extensions contains all extensions that have already setup type Extensions struct { manifests []*Manifest } // Manifests returns a extension manifests func (es *Extensions) Manifests() []*Manifest { if es == nil { return nil } manifests := make([]*Manifest, len(es.manifests)) copy(manifests, es.manifests) return manifests } // Bootstrap bootstraps all extensions func (es *Extensions) Bootstrap(ctx BootstrapContext) error { if es == nil { return nil } for _, m := range es.manifests { if m.bootstrap != nil { if err := m.bootstrap(ctx); err != nil { return err } } } return nil } // GetAccessCheckFuncs returns spec functions of the custom access check func (es *Extensions) GetAccessCheckFuncs() (funcs []AccessCheckFunc) { if es == nil { return nil } for _, m := range es.manifests { if m.accessCheckFunc != nil { funcs = append(funcs, m.accessCheckFunc) } } return funcs } // NewSessionExtensions creates a new ConnExtensions object func (es *Extensions) NewSessionExtensions() *SessionExtensions { if es == nil { return nil } return newSessionExtensions(es) }
// package db contains database related helper functions. The supported // databases (rdbms) are currently Firebird and MySQL. package db import "fmt" // DataPointers can be used for sql queries where you don't know the number of // columns to select. // // Usage: // // sqlStr := "SELECT C1, C2, Cn FROM table" // rows, _ := dbh.Query(sqlStr, code) // defer rows.Close() // // cols, _ := rows.Columns() // data, ptr := db.DataPointers(len(cols)) // // for rows.Next() { // if err := rows.Scan(ptr...); err != nil { // return err // } // // for _, value := range data { // fmt.Println(value) // } // } func DataPointers(length int) ([]interface{}, []interface{}) { data := make([]interface{}, length) pointers := make([]interface{}, length) //the 'scan destinations' have to be pointers. for i, _ := range pointers { pointers[i] = &data[i] } return data, pointers } //-------------------------------------------------------------------------- // Limit handles the sql limit functions for different rdbms. func Limit(rdbms string, from, to int) (string, int, int) { switch rdbms { case "firebird": //Firebird's ROWS function is not 0-based! return " ROWS ? TO ? ", from + 1, from + to case "mysql": return " LIMIT ?, ?", from, to default: return "unknown rdbms", 0, 0 } } //-------------------------------------------------------------------------- // ListConcat handles the sql list/concatenation functions for different rdbms. //Parameter '?' gehen nicht (!) bei Tabellennamen: "Parameter markers can be //used only where data values should appear, not for SQL keywords, identifiers! func ListConcat(rdbms string, table string) string { switch rdbms { case "firebird": return fmt.Sprintf(" LIST(TRIM(%s), ', ') ", table) case "mysql": return fmt.Sprintf(" GROUP_CONCAT(%s) ", table) default: return "unknown rdbms" } } //--------------------------------------------------------------------------
package context import ( "os" "strconv" ) type ( // Конфигурация Configuration struct { PsqlConfiguration *PsqlConfiguration ServerConfiguration *ServerConfiguration } // Конфигурация БД PsqlConfiguration struct { Host string Port string User string Password string DbName string SslMode string IsCreate bool } // Конфигурация сервера ServerConfiguration struct { Port string TokenKey string } ) func Build() *Configuration { config := &Configuration{ PsqlConfiguration: buildPsqlConfiguration(), ServerConfiguration: buildServerConfiguration(), } return config } func buildPsqlConfiguration() *PsqlConfiguration { isCreate, _ := strconv.ParseBool(lookupEnvOrDefault("DB_INITIALIZATION", "false")) return &PsqlConfiguration{ Host: lookupEnvOrDefault("DB_HOST", "127.0.0.1"), Port: lookupEnvOrDefault("DB_PORT", "5432"), DbName: lookupEnvOrDefault("DB_DATABASE", ""), User: lookupEnvOrDefault("DB_USER", "postgres"), Password: lookupEnvOrDefault("DB_PASSWORD", "postgres"), SslMode: lookupEnvOrDefault("DB_SSL", "disable"), IsCreate: isCreate, } } func buildServerConfiguration() *ServerConfiguration { return &ServerConfiguration{ Port: lookupEnvOrDefault("SERVER_PORT", ":8080"), TokenKey: lookupEnvOrDefault("TOKEN_KEY", ""), } } func lookupEnvOrDefault(key string, other string) string { value, present := os.LookupEnv(key) if !present { value = other } return value }
package main import ( "fmt" . "github.com/smartystreets/goconvey/convey" "gopkg.in/redis.v3" "os" "testing" "time" ) // TestRedis tests all of features of the redis interface. func TestRedis(t *testing.T) { Convey("The Redis interface tests, ", t, func() { Convey("Without a REDIS_URL", func() { curVal := os.Getenv("REDIS_URL") os.Setenv("REDIS_URL", "//not.a.user@%66%6f%6f.com/just/a/path/also") So(func() { redisClient() }, ShouldPanic) os.Setenv("REDIS_URL", curVal) }) Convey("With a valid REDIS_URL", func() { token := "testing" client := redisClient() Convey("The expected token Redis key is correct", func() { So(PerishableRedisKey(token), ShouldEqual, "goswift:perishabletoken:testing") }) Convey("Getting a non integer Redis key fails", func() { if err := client.Set(PerishableRedisKey(token), "val", 0).Err(); err != redis.Nil && err != nil { panic(fmt.Errorf("setting token %s failed %s", token, err)) } So(func() { getTokenHits(PerishableRedisKey(token), client) }, ShouldPanic) }) Convey("Incrementing a non integer Redis key fails", func() { if err := client.Set(PerishableRedisKey(token), "val", 0).Err(); err != redis.Nil && err != nil { panic(fmt.Errorf("setting token %s failed %s", token, err)) } So(func() { incrToken(PerishableRedisKey(token), client) }, ShouldPanic) So(func() { getTokenHits(PerishableRedisKey(token), client) }, ShouldPanic) }) Convey("Getting the value for a non existing key fails", func() { ok, _ := getTokenHits(PerishableRedisKey(token+"NotExist"), client) So(ok, ShouldEqual, false) }) Convey("Updating or getting an integer Redis key works", func() { if err := client.Set(PerishableRedisKey(token), 2, 0).Err(); err != redis.Nil && err != nil { panic(fmt.Errorf("setting token %s failed %s", token, err)) } So(func() { incrToken(PerishableRedisKey(token), client) }, ShouldNotPanic) ok, val := getTokenHits(PerishableRedisKey(token), client) So(ok, ShouldEqual, true) So(val, ShouldEqual, 3) // We have incremented the value already. }) Convey("Getting the TTL of a Redis key with a TTL works", func() { if err := client.Set(PerishableRedisKey(token), 2, time.Minute*1).Err(); err != redis.Nil && err != nil { panic(fmt.Errorf("setting token %s failed %s", token, err)) } ok, _ := getTokenTTL(PerishableRedisKey(token), client) So(ok, ShouldEqual, true) }) Convey("Getting the TTL of a Redis key without a TTL fails", func() { if err := client.Set(PerishableRedisKey(token), 2, -1).Err(); err != redis.Nil && err != nil { panic(fmt.Errorf("setting token %s failed %s", token, err)) } ok, _ := getTokenTTL(PerishableRedisKey(token), client) So(ok, ShouldEqual, false) }) }) }) }
package sort import "fmt" // MaxK return the kth max number in a numbers array func MaxK(nums []int, k int) int{ return _maxK(nums, 0, len(nums)-1, k-1) } func _maxK(nums []int, p int, r int, k int) int { if k > r || k < p{ return -1 } //分区 q := p for i := p; i <= r; i++ { if nums[i] > nums[r] { nums[i], nums[q] = nums[q], nums[i] q++ } } nums[q], nums[r] = nums[r], nums[q] //分治 if q == k { return nums[k] } else if q > k { return _maxK(nums, p, q-1, k) }else{ return _maxK(nums, q+1, r, k) } }
package main import ( "encoding/hex" "encoding/json" "log" "reflect" "strconv" "github.com/ugorji/go/codec" ) type Item struct { Ref Ref `json:"ref"` Size uint32 `json:"size"` Compression uint8 `json:"compr,omitempty"` OSize uint32 `json:"osize,omitempty"` } type Ref struct { Type uint8 HashBytes []byte } func main() { var ( bh codec.BincHandle mh codec.MsgpackHandle ) mh.MapType = reflect.TypeOf(map[string]interface{}(nil)) v := Item{ Ref: Ref{Type: 0, HashBytes: []byte("12345678901234567890")}, Size: 3555, Compression: 1, OSize: 7643, } b := make([]byte, 0, 64) enc := codec.NewEncoderBytes(&b, &mh) err := enc.Encode(v) if err != nil { log.Printf("error encoding %v to MessagePack: %v", v, err) } log.Printf("length of %#v as MessagePack: %d\n%v", v, len(b), b) b = b[:0] enc = codec.NewEncoderBytes(&b, &bh) if err = enc.Encode(v); err != nil { log.Printf("error encoding %v to Binc: %v", v, err) } log.Printf("length of %#v as Binc: %d\n%v", v, len(b), b) if b, err = json.Marshal(v); err != nil { log.Printf("error encoding to json: %v", err) } log.Printf("length of %#v as JSON: %d\n%s", v, len(b), b) b = b[:40] hex.Encode(b, v.Ref.HashBytes) b = append(append([]byte("[sha1-"), b...), []byte(strconv.FormatUint(uint64(v.Size), 10)+" 1 "+ strconv.FormatUint(uint64(v.OSize), 10)+"]")...) log.Printf("length of %#v as now: %d\n%s", v, len(b), b) }
package problem0189 func rotateNewPlace(nums []int, k int) { size := len(nums) newNums := make([]int, size) for i := 0; i < size; i++ { newNums[(i+k)%size] = nums[i] } copy(nums, newNums) } func rotate(nums []int, k int) { size := len(nums) k = k % size reverse(nums, 0, size-1) reverse(nums, 0, k-1) reverse(nums, k, size-1) } func reverse(nums []int, left, right int) { for left < right { nums[left], nums[right] = nums[right], nums[left] left++ right-- } }
package ciolite // Api functions that support: webhooks import ( "fmt" ) // GetWebhooks gets listings of Webhooks configured for the application. func (cioLite CioLite) GetWebhooks() ([]GetUsersWebhooksResponse, error) { // Make request request := clientRequest{ Method: "GET", Path: "/lite/webhooks", } // Make response var response []GetUsersWebhooksResponse // Request err := cioLite.doFormRequest(request, &response) return response, err } // GetWebhook gets the properties of a given Webhook. func (cioLite CioLite) GetWebhook(webhookID string) (GetUsersWebhooksResponse, error) { // Make request request := clientRequest{ Method: "GET", Path: fmt.Sprintf("/lite/webhooks/%s", webhookID), } // Make response var response GetUsersWebhooksResponse // Request err := cioLite.doFormRequest(request, &response) return response, err } // CreateWebhook creates a new Webhook for the application. // formValues requires CallbackURL, FailureNotifUrl, and may optionally contain // FilterTo, FilterFrom, FilterCC, FilterSubject, FilterThread, // FilterNewImportant, FilterFileName, FilterFolderAdded, FilterToDomain, // FilterFromDomain, IncludeBody, BodyType func (cioLite CioLite) CreateWebhook(formValues CreateUserWebhookParams) (CreateUserWebhookResponse, error) { // Make request request := clientRequest{ Method: "POST", Path: "/lite/webhooks", FormValues: formValues, } // Make response var response CreateUserWebhookResponse // Request err := cioLite.doFormRequest(request, &response) return response, err } // ModifyWebhook changes the properties of a given Webhook. // formValues requires Active func (cioLite CioLite) ModifyWebhook(webhookID string, formValues ModifyUserWebhookParams) (ModifyWebhookResponse, error) { // Make request request := clientRequest{ Method: "POST", Path: fmt.Sprintf("/lite/webhooks/%s", webhookID), FormValues: formValues, } // Make response var response ModifyWebhookResponse // Request err := cioLite.doFormRequest(request, &response) return response, err } // DeleteWebhookAccount cancels a Webhook. func (cioLite CioLite) DeleteWebhookAccount(webhookID string) (DeleteWebhookResponse, error) { // Make request request := clientRequest{ Method: "DELETE", Path: fmt.Sprintf("/lite/webhooks/%s", webhookID), } // Make response var response DeleteWebhookResponse // Request err := cioLite.doFormRequest(request, &response) return response, err }
package queries import ( "log" "github.com/jmoiron/sqlx" "gitlab.com/semestr-6/projekt-grupowy/backend/obsluga-formularzy/attributes/models" "gitlab.com/semestr-6/projekt-grupowy/backend/obsluga-formularzy/configuration" ) const GET_FACTOR_ATTRIBUTE_BY_ID_SQL = ` SELECT a."AttributeId" ,a."AttributeEnumId" ,a."SourceId" ,s."SourceDate" ,s."SourceDescription" ,ea."AttributeEnumNamePl" ,a."Value" ,a."ValueUnitId1" ,a."ValueUnitId2" ,a."ValueUnitId3" ,u1."UnitShortName" Unit1ShortName ,u2."UnitShortName" Unit2ShortName ,u3."UnitShortName" Unit3ShortName ,a."Uncertainty" FROM attributes."AttributesEnum" ea , attributes."Attributes" a , files."Sources" s , units."Units" u1 , units."Units" u2 , units."Units" u3 WHERE a."SourceId" = s."SourceId" AND a."AttributeEnumId" = ea."AttributeEnumId" AND a."ValueUnitId1" = u1."UnitId" AND a."ValueUnitId2" = u2."UnitId" AND a."ValueUnitId3" = u3."UnitId" AND a."AttributeId"=$1;` func GetFactorAttributeById(id int) (attribute *models.FactorAttributeModel, err error) { db, err := sqlx.Open("postgres", configuration.ConnectionString) defer db.Close() if err != nil { log.Fatal(err) return } var _attribute []models.FactorAttributeModel err = db.Select(&_attribute, GET_FACTOR_ATTRIBUTE_BY_ID_SQL, id) if err != nil { log.Fatal(err) return } if len(_attribute) > 0 { attribute = &_attribute[0] } return }
package flagen import "strconv" type value interface { set(string) error Get() interface{} Type() string } func newBoolValue(v string) (*boolValue, error) { bv := &boolValue{} err := bv.set(v) return bv, err } type boolValue struct { v bool } func (b *boolValue) set(s string) error { v, err := strconv.ParseBool(s) if err != nil { return err } b.v = v return err } func (b *boolValue) Get() interface{} { return b.v } func (b *boolValue) Type() string { return "bool" } func newIntValue(v string) (*intValue, error) { iv := &intValue{} err := iv.set(v) return iv, err } type intValue struct { v int64 } func (i *intValue) set(s string) error { v, err := strconv.ParseInt(s, 0, strconv.IntSize) if err != nil { return err } i.v = v return err } func (i *intValue) Get() interface{} { return i.v } func (i *intValue) Type() string { return "int" } func newFloatValue(v string) (*floatValue, error) { fv := &floatValue{} err := fv.set(v) return fv, err } type floatValue struct { v float64 } func (f *floatValue) set(s string) error { v, err := strconv.ParseFloat(s, 64) if err != nil { return err } f.v = v return err } func (f *floatValue) Get() interface{} { return f.v } func (f *floatValue) Type() string { return "float" } func newStringValue(v string) (*stringValue, error) { sv := &stringValue{} err := sv.set(v) return sv, err } type stringValue struct { v string } func (s *stringValue) set(val string) error { s.v = val return nil } func (s *stringValue) Get() interface{} { return s.v } func (s *stringValue) Type() string { return "string" }
// 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 executor import ( gjson "encoding/json" "testing" "github.com/pingcap/tidb/store/helper" "github.com/pingcap/tidb/types" "github.com/stretchr/testify/require" ) func TestShowPlacementLabelsBuilder(t *testing.T) { cases := []struct { stores [][]*helper.StoreLabel expects [][]interface{} }{ { stores: nil, expects: nil, }, { stores: [][]*helper.StoreLabel{ {{Key: "zone", Value: "z1"}, {Key: "rack", Value: "r3"}, {Key: "host", Value: "h1"}}, {{Key: "zone", Value: "z1"}, {Key: "rack", Value: "r1"}, {Key: "host", Value: "h2"}}, {{Key: "zone", Value: "z1"}, {Key: "rack", Value: "r2"}, {Key: "host", Value: "h2"}}, {{Key: "zone", Value: "z2"}, {Key: "rack", Value: "r1"}, {Key: "host", Value: "h2"}}, nil, {{Key: "k1", Value: "v1"}}, }, expects: [][]interface{}{ {"host", []string{"h1", "h2"}}, {"k1", []string{"v1"}}, {"rack", []string{"r1", "r2", "r3"}}, {"zone", []string{"z1", "z2"}}, }, }, } b := &showPlacementLabelsResultBuilder{} toBinaryJSON := func(obj interface{}) (bj types.BinaryJSON) { d, err := gjson.Marshal(obj) require.NoError(t, err) err = bj.UnmarshalJSON(d) require.NoError(t, err) return } for _, ca := range cases { for _, store := range ca.stores { bj := toBinaryJSON(store) err := b.AppendStoreLabels(bj) require.NoError(t, err) } rows, err := b.BuildRows() require.NoError(t, err) require.Equal(t, len(ca.expects), len(rows)) for idx, expect := range ca.expects { row := rows[idx] bj := toBinaryJSON(expect[1]) require.Equal(t, expect[0].(string), row[0].(string)) require.Equal(t, bj.TypeCode, row[1].(types.BinaryJSON).TypeCode) require.Equal(t, bj.Value, row[1].(types.BinaryJSON).Value) } } }
package main import ( log "github.com/sirupsen/logrus" "sync" "time" ) func Foo(wg *sync.WaitGroup) { defer wg.Done() log.Info("Foo is starting!") for i := 0; ; i++ { log.Debugf("Foo is doing thing %d", i) if i == 5 { log.Warn("Foo is 1/2 done!") } if i > 5 { log.Error("Uh-oh, I have a problem!") log.Debug("The problem is I lost my DB connection!") } time.Sleep(1 * time.Second) if i > 20 { break } } log.Info("Foo is done!") }
package cart import ( "context" "github.com/gingerxman/eel" "github.com/gingerxman/ginger-product/business" ) type CartRepository struct { eel.RepositoryBase } func NewCartRepository(ctx context.Context) *CartRepository { repository := new(CartRepository) repository.Ctx = ctx return repository } //GetShipInfoInCorp 根据id和user获得ShipInfo对象 func (this *CartRepository) GetCartForUserInCorp(user business.IUser, corp business.ICorp) *Cart { cart := Cart{ UserId: user.GetId(), CorpId: corp.GetId(), } cart.Ctx = this.Ctx return &cart } func init() { }
/* Copyright 2011 Google Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package db import ( "fmt" "reflect" "testing" ) type conversionTest struct { s, d interface{} // source and destination // following are used if they're non-zero wantint int64 wantuint uint64 wantstr string wanterr string } // Target variables for scanning into. var ( scanstr string scanint int scanint8 int8 scanint16 int16 scanint32 int32 scanuint8 uint8 scanuint16 uint16 ) var conversionTests = []conversionTest{ // Exact conversions (destination pointer type matches source type) {s: "foo", d: &scanstr, wantstr: "foo"}, {s: 123, d: &scanint, wantint: 123}, // To strings {s: []byte("byteslice"), d: &scanstr, wantstr: "byteslice"}, {s: 123, d: &scanstr, wantstr: "123"}, {s: int8(123), d: &scanstr, wantstr: "123"}, {s: int64(123), d: &scanstr, wantstr: "123"}, {s: uint8(123), d: &scanstr, wantstr: "123"}, {s: uint16(123), d: &scanstr, wantstr: "123"}, {s: uint32(123), d: &scanstr, wantstr: "123"}, {s: uint64(123), d: &scanstr, wantstr: "123"}, {s: 1.5, d: &scanstr, wantstr: "1.5"}, // Strings to integers {s: "255", d: &scanuint8, wantuint: 255}, {s: "256", d: &scanuint8, wanterr: `string "256" overflows uint8`}, {s: "256", d: &scanuint16, wantuint: 256}, {s: "-1", d: &scanint, wantint: -1}, {s: "foo", d: &scanint, wanterr: `converting string "foo" to a int: parsing "foo": invalid argument`}, } func intValue(intptr interface{}) int64 { return reflect.Indirect(reflect.ValueOf(intptr)).Int() } func uintValue(intptr interface{}) uint64 { return reflect.Indirect(reflect.ValueOf(intptr)).Uint() } func TestConversions(t *testing.T) { for n, ct := range conversionTests { err := copyConvert(ct.d, ct.s) errstr := "" if err != nil { errstr = err.String() } errf := func(format string, args ...interface{}) { base := fmt.Sprintf("copyConvert #%d: for %v (%T) -> %T, ", n, ct.s, ct.s, ct.d) t.Errorf(base+format, args...) } if errstr != ct.wanterr { errf("got error %q, want error %q", errstr, ct.wanterr) } if ct.wantstr != "" && ct.wantstr != scanstr { errf("want string %q, got %q", ct.wantstr, scanstr) } if ct.wantint != 0 && ct.wantint != intValue(ct.d) { errf("want int %d, got %d", ct.wantint, intValue(ct.d)) } if ct.wantuint != 0 && ct.wantuint != uintValue(ct.d) { errf("want uint %d, got %d", ct.wantuint, uintValue(ct.d)) } } } func TestNullableString(t *testing.T) { var ns NullableString copyConvert(&ns, []byte("foo")) if !ns.Ok { t.Errorf("expecting ok") } if ns.String != "foo" { t.Errorf("expecting foo; got %q", ns.String) } copyConvert(&ns, nil) if ns.Ok { t.Errorf("expecting not ok on nil") } if ns.String != "" { t.Errorf("expecting blank on nil; got %q", ns.String) } }
package attachments import ( "bufio" "bytes" "errors" "io" "os" "github.com/keybase/client/go/chat/globals" "github.com/keybase/client/go/libkb" "github.com/keybase/client/go/protocol/chat1" "github.com/keybase/client/go/protocol/gregor1" "golang.org/x/net/context" ) func AssetFromMessage(ctx context.Context, g *globals.Context, uid gregor1.UID, convID chat1.ConversationID, msgID chat1.MessageID, preview bool) (res chat1.Asset, err error) { msgs, err := g.ChatHelper.GetMessages(ctx, uid, convID, []chat1.MessageID{msgID}, true) if err != nil { return res, err } if len(msgs) == 0 { return res, libkb.NotFoundError{} } first := msgs[0] st, err := first.State() if err != nil { return res, err } if st == chat1.MessageUnboxedState_ERROR { em := first.Error().ErrMsg return res, errors.New(em) } if st != chat1.MessageUnboxedState_VALID { // given a message id that doesn't exist, msgs can come back // with an empty message in it (and st == 0). // this check prevents a panic, but perhaps the server needs // a fix as well. return res, libkb.NotFoundError{} } msg := first.Valid() body := msg.MessageBody t, err := body.MessageType() if err != nil { return res, err } var attachment chat1.MessageAttachment switch t { case chat1.MessageType_ATTACHMENT: attachment = msg.MessageBody.Attachment() case chat1.MessageType_ATTACHMENTUPLOADED: uploaded := msg.MessageBody.Attachmentuploaded() attachment = chat1.MessageAttachment{ Object: uploaded.Object, Previews: uploaded.Previews, Metadata: uploaded.Metadata, } default: return res, errors.New("not an attachment message") } res = attachment.Object if preview { if len(attachment.Previews) > 0 { res = attachment.Previews[0] } else if attachment.Preview != nil { res = *attachment.Preview } else { return res, errors.New("no preview in attachment") } } return res, nil } type fileReadResetter struct { filename string file *os.File buf *bufio.Reader } func newFileReadResetter(name string) (*fileReadResetter, error) { f := &fileReadResetter{filename: name} if err := f.open(); err != nil { return nil, err } return f, nil } func (f *fileReadResetter) open() error { ff, err := os.Open(f.filename) if err != nil { return err } f.file = ff f.buf = bufio.NewReader(f.file) return nil } func (f *fileReadResetter) Read(p []byte) (int, error) { return f.buf.Read(p) } func (f *fileReadResetter) Reset() error { _, err := f.file.Seek(0, io.SeekStart) if err != nil { return err } f.buf.Reset(f.file) return nil } func (f *fileReadResetter) Close() error { f.buf = nil if f.file != nil { return f.file.Close() } return nil } type bufReadResetter struct { buf []byte r *bytes.Reader } func newBufReadResetter(buf []byte) *bufReadResetter { return &bufReadResetter{ buf: buf, r: bytes.NewReader(buf), } } func (b *bufReadResetter) Read(p []byte) (int, error) { return b.r.Read(p) } func (b *bufReadResetter) Reset() error { b.r.Reset(b.buf) return nil }
package main import ( "fmt" "os" "github.com/vlad-belogrudov/gopl/pkg/reverse" ) func main() { if len(os.Args) < 2 { fmt.Fprintln(os.Stderr, "need string to revert") os.Exit(1) } bytes := []byte(os.Args[1]) if err := reverse.RevertUTF8Bytes(bytes); err != nil { fmt.Fprintln(os.Stderr, err) os.Exit(1) } fmt.Println(string(bytes)) }
/* Copyright (c) 2017 Jason Ish * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ package auth import ( "github.com/jasonish/evebox/server/sessions" "github.com/pkg/errors" "net/http" ) const SESSION_KEY = "x-evebox-session-id" var ErrNoUsername = errors.New("no username provided") var ErrNoPassword = errors.New("no password provided") type AuthenticationRequiredResponse struct { Types []string `json:"types"` } type Authenticator interface { Login(r *http.Request) (*sessions.Session, error) Authenticate(w http.ResponseWriter, r *http.Request) *sessions.Session }
package client import ( "crypto" "github.com/go-acme/lego/v3/certificate" "github.com/alphatr/acme-lego/common/errors" ) // CertificateObtain 证书获取 func (cli *Client) CertificateObtain(domains []string, secret crypto.PrivateKey) (*certificate.Resource, *errors.Error) { request := certificate.ObtainRequest{ Domains: domains, PrivateKey: secret, Bundle: true, MustStaple: true, } cert, errs := cli.lego.Certificate.Obtain(request) if errs != nil { return nil, errors.NewError(errors.ModelClientObtainErrno, errs) } return cert, nil }
package middleware import ( "context" "encoding/json" "errors" "github.com/bitmaelum/bitmaelum-suite/internal" "github.com/bitmaelum/bitmaelum-suite/internal/container" "github.com/bitmaelum/bitmaelum-suite/pkg/address" "github.com/gorilla/mux" "github.com/sirupsen/logrus" "github.com/vtolstov/jwt-go" "net/http" "strings" ) // JwtToken is a middleware that automatically verifies given JWT token type JwtToken struct{} type claimsContext string type addressContext string // ErrTokenNotValidated is returned when the token could not be validated (for any reason) var ErrTokenNotValidated = errors.New("token could not be validated") // Middleware JWT token authentication func (*JwtToken) Middleware(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { haddr, err := address.NewHashFromHash(mux.Vars(req)["addr"]) if err != nil { logrus.Trace("auth: no address specified") ErrorOut(w, http.StatusUnauthorized, "Cannot authorize without address") return } ar := container.GetAccountRepo() if !ar.Exists(*haddr) { logrus.Trace("auth: address not found") ErrorOut(w, http.StatusUnauthorized, "Address not found") return } token, err := checkToken(req.Header.Get("Authorization"), *haddr) if err != nil { logrus.Trace("auth: incorrect token: ", err) ErrorOut(w, http.StatusUnauthorized, "Unauthorized: " + err.Error()) return } ctx := req.Context() ctx = context.WithValue(ctx, claimsContext("claims"), token.Claims) ctx = context.WithValue(ctx, addressContext("address"), token.Claims.(*jwt.StandardClaims).Subject) next.ServeHTTP(w, req.WithContext(ctx)) }) } // Check if the authorization contains a valid JWT token for the given address func checkToken(auth string, addr address.HashAddress) (*jwt.Token, error) { if auth == "" { logrus.Trace("auth: empty auth string") return nil, ErrTokenNotValidated } if len(auth) <= 6 || strings.ToUpper(auth[0:7]) != "BEARER " { logrus.Trace("auth: bearer not found") return nil, ErrTokenNotValidated } tokenString := auth[7:] ar := container.GetAccountRepo() keys, err := ar.FetchKeys(addr) if err != nil { logrus.Trace("auth: cannot fetch keys: ", err) return nil, ErrTokenNotValidated } for _, key := range keys { token, err := internal.ValidateJWTToken(tokenString, addr, key) if err == nil { return token, nil } } logrus.Trace("auth: no key found that validates the token") return nil, ErrTokenNotValidated } // ErrorOut outputs an error func ErrorOut(w http.ResponseWriter, code int, msg string) { type OutputResponse struct { Error bool `json:"error,omitempty"` Status string `json:"status"` } logrus.Debugf("Returning error (%d): %s", code, msg) w.Header().Set("Content-Type", "application/json") w.WriteHeader(code) _ = json.NewEncoder(w).Encode(&OutputResponse{ Error: true, Status: msg, }) return }
package randomutils import ( "math/rand" "time" ) func RandomStringByPattern(pattern []byte, n int) string { result := []byte{} r := rand.New(rand.NewSource(time.Now().UnixNano())) for i := 0; i < n; i++ { result = append(result, pattern[r.Intn(len(pattern))]) } return string(result) } func RandomString(n int) string { pattern := "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLOMNOPQRSTUVWXYZ1234567890" return RandomStringByPattern([]byte(pattern), n) } func RandomNumber(n int) string { pattern := "1234567890" return RandomStringByPattern([]byte(pattern), n) }
package run import floc "gopkg.in/workanator/go-floc.v1" /* Parallel runs jobs in their own goroutines and waits until all of them finish. Summary: - Run jobs in goroutines : YES - Wait all jobs finish : YES - Run order : PARALLEL Diagram: +-->[JOB_1]--+ | | --+--> .. --+--> | | +-->[JOB_N]--+ */ func Parallel(jobs ...floc.Job) floc.Job { return func(flow floc.Flow, state floc.State, update floc.Update) { // Do not start parallel jobs if the execution is finished if flow.IsFinished() { return } // Create channel which is used for back counting of finished jobs done := make(chan struct{}, len(jobs)) defer close(done) // Run jobs in parallel running := 0 for _, job := range jobs { running++ // Run the job in it's own goroutine go func(job floc.Job) { defer func() { done <- struct{}{} }() job(flow, state, update) }(job) } // Wait until all jobs done for running > 0 { select { case <-flow.Done(): // The execution finished but we should wait until all jobs finished // and we assume all jobs are aware of the flow state. If we do // not wait that may lead to unpredicted behavior. case <-done: // One of the jobs finished running-- } } } }
package CpUtil // 求解器常用函数和常量 const BITSIZE = 64 const DIVBIT = 6 const MODMASK = 0x3f const INDEXOVERFLOW = -1 const ALLONELONG = 0xFFFFFFFFFFFFFFFF const ALLONE64 = 0xFFFFFFFFFFFFFFFF const INTMAXINF = 0x3f3f3f3f const INTMININF = -0x3f3f3f3f const LONGMAXINF = 0x3f3f3f3f3f3f3f3f const LONGMININF = -0x3f3f3f3f3f3f3f3f type Int2d struct { X int Y int } // func GetInt2d(a int) Int2d { return Int2d{a >> DIVBIT, a & MODMASK} } func GetInt2(a int) (int, int) { return a >> DIVBIT, a & MODMASK } func GetIndex(x, y int) int { return (x << DIVBIT) + y } // 十亿级前缀标识常量 // 30位值部,2位标识部 const VALUEPARTBITLENGTH = 30 const PERFIXMASK = 0x40000000 // 十亿级 const SUFFIXMASK = 0x3fffffff // 十亿级 // 给数据添加前缀 func markValue(a uint) uint { return a | PERFIXMASK } // 去掉数据据前缀 func demarkValue(a uint) uint { return a & SUFFIXMASK } // 解析数据: (数据类型,数据值) func resolveMark(a uint) (uint, uint) { return a >> VALUEPARTBITLENGTH, a & SUFFIXMASK } // 解析数据: (数据bool类型,数据值) func resolveMarkBoolean(a uint) (bool, uint) { return a >= PERFIXMASK, a & SUFFIXMASK }
package controller import ( "go-gin-start/app/util" "time" "github.com/gin-gonic/gin" ) type Index struct{} /** * Index **/ func (Index) Index(c *gin.Context) { // return c.JSON(200, gin.H{ "create_at": util.FirstIni.Section("").Key("created_at").String(), "server_time": time.Now(), }) }
package handlers import ( "hilfling-oauth/database" "net/http" "github.com/gin-gonic/gin" ) type securityLevel struct { Id int `json:"id" binding:"required"` Level string `json:"level" binding:"required"` } func getSecurityLevels() ([]securityLevel, error) { const q = `SELECT * FROM security_level;` rows := database.Query(q) results := make([]securityLevel, 0) for rows.Next() { // Loop through all DB rows var id int var level string err := rows.Scan(&id, &level) if err != nil { return nil, err } results = append(results, securityLevel{id, level}) } return results, nil } func GetSecurityLevels(ctx *gin.Context) { results, err := getSecurityLevels() if err != nil { ctx.JSON(http.StatusInternalServerError, gin.H{"status": "internal error: " + err.Error()}) return } ctx.JSON(http.StatusOK, results) }
package main import ( "fmt" "net/http" "github.com/wlMalk/gapi" "github.com/wlMalk/gapi/constants" "github.com/wlMalk/gapi/operation" "github.com/wlMalk/gapi/param" "github.com/wlMalk/gapi/request" "github.com/julienschmidt/httprouter" wrapper "github.com/wlMalk/gapi/wrapper/julienschmidt/httprouter" ) func main() { w := wrapper.Wrap(httprouter.New()) g := gapi.New(w).SetBasePath("/api") g.Operations.Set( operation.GET("/users/:id"). UsesFunc(getUser). Schemes(constants.SCHEME_HTTP). Params( param.PathParam("id").As(constants.TYPE_INT64), ), ) g.Start(":8080") } func getUser(w http.ResponseWriter, r *request.Request) { p := r.Input["id"] id := p.Int64() w.Write([]byte(fmt.Sprint(id))) }
package main import "fmt" var strList []string var numList []string var numListEmpty = []int{} // 已被分配内存, 所以不等于nil func main() { fmt.Println(strList, numList, numListEmpty) fmt.Println(len(strList), len(numListEmpty), len(numList)) fmt.Println(strList == nil) fmt.Println(numList == nil) fmt.Println(numListEmpty == nil) var a []string a[1] = "1" a[0] = "1" fmt.Println(a == nil, len(a)) b := make([]string, 1) b = append(b, "9") b = append(b, "8") fmt.Println(len(b), b[0], b[1], b[2]) }
/** Create a slice of a slice of string. Store the following data in the multi-dimensional slice: - "James", "Bond", "Shaken, not stirred" - "Miss", "Moneypenny", "Hellooooooo, James." Range over the records, then range ove the data in each record */ package main import ( "fmt" ) func main() { slice1 := []string{"James", "Bond", "Shaken, not stirred"} slice2 := []string{"Miss", "Moneypenny", "Hellooooooo, James."} multiSlice := [][]string {slice1, slice2} for index, value := range multiSlice { fmt.Println("Record :: ", index) for i, v := range value { fmt.Println("\tValue ", i, " :: ", v) } } }
//Package prototests contains some structures and values that are useful for testing the protocol buffer parser. package prototests
package api import ( "encoding/json" "fmt" "html/template" "github.com/mpolden/ipd/useragent" "github.com/sirupsen/logrus" "math/big" "net" "net/http" "path/filepath" "strconv" "strings" "github.com/gorilla/mux" ) const ( jsonMediaType = "application/json" textMediaType = "text/plain" ) type API struct { Template string IPHeader string oracle Oracle log *logrus.Logger } type Response struct { IP net.IP `json:"ip"` IPDecimal *big.Int `json:"ip_decimal"` Country string `json:"country,omitempty"` City string `json:"city,omitempty"` Hostname string `json:"hostname,omitempty"` } type PortResponse struct { IP net.IP `json:"ip"` Port uint64 `json:"port"` Reachable bool `json:"reachable"` } func New(oracle Oracle, logger *logrus.Logger) *API { return &API{oracle: oracle, log: logger} } func ipToDecimal(ip net.IP) *big.Int { i := big.NewInt(0) if to4 := ip.To4(); to4 != nil { i.SetBytes(to4) } else { i.SetBytes(ip) } return i } func ipFromRequest(header string, r *http.Request) (net.IP, error) { remoteIP := r.Header.Get(header) if remoteIP == "" { host, _, err := net.SplitHostPort(r.RemoteAddr) if err != nil { return nil, err } remoteIP = host } ip := net.ParseIP(remoteIP) if ip == nil { return nil, fmt.Errorf("could not parse IP: %s", remoteIP) } return ip, nil } func (a *API) newResponse(r *http.Request) (Response, error) { ip, err := ipFromRequest(a.IPHeader, r) if err != nil { return Response{}, err } ipDecimal := ipToDecimal(ip) country, err := a.oracle.LookupCountry(ip) if err != nil { a.log.Debug(err) } city, err := a.oracle.LookupCity(ip) if err != nil { a.log.Debug(err) } hostnames, err := a.oracle.LookupAddr(ip) if err != nil { a.log.Debug(err) } return Response{ IP: ip, IPDecimal: ipDecimal, Country: country, City: city, Hostname: strings.Join(hostnames, " "), }, nil } func (a *API) newPortResponse(r *http.Request) (PortResponse, error) { vars := mux.Vars(r) port, err := strconv.ParseUint(vars["port"], 10, 16) if err != nil { return PortResponse{Port: port}, err } if port < 1 || port > 65355 { return PortResponse{Port: port}, fmt.Errorf("invalid port: %d", port) } ip, err := ipFromRequest(a.IPHeader, r) if err != nil { return PortResponse{Port: port}, err } err = a.oracle.LookupPort(ip, port) return PortResponse{ IP: ip, Port: port, Reachable: err == nil, }, nil } func (a *API) CLIHandler(w http.ResponseWriter, r *http.Request) *appError { ip, err := ipFromRequest(a.IPHeader, r) if err != nil { return internalServerError(err) } fmt.Fprintln(w, ip.String()) return nil } func (a *API) CLICountryHandler(w http.ResponseWriter, r *http.Request) *appError { response, err := a.newResponse(r) if err != nil { return internalServerError(err) } fmt.Fprintln(w, response.Country) return nil } func (a *API) CLICityHandler(w http.ResponseWriter, r *http.Request) *appError { response, err := a.newResponse(r) if err != nil { return internalServerError(err) } fmt.Fprintln(w, response.City) return nil } func (a *API) JSONHandler(w http.ResponseWriter, r *http.Request) *appError { response, err := a.newResponse(r) if err != nil { return internalServerError(err).AsJSON() } b, err := json.Marshal(response) if err != nil { return internalServerError(err).AsJSON() } w.Header().Set("Content-Type", jsonMediaType) w.Write(b) return nil } func (a *API) PortHandler(w http.ResponseWriter, r *http.Request) *appError { response, err := a.newPortResponse(r) if err != nil { return badRequest(err).WithMessage(fmt.Sprintf("Invalid port: %d", response.Port)).AsJSON() } b, err := json.Marshal(response) if err != nil { return internalServerError(err).AsJSON() } w.Header().Set("Content-Type", jsonMediaType) w.Write(b) return nil } func (a *API) DefaultHandler(w http.ResponseWriter, r *http.Request) *appError { response, err := a.newResponse(r) if err != nil { return internalServerError(err) } t, err := template.New(filepath.Base(a.Template)).ParseFiles(a.Template) if err != nil { return internalServerError(err) } var data = struct { Host string Response Oracle }{r.Host, response, a.oracle} if err := t.Execute(w, &data); err != nil { return internalServerError(err) } return nil } func (a *API) NotFoundHandler(w http.ResponseWriter, r *http.Request) *appError { err := notFound(nil).WithMessage("404 page not found") if r.Header.Get("accept") == jsonMediaType { err = err.AsJSON() } return err } func cliMatcher(r *http.Request, rm *mux.RouteMatch) bool { ua := useragent.Parse(r.UserAgent()) switch ua.Product { case "curl", "HTTPie", "Wget", "fetch libfetch", "Go", "Go-http-client", "ddclient": return true } return false } type appHandler func(http.ResponseWriter, *http.Request) *appError func (fn appHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { if e := fn(w, r); e != nil { // e is *appError // When Content-Type for error is JSON, we need to marshal the response into JSON if e.IsJSON() { var data = struct { Error string `json:"error"` }{e.Message} b, err := json.Marshal(data) if err != nil { panic(err) } e.Message = string(b) } // Set Content-Type of response if set in error if e.ContentType != "" { w.Header().Set("Content-Type", e.ContentType) } w.WriteHeader(e.Code) fmt.Fprint(w, e.Message) } } func (a *API) Router() http.Handler { r := mux.NewRouter() // JSON r.Handle("/", appHandler(a.JSONHandler)).Methods("GET").Headers("Accept", jsonMediaType) r.Handle("/json", appHandler(a.JSONHandler)).Methods("GET") // CLI r.Handle("/", appHandler(a.CLIHandler)).Methods("GET").MatcherFunc(cliMatcher) r.Handle("/", appHandler(a.CLIHandler)).Methods("GET").Headers("Accept", textMediaType) r.Handle("/ip", appHandler(a.CLIHandler)).Methods("GET") r.Handle("/country", appHandler(a.CLICountryHandler)).Methods("GET") r.Handle("/city", appHandler(a.CLICityHandler)).Methods("GET") // Browser r.Handle("/", appHandler(a.DefaultHandler)).Methods("GET") // Port testing r.Handle("/port/{port:[0-9]+}", appHandler(a.PortHandler)).Methods("GET") // Not found handler which returns JSON when appropriate r.NotFoundHandler = appHandler(a.NotFoundHandler) return r }
package modules import ( "../../domain/repository" serviceModule "../../services" ) type ServiceModule interface { LoadServices(kpr repository.IKubePodRepository) *serviceModule.IKubeService } func LoadServices(kpr repository.IKubePodRepository) serviceModule.IKubeService { var kubeService = serviceModule.InitKubeService(kpr) return kubeService }
package draw type RectangleGraphic struct { rect Rectangle Style RectangStyle childs []IGraphic parent IGraphic text *Text } type RectangStyle struct { Level int DrawBorder bool DoFill bool FillColor Color BorderColor Color BorderWidth int } func (this *RectangleGraphic) Draw(canvas ICanvas) error { return nil } func (this *RectangleGraphic) Add(child IGraphic) error { return nil } func (this *RectangleGraphic) Remove(child IGraphic) error { return nil } func (this *RectangleGraphic) Parent() IGraphic { return this.parent } func (this *RectangleGraphic) Level(child IGraphic) int { return this.Style.Level }
/* * @lc app=leetcode.cn id=1325 lang=golang * * [1325] 删除给定值的叶子节点 */ // @lc code=start /** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */ // package leetcode // type TreeNode struct{ // Val int // Left *TreeNode // Right *TreeNode // } func removeLeafNodes(root *TreeNode, target int) *TreeNode { if root != nil{ root.Left = removeLeafNodes(root.Left, target) root.Right = removeLeafNodes(root.Right, target) if root.Left == nil && root.Right == nil && root.Val == target{ return nil } return root }else { return nil } } // @lc code=end
package api import ( "context" "fmt" "net/http" "time" ) type config struct { Port uint `json:"port"` CreaturesPath string `json:"creatures_path"` } type ShutdownFunc func(context.Context) error func Serve(configPath string) (error, <-chan error, ShutdownFunc) { conf, err := readConfig(configPath) if err != nil { return err, nil, nil } server := http.Server{ Addr: fmt.Sprintf(":%d", conf.Port), ReadTimeout: time.Second * 10, Handler: makeAPIHandler(conf), } fatal := make(chan error, 1) go func() { if err := server.ListenAndServe(); err != nil && err != http.ErrServerClosed { fatal <- err } }() return nil, fatal, func(ctx context.Context) error { return server.Shutdown(ctx) } } func readConfig(path string) (config, error) { var c config if err := readJSONFile(path, &c); err != nil { return config{}, err } return c, nil }
package Services_GIS import ( . "Framework/Framework_Definitions" ) // ------------------------------------------- Definitions ------------------------------------------- // // To create new services, in a new file create a struct and implement the methods found in ServiceInterface in ServiceInterface.go // All service structs must be in the AllServiceInterfaces array at the top of Services.go // Put custom event types here. Assign them to positive integers const ( PING EventType = 1 PONG EventType = 2 PRINT_LINE EventType = 5 REQUEST_USER_INPUT EventType = 10 USER_INPUT EventType = 11 ADD_DATA EventType = 20 REMOVE_DATA EventType = 21 GENERATE_MAP EventType = 22 REQUEST_DATASET_NAMES EventType = 30 DATASET_CHANGE EventType = 31 CHECK_DATA_REQUEST EventType = 40 IS_VALID_DATA_REQUEST EventType = 41 // REQUEST_DATA EventType = 30 ) var AllServiceInterfaces = [...]ServiceInterface{ &(IOService{}), &(GISService{}), &(MenuService{}), }
package middleware import ( "net/http" ) // PrettyJSON is a middleware that will set a response header based on the request URI. This can be used to output // json data either indented or not. type PrettyJSON struct { http.ResponseWriter } // Middleware sets header based on query param func (*PrettyJSON) Middleware(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { q := req.URL.Query() w.Header().Set("x-pretty-json", q.Get("pretty")) next.ServeHTTP(w, req) }) }
package main import ( "errors" "fmt" "math" "os" "path/filepath" "github.com/gitchander/go-lang/cairo" "github.com/gitchander/go-lang/cairo/color" ) const ( textureDefiance1 = "./images/defiance1.png" textureDefiance2 = "./images/defiance2.png" textureChippedBricks = "./images/chipped-bricks.png" textureCircleBlue = "./images/circle-blue.png" ) func DegToRad(deg float64) float64 { return deg * (math.Pi / 180.0) } func RadToDeg(rad float64) float64 { return rad * (180.0 / math.Pi) } type Size struct { Width, Height int } type Example struct { SampleFunc func(c *cairo.Canvas) Dir string FileName string Size Size } func (e *Example) Execute() error { fileName := filepath.Join(e.Dir, e.FileName) surface, err := cairo.NewSurface(cairo.FORMAT_ARGB32, e.Size.Width, e.Size.Height) if err != nil { return err } defer surface.Destroy() canvas, err := cairo.NewCanvas(surface) if err != nil { return err } defer canvas.Destroy() color.CanvasFillRGB(canvas, color.NewRGB(1.0, 1.0, 1.0)) e.SampleFunc(canvas) if err = surface.WriteToPNG(fileName); err != nil { return err } return nil } func makeDir(dir string) error { fi, err := os.Stat(dir) if err != nil { err = os.Mkdir(dir, os.ModePerm) if err != nil { return err } } else { if !fi.IsDir() { return errors.New("file is not dir") } } return nil } func ExampleHelloWorld(c *cairo.Canvas) { c.SelectFontFace("serif", cairo.FONT_SLANT_NORMAL, cairo.FONT_WEIGHT_BOLD) c.SetFontSize(32.0) c.SetSourceRGB(0.0, 0.0, 0.7) c.MoveTo(20.0, 140.0) c.ShowText("Hello World") } func ExampleArc(c *cairo.Canvas) { var ( xc float64 = 128.0 yc float64 = 128.0 radius float64 = 100.0 ) angle1 := DegToRad(45.0) // angles are specified angle2 := DegToRad(180.0) // in radians c.SetLineWidth(10.0) c.Arc(xc, yc, radius, angle1, angle2) c.Stroke() // draw helping lines c.SetSourceRGBA(1, 0.2, 0.2, 0.6) c.SetLineWidth(6.0) c.Arc(xc, yc, 10.0, 0, 2*math.Pi) c.Fill() c.Arc(xc, yc, radius, angle1, angle1) c.LineTo(xc, yc) c.Arc(xc, yc, radius, angle2, angle2) c.LineTo(xc, yc) c.Stroke() } func ExampleArcNegative(c *cairo.Canvas) { var ( xc float64 = 128.0 yc float64 = 128.0 radius float64 = 100.0 ) angle1 := DegToRad(45.0) // angles are specified angle2 := DegToRad(180.0) // in radians c.SetLineWidth(10.0) c.ArcNegative(xc, yc, radius, angle1, angle2) c.Stroke() // draw helping lines c.SetSourceRGBA(1, 0.2, 0.2, 0.6) c.SetLineWidth(6.0) c.Arc(xc, yc, 10.0, 0, 2*math.Pi) c.Fill() c.Arc(xc, yc, radius, angle1, angle1) c.LineTo(xc, yc) c.Arc(xc, yc, radius, angle2, angle2) c.LineTo(xc, yc) c.Stroke() } func ExampleClip(c *cairo.Canvas) { c.Arc(128.0, 128.0, 76.8, 0, 2*math.Pi) c.Clip() c.NewPath() // current path is not consumed by cairo_clip() c.Rectangle(0, 0, 256, 256) c.Fill() c.SetSourceRGB(0, 1, 0) c.MoveTo(0, 0) c.LineTo(256, 256) c.MoveTo(256, 0) c.LineTo(0, 256) c.SetLineWidth(10.0) c.Stroke() } func ExampleClipImage(c *cairo.Canvas) { c.Arc(128.0, 128.0, 76.8, 0, 2*math.Pi) c.Clip() c.NewPath() // path not consumed by clip() image, err := cairo.NewSurfaceFromPNG(textureDefiance1) if err != nil { fmt.Println(err.Error()) return } defer image.Destroy() w := float64(image.GetWidth()) h := float64(image.GetHeight()) c.Scale(256.0/w, 256.0/h) c.SetSourceSurface(image, 0, 0) c.Paint() } func ExampleCurveRectangle(c *cairo.Canvas) { // a custom shape that could be wrapped in a function var ( x0 float64 = 25.6 // parameters like cairo_rectangle y0 float64 = 25.6 rectWidth float64 = 204.8 rectHeight float64 = 204.8 radius float64 = 102.4 // and an approximate curvature radius ) x1 := x0 + rectWidth y1 := y0 + rectHeight if (rectWidth == 0) || (rectHeight == 0) { return } if rectWidth/2 < radius { if rectHeight/2 < radius { c.MoveTo(x0, (y0+y1)/2) c.CurveTo(x0, y0, x0, y0, (x0+x1)/2, y0) c.CurveTo(x1, y0, x1, y0, x1, (y0+y1)/2) c.CurveTo(x1, y1, x1, y1, (x1+x0)/2, y1) c.CurveTo(x0, y1, x0, y1, x0, (y0+y1)/2) } else { c.MoveTo(x0, y0+radius) c.CurveTo(x0, y0, x0, y0, (x0+x1)/2, y0) c.CurveTo(x1, y0, x1, y0, x1, y0+radius) c.LineTo(x1, y1-radius) c.CurveTo(x1, y1, x1, y1, (x1+x0)/2, y1) c.CurveTo(x0, y1, x0, y1, x0, y1-radius) } } else { if rectHeight/2 < radius { c.MoveTo(x0, (y0+y1)/2) c.CurveTo(x0, y0, x0, y0, x0+radius, y0) c.LineTo(x1-radius, y0) c.CurveTo(x1, y0, x1, y0, x1, (y0+y1)/2) c.CurveTo(x1, y1, x1, y1, x1-radius, y1) c.LineTo(x0+radius, y1) c.CurveTo(x0, y1, x0, y1, x0, (y0+y1)/2) } else { c.MoveTo(x0, y0+radius) c.CurveTo(x0, y0, x0, y0, x0+radius, y0) c.LineTo(x1-radius, y0) c.CurveTo(x1, y0, x1, y0, x1, y0+radius) c.LineTo(x1, y1-radius) c.CurveTo(x1, y1, x1, y1, x1-radius, y1) c.LineTo(x0+radius, y1) c.CurveTo(x0, y1, x0, y1, x0, y1-radius) } } c.ClosePath() c.SetSourceRGB(0.5, 0.5, 1) c.FillPreserve() c.SetSourceRGBA(0.5, 0, 0, 0.5) c.SetLineWidth(10.0) c.Stroke() } func ExampleCurveTo(c *cairo.Canvas) { var ( x, y float64 = 25.6, 128.0 x1, y1 float64 = 102.4, 230.4 x2, y2 float64 = 153.6, 25.6 x3, y3 float64 = 230.4, 128.0 ) c.MoveTo(x, y) c.CurveTo(x1, y1, x2, y2, x3, y3) c.SetLineWidth(10.0) c.Stroke() c.SetSourceRGBA(1, 0.2, 0.2, 0.6) c.SetLineWidth(6.0) c.MoveTo(x, y) c.LineTo(x1, y1) c.MoveTo(x2, y2) c.LineTo(x3, y3) c.Stroke() } func ExampleGradient(c *cairo.Canvas) { // draw background { p, _ := cairo.NewPatternLinear(0.0, 0.0, 0.0, 256.0) p.AddColorStopRGBA(1, 0, 0, 0, 1) p.AddColorStopRGBA(0, 1, 1, 1, 1) c.Rectangle(0, 0, 256, 256) c.SetSource(p) c.Fill() p.Destroy() } // draw sphere { p, _ := cairo.NewPatternRadial( 115.2, 102.4, 25.6, 102.4, 102.4, 128.0, ) p.AddColorStopRGBA(0, 1, 1, 1, 1) p.AddColorStopRGBA(1, 0, 0, 0, 1) c.SetSource(p) c.Arc(128.0, 128.0, 76.8, 0, 2*math.Pi) c.Fill() p.Destroy() } } func ExampleSetLineJoin(c *cairo.Canvas) { c.SetLineWidth(40.96) c.MoveTo(76.8, 84.48) c.RelLineTo(51.2, -51.2) c.RelLineTo(51.2, 51.2) c.SetLineJoin(cairo.LINE_JOIN_MITER) // default c.Stroke() c.MoveTo(76.8, 161.28) c.RelLineTo(51.2, -51.2) c.RelLineTo(51.2, 51.2) c.SetLineJoin(cairo.LINE_JOIN_BEVEL) c.Stroke() c.MoveTo(76.8, 238.08) c.RelLineTo(51.2, -51.2) c.RelLineTo(51.2, 51.2) c.SetLineJoin(cairo.LINE_JOIN_ROUND) c.Stroke() } func ExampleDonut(c *cairo.Canvas) { var w, h float64 = 256, 256 c.SetLineWidth(0.5) c.Translate(w/2, h/2) c.Arc(0, 0, 120, 0, 2*math.Pi) c.Stroke() for i := 0; i < 36; i++ { c.Save() c.Rotate(float64(i) * math.Pi / 36) c.Scale(0.3, 1) c.Arc(0, 0, 120, 0, 2*math.Pi) c.Restore() c.Stroke() } } func ExampleDash(c *cairo.Canvas) { var ( dashes = []float64{ 50.0, // ink 10.0, // skip 10.0, // ink 10.0, // skip } offset float64 = -50.0 ) c.SetDash(dashes, offset) c.SetLineWidth(10.0) c.MoveTo(128.0, 25.6) c.LineTo(230.4, 230.4) c.RelLineTo(-102.4, 0.0) c.CurveTo(51.2, 230.4, 51.2, 128.0, 128.0, 128.0) c.Stroke() } func ExampleFillAndStroke2(c *cairo.Canvas) { c.MoveTo(128.0, 25.6) c.LineTo(230.4, 230.4) c.RelLineTo(-102.4, 0.0) c.CurveTo(51.2, 230.4, 51.2, 128.0, 128.0, 128.0) c.ClosePath() c.MoveTo(64.0, 25.6) c.RelLineTo(51.2, 51.2) c.RelLineTo(-51.2, 51.2) c.RelLineTo(-51.2, -51.2) c.ClosePath() c.SetLineWidth(10.0) c.SetSourceRGB(0, 0, 1) c.FillPreserve() c.SetSourceRGB(0, 0, 0) c.Stroke() } func ExampleFillStyle(c *cairo.Canvas) { c.SetLineWidth(6) c.Rectangle(12, 12, 232, 70) c.NewSubPath() c.Arc(64, 64, 40, 0, 2*math.Pi) c.NewSubPath() c.ArcNegative(192, 64, 40, 0, -2*math.Pi) c.SetFillRule(cairo.FILL_RULE_EVEN_ODD) c.SetSourceRGB(0, 0.7, 0) c.FillPreserve() c.SetSourceRGB(0, 0, 0) c.Stroke() c.Translate(0, 128) c.Rectangle(12, 12, 232, 70) c.NewSubPath() c.Arc(64, 64, 40, 0, 2*math.Pi) c.NewSubPath() c.ArcNegative(192, 64, 40, 0, -2*math.Pi) c.SetFillRule(cairo.FILL_RULE_WINDING) c.SetSourceRGB(0, 0, 0.9) c.FillPreserve() c.SetSourceRGB(0, 0, 0) c.Stroke() } func ExampleImage(c *cairo.Canvas) { image, err := cairo.NewSurfaceFromPNG(textureDefiance2) if err != nil { fmt.Println(err.Error()) return } defer image.Destroy() w := float64(image.GetWidth()) h := float64(image.GetHeight()) c.Translate(128.0, 128.0) c.Rotate(45 * math.Pi / 180) c.Scale(256.0/w, 256.0/h) c.Translate(-0.5*w, -0.5*h) c.SetSourceSurface(image, 0, 0) c.Paint() } func ExampleImagePattern(c *cairo.Canvas) { image, err := cairo.NewSurfaceFromPNG(textureCircleBlue) if err != nil { fmt.Println(err.Error()) return } defer image.Destroy() w := float64(image.GetWidth()) h := float64(image.GetHeight()) pattern, _ := cairo.NewPatternForSurface(image) defer pattern.Destroy() pattern.SetExtend(cairo.EXTEND_REPEAT) c.Translate(128.0, 128.0) c.Rotate(math.Pi / 4) c.Scale(1/math.Sqrt(2), 1/math.Sqrt(2)) c.Translate(-128.0, -128.0) matrix := cairo.NewMatrix() matrix.InitScale(w/256.0*5.0, h/256.0*5.0) pattern.SetMatrix(matrix) c.SetSource(pattern) c.Rectangle(0, 0, 256.0, 256.0) c.Fill() } func ExampleMultiSegmentCaps(c *cairo.Canvas) { c.MoveTo(50.0, 75.0) c.LineTo(200.0, 75.0) c.MoveTo(50.0, 125.0) c.LineTo(200.0, 125.0) c.MoveTo(50.0, 175.0) c.LineTo(200.0, 175.0) c.SetLineWidth(30.0) c.SetLineCap(cairo.LINE_CAP_ROUND) c.Stroke() } func ExampleRoundedRectangle(c *cairo.Canvas) { // a custom shape that could be wrapped in a function var ( x float64 = 25.6 // parameters like cairo_rectangle y float64 = 25.6 width float64 = 204.8 height float64 = 204.8 aspect float64 = 1.0 // aspect ratio corner_radius float64 = height / 10.0 // and corner curvature radius radius float64 = corner_radius / aspect degrees float64 = math.Pi / 180.0 ) c.NewSubPath() c.Arc(x+width-radius, y+radius, radius, -90*degrees, 0*degrees) c.Arc(x+width-radius, y+height-radius, radius, 0*degrees, 90*degrees) c.Arc(x+radius, y+height-radius, radius, 90*degrees, 180*degrees) c.Arc(x+radius, y+radius, radius, 180*degrees, 270*degrees) c.ClosePath() c.SetSourceRGB(0.5, 0.5, 1) c.FillPreserve() c.SetSourceRGBA(0.5, 0, 0, 0.5) c.SetLineWidth(10.0) c.Stroke() } func ExampleSetLineCap(c *cairo.Canvas) { c.SetLineWidth(30.0) c.SetLineCap(cairo.LINE_CAP_BUTT) // default c.MoveTo(64.0, 50.0) c.LineTo(64.0, 200.0) c.Stroke() c.SetLineCap(cairo.LINE_CAP_ROUND) c.MoveTo(128.0, 50.0) c.LineTo(128.0, 200.0) c.Stroke() c.SetLineCap(cairo.LINE_CAP_SQUARE) c.MoveTo(192.0, 50.0) c.LineTo(192.0, 200.0) c.Stroke() // draw helping lines c.SetSourceRGB(1, 0.2, 0.2) c.SetLineWidth(2.56) c.MoveTo(64.0, 50.0) c.LineTo(64.0, 200.0) c.MoveTo(128.0, 50.0) c.LineTo(128.0, 200.0) c.MoveTo(192.0, 50.0) c.LineTo(192.0, 200.0) c.Stroke() } func ExampleText(c *cairo.Canvas) { c.SelectFontFace("Sans", cairo.FONT_SLANT_NORMAL, cairo.FONT_WEIGHT_BOLD) c.SetFontSize(90.0) c.MoveTo(10.0, 135.0) c.ShowText("Hello") c.MoveTo(70.0, 165.0) c.TextPath("void") c.SetSourceRGB(0.5, 0.5, 1) c.FillPreserve() c.SetSourceRGB(0, 0, 0) c.SetLineWidth(2.56) c.Stroke() // draw helping lines c.SetSourceRGBA(1, 0.2, 0.2, 0.6) c.Arc(10.0, 135.0, 5.12, 0, 2*math.Pi) c.ClosePath() c.Arc(70.0, 165.0, 5.12, 0, 2*math.Pi) c.Fill() } func ExampleTextAlignCenter(c *cairo.Canvas) { var extents cairo.TextExtents text := "cairo" var x, y float64 c.SelectFontFace("Sans", cairo.FONT_SLANT_NORMAL, cairo.FONT_WEIGHT_NORMAL) c.SetFontSize(52.0) c.TextExtents(text, &extents) x = 128.0 - (extents.Width/2 + extents.BearingX) y = 128.0 - (extents.Height/2 + extents.BearingY) c.MoveTo(x, y) c.ShowText(text) // draw helping lines c.SetSourceRGBA(1, 0.2, 0.2, 0.6) c.SetLineWidth(6.0) c.Arc(x, y, 10.0, 0, 2*math.Pi) c.Fill() c.MoveTo(128.0, 0) c.RelLineTo(0, 256) c.MoveTo(0, 128.0) c.RelLineTo(256, 0) c.Stroke() } func ExampleTextExtents(c *cairo.Canvas) { var extents cairo.TextExtents text := "cairo" var x, y float64 c.SelectFontFace("Sans", cairo.FONT_SLANT_NORMAL, cairo.FONT_WEIGHT_NORMAL) c.SetFontSize(100.0) c.TextExtents(text, &extents) x = 25.0 y = 150.0 c.MoveTo(x, y) c.ShowText(text) // draw helping lines c.SetSourceRGBA(1, 0.2, 0.2, 0.6) c.SetLineWidth(6.0) c.Arc(x, y, 10.0, 0, 2*math.Pi) c.Fill() c.MoveTo(x, y) c.RelLineTo(0, -extents.Height) c.RelLineTo(extents.Width, 0) c.RelLineTo(extents.BearingX, -extents.BearingY) c.Stroke() } func main() { var ( size = Size{256, 256} dir = "./result" ) if err := makeDir(dir); err != nil { fmt.Println(err.Error()) return } es := []Example{ Example{ExampleHelloWorld, dir, "example-hello-world.png", size}, Example{ExampleArc, dir, "example-arc.png", size}, Example{ExampleArcNegative, dir, "example-arc-negative.png", size}, Example{ExampleClip, dir, "example-clip.png", size}, Example{ExampleClipImage, dir, "example-clip-image.png", size}, Example{ExampleCurveRectangle, dir, "example-curve-rectangle.png", size}, Example{ExampleCurveTo, dir, "example-curve-to.png", size}, Example{ExampleGradient, dir, "example-gradient.png", size}, Example{ExampleSetLineJoin, dir, "example-set-line-join.png", size}, Example{ExampleDonut, dir, "example-donut.png", size}, Example{ExampleDash, dir, "example-dash.png", size}, Example{ExampleFillAndStroke2, dir, "example-fill-and-stroke2.png", size}, Example{ExampleFillStyle, dir, "example-fill-style.png", size}, Example{ExampleImage, dir, "example-image.png", size}, Example{ExampleImagePattern, dir, "example-image-pattern.png", size}, Example{ExampleMultiSegmentCaps, dir, "example-multi-segment-caps.png", size}, Example{ExampleRoundedRectangle, dir, "example-rounded-rectangle.png", size}, Example{ExampleSetLineCap, dir, "example-set-line-cap.png", size}, Example{ExampleText, dir, "example-text.png", size}, Example{ExampleTextAlignCenter, dir, "example-text-align-center.png", size}, Example{ExampleTextExtents, dir, "example-text-extents.png", size}, } for _, e := range es { if err := e.Execute(); err != nil { fmt.Println(err.Error()) return } } }
package fibonacci import ( "testing" ) func TestFibonacci(t *testing.T) { want := 55 got := Fibonacci(10) if got[10] != want { t.Fatalf("expectation: %d\nreality: %d", want, got) } }
// https://www.hackerrank.com/challenges/balanced-parentheses package main import ( "bufio" "fmt" "os" ) func main() { var t int _, err := fmt.Scan(&t) if err == nil { scanner := bufio.NewScanner(os.Stdin) testCases := make([]string, t) for i := 0; i < t; i++ { if !scanner.Scan() { break } testCases[i] = scanner.Text() } lookup := map[rune]rune{ '{': '}', '[': ']', '(': ')', } var stack []rune for _, testCase := range testCases { var result string for _, r := range testCase { if _, exists := lookup[r]; exists { stack = append(stack, r) result = "NO" } else { l := len(stack) if l == 0 { result = "NO" break } var x rune stack, x = stack[:l-1], stack[l-1] if r != lookup[x] { result = "NO" break } else { result = "YES" } } } fmt.Println(result) } } }
package models import ( "fmt" "github.com/kjirou/tower-of-go/utils" "testing" "time" "strings" ) func TestField_At_NotTD(t *testing.T) { field := createField(2, 3) t.Run("指定した位置の要素を取得できる", func(t *testing.T) { element, _ := field.At(&utils.MatrixPosition{Y: 1, X: 2}) if element.GetPosition().GetY() != 1 { t.Fatal("Y が違う") } else if element.GetPosition().GetX() != 2 { t.Fatal("X が違う") } }) t.Run("存在しない位置を指定したとき", func(t *testing.T) { type testCase struct{ Y int X int } var testCases []testCase testCases = append(testCases, testCase{Y: -1, X: 0}) testCases = append(testCases, testCase{Y: 2, X: 0}) testCases = append(testCases, testCase{Y: 0, X: -1}) testCases = append(testCases, testCase{Y: 0, X: 3}) for _, tc := range testCases { tc := tc t.Run(fmt.Sprintf("Y=%d,X=%dはエラーを返す", tc.Y, tc.X), func(t *testing.T) { _, err := field.At(&utils.MatrixPosition{Y: tc.Y, X: tc.X}) if err == nil { t.Fatal("エラーを返さない") } else if !strings.Contains(err.Error(), " position ") { t.Fatal("意図したエラーメッセージではない") } }) } }) } func TestField_GetElementOfHero_NotTD(t *testing.T) { t.Run("ヒーローが存在しないときはエラーを返す", func(t *testing.T) { field := createField(3, 5) _, err := field.GetElementOfHero() if err == nil { t.Fatal("エラーを返さない") } else if !strings.Contains(err.Error(), "does not exist") { t.Fatal("意図したエラーメッセージではない") } }) t.Run("ヒーローが複数存在するときはエラーを返す", func(t *testing.T) { field := createField(3, 5) field.matrix[0][0].UpdateObjectClass("hero") field.matrix[0][1].UpdateObjectClass("hero") _, err := field.GetElementOfHero() if err == nil { t.Fatal("エラーを返さない") } else if !strings.Contains(err.Error(), " multiple ") { t.Fatal("意図したエラーメッセージではない") } }) } func TestField_MoveObject_NotTD(t *testing.T) { field := createField(2, 3) fromPosition := &utils.MatrixPosition{Y: 0, X: 0} toPosition := &utils.MatrixPosition{Y: 1, X: 2} fromElement, _ := field.At(fromPosition) toElement, _ := field.At(toPosition) t.Run("始点の物体が空ではなく、終点の物体が空のとき、物体種別が移動する", func(t *testing.T) { fromElement.UpdateObjectClass("wall") toElement.UpdateObjectClass("empty") field.MoveObject(fromPosition, toPosition) if toElement.GetObjectClass() != "wall" { t.Fatal("物体種別が移動していない") } }) t.Run("始点の物体が空ではなく、終点の物体が空ではないとき、エラーを返す", func(t *testing.T) { fromElement.UpdateObjectClass("wall") toElement.UpdateObjectClass("wall") err := field.MoveObject(fromPosition, toPosition) if err == nil { t.Fatal("エラーを返さない") } else if !strings.Contains(err.Error(), "object exists") { t.Fatal("意図したエラーメッセージではない") } }) t.Run("始点の物体が空のとき、エラーを返す", func(t *testing.T) { fromElement.UpdateObjectClass("empty") err := field.MoveObject(fromPosition, toPosition) if err == nil { t.Fatal("エラーを返さない") } else if !strings.Contains(err.Error(), "does not exist") { t.Fatal("意図したエラーメッセージではない") } }) } func TestField_ResetMaze_NotTD(t *testing.T) { t.Run("外周1マスは壁になる", func(t *testing.T) { field := createField(7, 7) field.ResetMaze() for y, row := range field.matrix { for x, element := range row { isTopOrBottomEdge := y == 0 || y == field.MeasureRowLength()-1 isLeftOrRightEdge := x == 0 || x == field.MeasureColumnLength()-1 if (isTopOrBottomEdge || isLeftOrRightEdge) && element.GetObjectClass() != "wall" { t.Fatalf("Y=%d, X=%d が壁ではない", y, x) } } } }) t.Run("ヒーローが存在していたとき、ヒーローは削除される", func(t *testing.T) { field := createField(7, 7) element, err := field.At(HeroPosition) if err != nil { t.Fatal("ヒーローの配置に失敗する") } element.UpdateObjectClass("hero") field.ResetMaze() for _, row := range field.matrix { for _, element := range row { if element.GetObjectClass() == "hero" { t.Fatal("ヒーローが存在している") } } } }) } func TestGame_CalculateRemainingTime_NotTD(t *testing.T) { game := &Game{} t.Run("リセット直後は30を返す", func(t *testing.T) { game.Reset() executionTime, _ := time.ParseDuration("2s") remainingTime := game.CalculateRemainingTime(executionTime) if remainingTime.Seconds() != 30 { t.Fatal("30ではない") } }) t.Run("最小で0を返す", func(t *testing.T) { game.Reset() startTime, _ := time.ParseDuration("1s") game.Start(startTime) currentTime, _ := time.ParseDuration("999s") remainingTime := game.CalculateRemainingTime(currentTime) if remainingTime.Seconds() != 0 { t.Fatal("0ではない") } }) } func TestGame_Start_NotTD(t *testing.T) { game := &Game{} t.Run("It works", func(t *testing.T) { executionTime, _ := time.ParseDuration("0s") game.Start(executionTime) if game.IsStarted() { t.Fatal("開始している") } if game.IsFinished() { t.Fatal("終了している") } }) }
package config import ( "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/pomerium/pomerium/pkg/policy" "github.com/pomerium/pomerium/pkg/policy/parser" ) func TestPolicy_ToPPL(t *testing.T) { str, err := policy.GenerateRegoFromPolicy((&Policy{ AllowPublicUnauthenticatedAccess: true, CORSAllowPreflight: true, AllowAnyAuthenticatedUser: true, AllowedDomains: []string{"a.example.com", "b.example.com"}, AllowedUsers: []string{"user1", "user2"}, AllowedIDPClaims: map[string][]interface{}{ "family_name": {"Smith", "Jones"}, }, SubPolicies: []SubPolicy{ { AllowedDomains: []string{"c.example.com", "d.example.com"}, AllowedUsers: []string{"user3", "user4"}, AllowedIDPClaims: map[string][]interface{}{ "given_name": {"John"}, }, }, { AllowedDomains: []string{"e.example.com"}, AllowedUsers: []string{"user5"}, AllowedIDPClaims: map[string][]interface{}{ "timezone": {"EST"}, }, }, }, Policy: &PPLPolicy{ Policy: &parser.Policy{ Rules: []parser.Rule{{ Action: parser.ActionAllow, Or: []parser.Criterion{{ Name: "user", Data: parser.Object{ "is": parser.String("user6"), }, }}, }}, }, }, }).ToPPL()) require.NoError(t, err) assert.Equal(t, `package pomerium.policy default allow = [false, set()] default deny = [false, set()] accept_0 = [true, {"accept"}] cors_preflight_0 = [true, {"cors-request"}] { input.http.method == "OPTIONS" count(object.get(input.http.headers, "Access-Control-Request-Method", [])) > 0 count(object.get(input.http.headers, "Origin", [])) > 0 } else = [false, {"non-cors-request"}] authenticated_user_0 = [true, {"user-ok"}] { session := get_session(input.session.id) session.user_id != null session.user_id != "" } else = [false, {"user-unauthorized"}] { session := get_session(input.session.id) session.id != "" } else = [false, {"user-unauthenticated"}] domain_0 = [true, {"domain-ok"}] { session := get_session(input.session.id) user := get_user(session) domain := split(get_user_email(session, user), "@")[1] domain == "a.example.com" } else = [false, {"domain-unauthorized"}] { session := get_session(input.session.id) session.id != "" } else = [false, {"user-unauthenticated"}] domain_1 = [true, {"domain-ok"}] { session := get_session(input.session.id) user := get_user(session) domain := split(get_user_email(session, user), "@")[1] domain == "b.example.com" } else = [false, {"domain-unauthorized"}] { session := get_session(input.session.id) session.id != "" } else = [false, {"user-unauthenticated"}] domain_2 = [true, {"domain-ok"}] { session := get_session(input.session.id) user := get_user(session) domain := split(get_user_email(session, user), "@")[1] domain == "c.example.com" } else = [false, {"domain-unauthorized"}] { session := get_session(input.session.id) session.id != "" } else = [false, {"user-unauthenticated"}] domain_3 = [true, {"domain-ok"}] { session := get_session(input.session.id) user := get_user(session) domain := split(get_user_email(session, user), "@")[1] domain == "d.example.com" } else = [false, {"domain-unauthorized"}] { session := get_session(input.session.id) session.id != "" } else = [false, {"user-unauthenticated"}] domain_4 = [true, {"domain-ok"}] { session := get_session(input.session.id) user := get_user(session) domain := split(get_user_email(session, user), "@")[1] domain == "e.example.com" } else = [false, {"domain-unauthorized"}] { session := get_session(input.session.id) session.id != "" } else = [false, {"user-unauthenticated"}] claim_0 = [true, {"claim-ok"}] { rule_data := "Smith" rule_path := "family_name" session := get_session(input.session.id) session_claims := object.get(session, "claims", {}) user := get_user(session) user_claims := object.get(user, "claims", {}) all_claims := object.union(session_claims, user_claims) values := object_get(all_claims, rule_path, []) rule_data == values[_0] } else = [false, {"claim-unauthorized"}] { session := get_session(input.session.id) session.id != "" } else = [false, {"user-unauthenticated"}] claim_1 = [true, {"claim-ok"}] { rule_data := "Jones" rule_path := "family_name" session := get_session(input.session.id) session_claims := object.get(session, "claims", {}) user := get_user(session) user_claims := object.get(user, "claims", {}) all_claims := object.union(session_claims, user_claims) values := object_get(all_claims, rule_path, []) rule_data == values[_0] } else = [false, {"claim-unauthorized"}] { session := get_session(input.session.id) session.id != "" } else = [false, {"user-unauthenticated"}] claim_2 = [true, {"claim-ok"}] { rule_data := "John" rule_path := "given_name" session := get_session(input.session.id) session_claims := object.get(session, "claims", {}) user := get_user(session) user_claims := object.get(user, "claims", {}) all_claims := object.union(session_claims, user_claims) values := object_get(all_claims, rule_path, []) rule_data == values[_0] } else = [false, {"claim-unauthorized"}] { session := get_session(input.session.id) session.id != "" } else = [false, {"user-unauthenticated"}] claim_3 = [true, {"claim-ok"}] { rule_data := "EST" rule_path := "timezone" session := get_session(input.session.id) session_claims := object.get(session, "claims", {}) user := get_user(session) user_claims := object.get(user, "claims", {}) all_claims := object.union(session_claims, user_claims) values := object_get(all_claims, rule_path, []) rule_data == values[_0] } else = [false, {"claim-unauthorized"}] { session := get_session(input.session.id) session.id != "" } else = [false, {"user-unauthenticated"}] user_0 = [true, {"user-ok"}] { session := get_session(input.session.id) user_id := session.user_id user_id == "user1" } else = [false, {"user-unauthorized"}] { session := get_session(input.session.id) session.id != "" } else = [false, {"user-unauthenticated"}] email_0 = [true, {"email-ok"}] { session := get_session(input.session.id) user := get_user(session) email := get_user_email(session, user) email == "user1" } else = [false, {"email-unauthorized"}] { session := get_session(input.session.id) session.id != "" } else = [false, {"user-unauthenticated"}] user_1 = [true, {"user-ok"}] { session := get_session(input.session.id) user_id := session.user_id user_id == "user2" } else = [false, {"user-unauthorized"}] { session := get_session(input.session.id) session.id != "" } else = [false, {"user-unauthenticated"}] email_1 = [true, {"email-ok"}] { session := get_session(input.session.id) user := get_user(session) email := get_user_email(session, user) email == "user2" } else = [false, {"email-unauthorized"}] { session := get_session(input.session.id) session.id != "" } else = [false, {"user-unauthenticated"}] user_2 = [true, {"user-ok"}] { session := get_session(input.session.id) user_id := session.user_id user_id == "user3" } else = [false, {"user-unauthorized"}] { session := get_session(input.session.id) session.id != "" } else = [false, {"user-unauthenticated"}] email_2 = [true, {"email-ok"}] { session := get_session(input.session.id) user := get_user(session) email := get_user_email(session, user) email == "user3" } else = [false, {"email-unauthorized"}] { session := get_session(input.session.id) session.id != "" } else = [false, {"user-unauthenticated"}] user_3 = [true, {"user-ok"}] { session := get_session(input.session.id) user_id := session.user_id user_id == "user4" } else = [false, {"user-unauthorized"}] { session := get_session(input.session.id) session.id != "" } else = [false, {"user-unauthenticated"}] email_3 = [true, {"email-ok"}] { session := get_session(input.session.id) user := get_user(session) email := get_user_email(session, user) email == "user4" } else = [false, {"email-unauthorized"}] { session := get_session(input.session.id) session.id != "" } else = [false, {"user-unauthenticated"}] user_4 = [true, {"user-ok"}] { session := get_session(input.session.id) user_id := session.user_id user_id == "user5" } else = [false, {"user-unauthorized"}] { session := get_session(input.session.id) session.id != "" } else = [false, {"user-unauthenticated"}] email_4 = [true, {"email-ok"}] { session := get_session(input.session.id) user := get_user(session) email := get_user_email(session, user) email == "user5" } else = [false, {"email-unauthorized"}] { session := get_session(input.session.id) session.id != "" } else = [false, {"user-unauthenticated"}] or_0 = v { results := [accept_0, cors_preflight_0, authenticated_user_0, domain_0, domain_1, domain_2, domain_3, domain_4, claim_0, claim_1, claim_2, claim_3, user_0, email_0, user_1, email_1, user_2, email_2, user_3, email_3, user_4, email_4] normalized := [normalize_criterion_result(x) | x := results[i]] v := merge_with_or(normalized) } user_5 = [true, {"user-ok"}] { session := get_session(input.session.id) user_id := session.user_id user_id == "user6" } else = [false, {"user-unauthorized"}] { session := get_session(input.session.id) session.id != "" } else = [false, {"user-unauthenticated"}] or_1 = v { results := [user_5] normalized := [normalize_criterion_result(x) | x := results[i]] v := merge_with_or(normalized) } allow = v { results := [or_0, or_1] normalized := [normalize_criterion_result(x) | x := results[i]] v := merge_with_or(normalized) } invert_criterion_result(in) = out { in[0] out = array.concat([false], array.slice(in, 1, count(in))) } else = out { not in[0] out = array.concat([true], array.slice(in, 1, count(in))) } normalize_criterion_result(result) = v { is_boolean(result) v = [result, set()] } else = v { is_array(result) v = result } else = v { v = [false, set()] } object_union(xs) = merged { merged = {k: v | some k xs[_0][k] vs := [xv | xv := xs[_][k]] v := vs[count(vs) - 1] } } merge_with_and(results) = [true, reasons, additional_data] { true_results := [x | x := results[i]; x[0]] count(true_results) == count(results) reasons := union({x | x := true_results[i][1]}) additional_data := object_union({x | x := true_results[i][2]}) } else = [false, reasons, additional_data] { false_results := [x | x := results[i]; not x[0]] reasons := union({x | x := false_results[i][1]}) additional_data := object_union({x | x := false_results[i][2]}) } merge_with_or(results) = [true, reasons, additional_data] { true_results := [x | x := results[i]; x[0]] count(true_results) > 0 reasons := union({x | x := true_results[i][1]}) additional_data := object_union({x | x := true_results[i][2]}) } else = [false, reasons, additional_data] { false_results := [x | x := results[i]; not x[0]] reasons := union({x | x := false_results[i][1]}) additional_data := object_union({x | x := false_results[i][2]}) } get_session(id) = v { v = get_databroker_record("type.googleapis.com/user.ServiceAccount", id) v != null } else = iv { v = get_databroker_record("type.googleapis.com/session.Session", id) v != null object.get(v, "impersonate_session_id", "") != "" iv = get_databroker_record("type.googleapis.com/session.Session", v.impersonate_session_id) iv != null } else = v { v = get_databroker_record("type.googleapis.com/session.Session", id) v != null object.get(v, "impersonate_session_id", "") == "" } else = {} get_user(session) = v { v = get_databroker_record("type.googleapis.com/user.User", session.user_id) v != null } else = {} get_user_email(session, user) = v { v = user.email } else = "" object_get(obj, key, def) = value { undefined := "10a0fd35-0f1a-4e5b-97ce-631e89e1bafa" value = object.get(obj, key, undefined) value != undefined } else = value { segments := split(replace(key, ".", "/"), "/") count(segments) == 2 o1 := object.get(obj, segments[0], {}) value = object.get(o1, segments[1], def) } else = value { segments := split(replace(key, ".", "/"), "/") count(segments) == 3 o1 := object.get(obj, segments[0], {}) o2 := object.get(o1, segments[1], {}) value = object.get(o2, segments[2], def) } else = value { segments := split(replace(key, ".", "/"), "/") count(segments) == 4 o1 := object.get(obj, segments[0], {}) o2 := object.get(o1, segments[1], {}) o3 := object.get(o2, segments[2], {}) value = object.get(o3, segments[3], def) } else = value { segments := split(replace(key, ".", "/"), "/") count(segments) == 5 o1 := object.get(obj, segments[0], {}) o2 := object.get(o1, segments[1], {}) o3 := object.get(o2, segments[2], {}) o4 := object.get(o3, segments[3], {}) value = object.get(o4, segments[4], def) } else = value { value = object.get(obj, key, def) } `, str) }
package exception //go:generate go install github.com/Beyond-simplechain/foundation/log //go:generate go install github.com/Beyond-simplechain/foundation/exception //go:generate gotemplate -outfmt "gen_%v" "github.com/Beyond-simplechain/foundation/exception/template" "StdException(Exception,StdExceptionCode,\"golang standard error\")" //go:generate gotemplate -outfmt "gen_%v" "github.com/Beyond-simplechain/foundation/exception/template" "FcException(Exception,UnspecifiedExceptionCode,\"unspecified\")" //go:generate gotemplate -outfmt "gen_%v" "github.com/Beyond-simplechain/foundation/exception/template" "UnHandledException(Exception,UnhandledExceptionCode,\"unhandled\")" //go:generate gotemplate -outfmt "gen_%v" "github.com/Beyond-simplechain/foundation/exception/template" "AssertException(Exception,AssertExceptionCode,\"Assert Exception\")" //go:generate go build .
package parser import ( "github.com/PuerkitoBio/goquery" "spider/entity" ) type Parser interface { ConnectDocument(target string) *goquery.Selection //连接爬取页面,并设置css选择器 SelectorService(i int, selection *goquery.Selection) //处理经过css选择器筛选后的元素 GetDocInfo() []entity.JobInfo //返回爬取信息 }
package dbsrv import ( "os" "time" "gopkg.in/doug-martin/goqu.v3" "github.com/empirefox/esecend/front" "github.com/empirefox/reform" ) func (dbs *DbService) WishlistSave(userId uint, payload *front.WishlistSavePayload) (*front.WishItem, error) { data := &front.WishItem{ UserID: userId, CreatedAt: time.Now().Unix(), Name: payload.Name, Img: payload.Img, Price: payload.Price, ProductID: payload.ProductID, } err := dbs.db.InTransaction(func(db *reform.TX) error { ds := dbs.DS.Where(goqu.I("$UserID").Eq(userId)).Where(goqu.I("$ProductID").Eq(payload.ProductID)) // update first ra, err := db.DsUpdateStruct(data, ds) if err != nil { return err } if ra == 0 { return db.Insert(data) } table := front.WishItemTable query, args, err := ds.From(table.Name()).Select(table.PK()).Limit(1).ToSql() if err != nil { return err } if err = db.QueryRow(os.Expand(query, table.ToCol), args...).Scan(&data.ID); err != nil { return err } if ra > 1 { if _, err = db.DsDelete(table, ds.Where(goqu.I(table.PK()).Neq(data.ID))); err != nil { return err } } return nil }) if err != nil { return nil, err } return data, nil } func (dbs *DbService) WishlistDel(userId uint, ids []uint) error { ds := dbs.DS.Where(goqu.I("$UserID").Eq(userId)) if len(ids) != 0 { ds = ds.Where(goqu.I("$ProductID").In(ids)) } _, err := dbs.GetDB().DsDelete(front.WishItemTable, ds) return err }
package routers import ( "errors" "io/ioutil" "net/http" "regexp" "strconv" "github.com/gin-gonic/gin" "github.com/vpakhuchyi/web-server/models" ) //POSTJSONHandler is a POST handler for "/searchText"; //it checks incoming JSON and sends a result of "searchForArgsOnEachSite" func as JSON response. func POSTJSONHandler(c *gin.Context) { var reqjson models.Request if c.Bind(&reqjson) == nil && len(reqjson.Site) > 0 && len(reqjson.SearchText) > 0 { var respjson models.Response result, err := SearchForArgOnSites(reqjson.SearchText, reqjson.Site) code := 400 if err != nil { c.Error(err) if err.Error() == "no content" { code = 204 } c.Writer.WriteString("HTTP code " + strconv.Itoa(code) + " " + err.Error()) } else { respjson.FoundAtSite = result c.JSON(http.StatusOK, respjson) } } } func getContentFromURL(url string) []byte { if url != "" { res, _ := http.Get(url) c, _ := ioutil.ReadAll(res.Body) defer res.Body.Close() return c } return nil } func checkConnectionToURL(url string) error { _, err := http.Get(url) return err } //SearchForArgOnSites receive a string "text" for search and a []string "sites" for searching place; //func returns string and error; //if text was found it returnes string with URL where it was found and nil error; //func returns empty string and not-nil error when text wasn't found. func SearchForArgOnSites(text string, sites []string) (r string, err error) { if text == "" { err = errors.New("invailid request") return r, err } retext := regexp.MustCompile(text) for _, val := range sites { if checkConnectionToURL(val) != nil { err = errors.New("invailid request") continue } if retext.Find(getContentFromURL(val)) != nil { r = val err = nil break } else { err = errors.New("no content") } } return r, err }
package influxdb import ( "encoding/json" "math" "regexp" "sort" "strings" "time" "github.com/boltdb/bolt" "github.com/influxdb/influxdb/influxql" ) // database is a collection of retention policies and shards. It also has methods // for keeping an in memory index of all the measurements, series, and tags in the database. // Methods on this struct aren't goroutine safe. They assume that the server is handling // any locking to make things safe. type database struct { name string policies map[string]*RetentionPolicy // retention policies by name defaultRetentionPolicy string // in memory indexing structures measurements map[string]*Measurement // measurement name to object and index series map[uint32]*Series // map series id to the Series object names []string // sorted list of the measurement names } // newDatabase returns an instance of database. func newDatabase() *database { return &database{ policies: make(map[string]*RetentionPolicy), measurements: make(map[string]*Measurement), series: make(map[uint32]*Series), names: make([]string, 0), } } // shardGroupByTimestamp returns a shard group that owns a given timestamp. func (db *database) shardGroupByTimestamp(policy string, timestamp time.Time) (*ShardGroup, error) { p := db.policies[policy] if p == nil { return nil, ErrRetentionPolicyNotFound } return p.shardGroupByTimestamp(timestamp), nil } // timeBetweenInclusive returns true if t is between min and max, inclusive. func timeBetweenInclusive(t, min, max time.Time) bool { return (t.Equal(min) || t.After(min)) && (t.Equal(max) || t.Before(max)) } // MarshalJSON encodes a database into a JSON-encoded byte slice. func (db *database) MarshalJSON() ([]byte, error) { // Copy over properties to intermediate type. var o databaseJSON o.Name = db.name o.DefaultRetentionPolicy = db.defaultRetentionPolicy for _, rp := range db.policies { o.Policies = append(o.Policies, rp) } return json.Marshal(&o) } // UnmarshalJSON decodes a JSON-encoded byte slice to a database. func (db *database) UnmarshalJSON(data []byte) error { // Decode into intermediate type. var o databaseJSON if err := json.Unmarshal(data, &o); err != nil { return err } // Copy over properties from intermediate type. db.name = o.Name db.defaultRetentionPolicy = o.DefaultRetentionPolicy // Copy shard policies. db.policies = make(map[string]*RetentionPolicy) for _, rp := range o.Policies { db.policies[rp.Name] = rp } return nil } // databaseJSON represents the JSON-serialization format for a database. type databaseJSON struct { Name string `json:"name,omitempty"` DefaultRetentionPolicy string `json:"defaultRetentionPolicy,omitempty"` Policies []*RetentionPolicy `json:"policies,omitempty"` } // Measurement represents a collection of time series in a database. It also contains in memory // structures for indexing tags. These structures are accessed through private methods on the Measurement // object. Generally these methods are only accessed from Index, which is responsible for ensuring // go routine safe access. type Measurement struct { Name string `json:"name,omitempty"` Fields []*Field `json:"fields,omitempty"` // in memory index fields series map[string]*Series // sorted tagset string to the series object seriesByID map[uint32]*Series // lookup table for series by their id measurement *Measurement seriesByTagKeyValue map[string]map[string]SeriesIDs // map from tag key to value to sorted set of series ids ids SeriesIDs // sorted list of series IDs in this measurement } func NewMeasurement(name string) *Measurement { return &Measurement{ Name: name, Fields: make([]*Field, 0), series: make(map[string]*Series), seriesByID: make(map[uint32]*Series), seriesByTagKeyValue: make(map[string]map[string]SeriesIDs), ids: SeriesIDs(make([]uint32, 0)), } } // createFieldIfNotExists creates a new field with an autoincrementing ID. // Returns an error if 255 fields have already been created on the measurement. func (m *Measurement) createFieldIfNotExists(name string, typ influxql.DataType) (*Field, error) { // Ignore if the field already exists. if f := m.FieldByName(name); f != nil { return f, nil } // Only 255 fields are allowed. If we go over that then return an error. if len(m.Fields)+1 > math.MaxUint8 { return nil, ErrFieldOverflow } // Create and append a new field. f := &Field{ ID: uint8(len(m.Fields) + 1), Name: name, Type: typ, } m.Fields = append(m.Fields, f) return f, nil } // Field returns a field by id. func (m *Measurement) Field(id uint8) *Field { for _, f := range m.Fields { if f.ID == id { return f } } return nil } // FieldByName returns a field by name. func (m *Measurement) FieldByName(name string) *Field { for _, f := range m.Fields { if f.Name == name { return f } } return nil } // addSeries will add a series to the measurementIndex. Returns false if already present func (m *Measurement) addSeries(s *Series) bool { if _, ok := m.seriesByID[s.ID]; ok { return false } m.seriesByID[s.ID] = s tagset := string(marshalTags(s.Tags)) m.series[tagset] = s m.ids = append(m.ids, s.ID) // the series ID should always be higher than all others because it's a new // series. So don't do the sort if we don't have to. if len(m.ids) > 1 && m.ids[len(m.ids)-1] < m.ids[len(m.ids)-2] { sort.Sort(m.ids) } // add this series id to the tag index on the measurement for k, v := range s.Tags { valueMap := m.seriesByTagKeyValue[k] if valueMap == nil { valueMap = make(map[string]SeriesIDs) m.seriesByTagKeyValue[k] = valueMap } ids := valueMap[v] ids = append(ids, s.ID) // most of the time the series ID will be higher than all others because it's a new // series. So don't do the sort if we don't have to. if len(ids) > 1 && ids[len(ids)-1] < ids[len(ids)-2] { sort.Sort(ids) } valueMap[v] = ids } return true } // seriesByTags returns the Series that matches the given tagset. func (m *Measurement) seriesByTags(tags map[string]string) *Series { return m.series[string(marshalTags(tags))] } // seriesIDs returns the series ids for a given filter func (m *Measurement) seriesIDs(filter *TagFilter) (ids SeriesIDs) { values := m.seriesByTagKeyValue[filter.Key] if values == nil { return } // handle regex filters if filter.Regex != nil { for k, v := range values { if filter.Regex.MatchString(k) { if ids == nil { ids = v } else { ids = ids.Union(v) } } } if filter.Not { ids = m.ids.Reject(ids) } return } // this is for the value is not null query if filter.Not && filter.Value == "" { for _, v := range values { if ids == nil { ids = v } else { ids.Intersect(v) } } return } // get the ids that have the given key/value tag pair ids = SeriesIDs(values[filter.Value]) // filter out these ids from the entire set if it's a not query if filter.Not { ids = m.ids.Reject(ids) } return } // tagValues returns a map of unique tag values for the given key func (m *Measurement) tagValues(key string) TagValues { tags := m.seriesByTagKeyValue[key] values := make(map[string]bool, len(tags)) for k, _ := range tags { values[k] = true } return TagValues(values) } // mapValues converts a map of values with string keys to field id keys. // Returns nil if any field doesn't exist. func (m *Measurement) mapValues(values map[string]interface{}) map[uint8]interface{} { other := make(map[uint8]interface{}, len(values)) for k, v := range values { // TODO: Cast value to original field type. f := m.FieldByName(k) if f == nil { return nil } other[f.ID] = v } return other } type Measurements []*Measurement // Field represents a series field. type Field struct { ID uint8 `json:"id,omitempty"` Name string `json:"name,omitempty"` Type influxql.DataType `json:"type,omitempty"` } // Fields represents a list of fields. type Fields []*Field // Series belong to a Measurement and represent unique time series in a database type Series struct { ID uint32 Tags map[string]string measurement *Measurement } // match returns true if all tags match the series' tags. func (s *Series) match(tags map[string]string) bool { for k, v := range tags { if s.Tags[k] != v { return false } } return true } // RetentionPolicy represents a policy for creating new shards in a database and how long they're kept around for. type RetentionPolicy struct { // Unique name within database. Required. Name string // Length of time to keep data around Duration time.Duration // The number of copies to make of each shard. ReplicaN uint32 shardGroups []*ShardGroup } // NewRetentionPolicy returns a new instance of RetentionPolicy with defaults set. func NewRetentionPolicy(name string) *RetentionPolicy { return &RetentionPolicy{ Name: name, ReplicaN: DefaultReplicaN, Duration: DefaultShardRetention, } } // shardGroupByTimestamp returns the group in the policy that owns a timestamp. // Returns nil group does not exist. func (rp *RetentionPolicy) shardGroupByTimestamp(timestamp time.Time) *ShardGroup { for _, g := range rp.shardGroups { if timeBetweenInclusive(timestamp, g.StartTime, g.EndTime) { return g } } return nil } // MarshalJSON encodes a retention policy to a JSON-encoded byte slice. func (rp *RetentionPolicy) MarshalJSON() ([]byte, error) { var o retentionPolicyJSON o.Name = rp.Name o.Duration = rp.Duration o.ReplicaN = rp.ReplicaN for _, g := range rp.shardGroups { o.ShardGroups = append(o.ShardGroups, g) } return json.Marshal(&o) } // UnmarshalJSON decodes a JSON-encoded byte slice to a retention policy. func (rp *RetentionPolicy) UnmarshalJSON(data []byte) error { // Decode into intermediate type. var o retentionPolicyJSON if err := json.Unmarshal(data, &o); err != nil { return err } // Copy over properties from intermediate type. rp.Name = o.Name rp.ReplicaN = o.ReplicaN rp.Duration = o.Duration rp.shardGroups = o.ShardGroups return nil } // retentionPolicyJSON represents an intermediate struct for JSON marshaling. type retentionPolicyJSON struct { Name string `json:"name"` ReplicaN uint32 `json:"replicaN,omitempty"` SplitN uint32 `json:"splitN,omitempty"` Duration time.Duration `json:"duration,omitempty"` ShardGroups []*ShardGroup `json:"shardGroups,omitempty"` } // TagFilter represents a tag filter when looking up other tags or measurements. type TagFilter struct { Not bool Key string Value string Regex *regexp.Regexp } // SeriesIDs is a convenience type for sorting, checking equality, and doing union and // intersection of collections of series ids. type SeriesIDs []uint32 func (p SeriesIDs) Len() int { return len(p) } func (p SeriesIDs) Less(i, j int) bool { return p[i] < p[j] } func (p SeriesIDs) Swap(i, j int) { p[i], p[j] = p[j], p[i] } // Equals assumes that both are sorted. This is by design, no touchy! func (a SeriesIDs) Equals(seriesIDs SeriesIDs) bool { if len(a) != len(seriesIDs) { return false } for i, s := range seriesIDs { if a[i] != s { return false } } return true } // Intersect returns a new collection of series ids in sorted order that is the intersection of the two. // The two collections must already be sorted. func (a SeriesIDs) Intersect(seriesIDs SeriesIDs) SeriesIDs { l := a r := seriesIDs // we want to iterate through the shortest one and stop if len(seriesIDs) < len(a) { l = seriesIDs r = a } // they're in sorted order so advance the counter as needed. // That is, don't run comparisons against lower values that we've already passed var i, j int ids := make([]uint32, 0, len(l)) for i < len(l) && j < len(r) { if l[i] == r[j] { ids = append(ids, l[i]) i += 1 j += 1 } else if l[i] < r[j] { i += 1 } else { j += 1 } } return SeriesIDs(ids) } // Union returns a new collection of series ids in sorted order that is the union of the two. // The two collections must already be sorted. func (l SeriesIDs) Union(r SeriesIDs) SeriesIDs { ids := make([]uint32, 0, len(l)+len(r)) var i, j int for i < len(l) && j < len(r) { if l[i] == r[j] { ids = append(ids, l[i]) i += 1 j += 1 } else if l[i] < r[j] { ids = append(ids, l[i]) i += 1 } else { ids = append(ids, r[j]) j += 1 } } // now append the remainder if i < len(l) { ids = append(ids, l[i:]...) } else if j < len(r) { ids = append(ids, r[j:]...) } return ids } // Reject returns a new collection of series ids in sorted order with the passed in set removed from the original. This is useful for the NOT operator. // The two collections must already be sorted. func (l SeriesIDs) Reject(r SeriesIDs) SeriesIDs { var i, j int ids := make([]uint32, 0, len(l)) for i < len(l) && j < len(r) { if l[i] == r[j] { i += 1 j += 1 } else if l[i] < r[j] { ids = append(ids, l[i]) i += 1 } else { j += 1 } } // append the remainder if i < len(l) { ids = append(ids, l[i:]...) } return SeriesIDs(ids) } // addSeriesToIndex adds the series for the given measurement to the index. Returns false if already present func (d *database) addSeriesToIndex(measurementName string, s *Series) bool { // if there is a measurement for this id, it's already been added if d.series[s.ID] != nil { return false } // get or create the measurement index and index it globally and in the measurement idx := d.createMeasurementIfNotExists(measurementName) s.measurement = idx d.series[s.ID] = s // TODO: add this series to the global tag index return idx.addSeries(s) } // createMeasurementIfNotExists will either add a measurement object to the index or return the existing one. func (d *database) createMeasurementIfNotExists(name string) *Measurement { idx := d.measurements[name] if idx == nil { idx = NewMeasurement(name) d.measurements[name] = idx d.names = append(d.names, name) sort.Strings(d.names) } return idx } // MeasurementsBySeriesIDs returns a collection of unique Measurements for the passed in SeriesIDs. func (d *database) MeasurementsBySeriesIDs(seriesIDs SeriesIDs) []*Measurement { measurements := make(map[*Measurement]bool) for _, id := range seriesIDs { m := d.series[id].measurement measurements[m] = true } values := make([]*Measurement, 0, len(measurements)) for m, _ := range measurements { values = append(values, m) } return values } // SeriesIDs returns an array of series ids for the given measurements and filters to be applied to all. // Filters are equivalent to an AND operation. If you want to do an OR, get the series IDs for one set, // then get the series IDs for another set and use the SeriesIDs.Union to combine the two. func (d *database) SeriesIDs(names []string, filters []*TagFilter) SeriesIDs { // they want all ids if no filters are specified if len(filters) == 0 { ids := SeriesIDs(make([]uint32, 0)) for _, idx := range d.measurements { ids = ids.Union(idx.ids) } return ids } ids := SeriesIDs(make([]uint32, 0)) for _, n := range names { ids = ids.Union(d.seriesIDsByName(n, filters)) } return ids } // TagKeys returns a sorted array of unique tag keys for the given measurements. // If an empty or nil slice is passed in, the tag keys for the entire database will be returned. func (d *database) TagKeys(names []string) []string { if len(names) == 0 { names = d.names } keys := make(map[string]bool) for _, n := range names { idx := d.measurements[n] if idx != nil { for k, _ := range idx.seriesByTagKeyValue { keys[k] = true } } } sortedKeys := make([]string, 0, len(keys)) for k, _ := range keys { sortedKeys = append(sortedKeys, k) } sort.Strings(sortedKeys) return sortedKeys } // TagValues returns a map of unique tag values for the given measurements and key with the given filters applied. // Call .ToSlice() on the result to convert it into a sorted slice of strings. // Filters are equivalent to and AND operation. If you want to do an OR, get the tag values for one set, // then get the tag values for another set and do a union of the two. func (d *database) TagValues(names []string, key string, filters []*TagFilter) TagValues { values := TagValues(make(map[string]bool)) // see if they just want all the tag values for this key if len(filters) == 0 { for _, n := range names { idx := d.measurements[n] if idx != nil { values.Union(idx.tagValues(key)) } } return values } // they have filters so just get a set of series ids matching them and then get the tag values from those seriesIDs := d.SeriesIDs(names, filters) return d.tagValuesBySeries(key, seriesIDs) } // tagValuesBySeries will return a TagValues map of all the unique tag values for a collection of series. func (d *database) tagValuesBySeries(key string, seriesIDs SeriesIDs) TagValues { values := make(map[string]bool) for _, id := range seriesIDs { s := d.series[id] if s == nil { continue } if v, ok := s.Tags[key]; ok { values[v] = true } } return TagValues(values) } type TagValues map[string]bool // ToSlice returns a sorted slice of the TagValues func (t TagValues) ToSlice() []string { a := make([]string, 0, len(t)) for v, _ := range t { a = append(a, v) } sort.Strings(a) return a } // Union will modify the receiver by merging in the passed in values. func (l TagValues) Union(r TagValues) { for v, _ := range r { l[v] = true } } // Intersect will modify the receiver by keeping only the keys that exist in the passed in values func (l TagValues) Intersect(r TagValues) { for v, _ := range l { if _, ok := r[v]; !ok { delete(l, v) } } } //seriesIDsByName is the same as SeriesIDs, but for a specific measurement. func (d *database) seriesIDsByName(name string, filters []*TagFilter) SeriesIDs { idx := d.measurements[name] if idx == nil { return nil } // process the filters one at a time to get the list of ids they return idsPerFilter := make([]SeriesIDs, len(filters), len(filters)) for i, filter := range filters { idsPerFilter[i] = idx.seriesIDs(filter) } // collapse the set of ids allIDs := idsPerFilter[0] for i := 1; i < len(filters); i++ { allIDs = allIDs.Intersect(idsPerFilter[i]) } return allIDs } // MeasurementBySeriesID returns the Measurement that is the parent of the given series id. func (d *database) MeasurementBySeriesID(id uint32) *Measurement { if s, ok := d.series[id]; ok { return s.measurement } return nil } // MeasurementAndSeries returns the Measurement and the Series for a given measurement name and tag set. func (d *database) MeasurementAndSeries(name string, tags map[string]string) (*Measurement, *Series) { idx := d.measurements[name] if idx == nil { return nil, nil } return idx, idx.seriesByTags(tags) } // SereiesByID returns the Series that has the given id. func (d *database) SeriesByID(id uint32) *Series { return d.series[id] } // Measurements returns all measurements that match the given filters. func (d *database) Measurements(filters []*TagFilter) []*Measurement { measurements := make([]*Measurement, 0, len(d.measurements)) for _, idx := range d.measurements { measurements = append(measurements, idx.measurement) } return measurements } // Names returns all measurement names in sorted order. func (d *database) Names() []string { return d.names } // DropSeries will clear the index of all references to a series. func (d *database) DropSeries(id uint32) { panic("not implemented") } // DropMeasurement will clear the index of all references to a measurement and its child series. func (d *database) DropMeasurement(name string) { panic("not implemented") } // used to convert the tag set to bytes for use as a lookup key func marshalTags(tags map[string]string) []byte { s := make([]string, 0, len(tags)) // pull out keys to sort for k := range tags { s = append(s, k) } sort.Strings(s) // now append on the key values in key sorted order for _, k := range s { s = append(s, tags[k]) } return []byte(strings.Join(s, "|")) } // dbi is an interface the query engine uses to communicate with the database during planning. type dbi struct { server *Server db *database } // MatchSeries returns a list of series data ids matching a name and tags. func (dbi *dbi) MatchSeries(name string, tags map[string]string) (a []uint32) { // Find measurement by name. m := dbi.db.measurements[name] if m == nil { return nil } // Match each series on the measurement by tagset. // TODO: Use paul's fancy index. for _, s := range m.seriesByID { if s.match(tags) { a = append(a, s.ID) } } return } // SeriesTagValues returns a slice of tag values for a series. func (dbi *dbi) SeriesTagValues(seriesID uint32, keys []string) []string { // Find series by id. s := dbi.db.series[seriesID] // Lookup value for each key. values := make([]string, len(keys)) for i, key := range keys { values[i] = s.Tags[key] } return values } // Field returns the id and data type for a series field. // Returns id of zero if not a field. func (dbi *dbi) Field(name, field string) (fieldID uint8, typ influxql.DataType) { // Find measurement by name. m := dbi.db.measurements[name] if m == nil { return 0, influxql.Unknown } // Find field by name. f := m.FieldByName(field) if f == nil { return 0, influxql.Unknown } return f.ID, f.Type } // CreateIterator returns an iterator to iterate over the field values in a series. func (dbi *dbi) CreateIterator(seriesID uint32, fieldID uint8, typ influxql.DataType, min, max time.Time, interval time.Duration) influxql.Iterator { // TODO: Add retention policy to the arguments. // Create an iterator to hold the transaction and series ids. itr := &iterator{ seriesID: seriesID, fieldID: fieldID, typ: typ, imin: -1, interval: int64(interval), } if !min.IsZero() { itr.min = min.UnixNano() } if !max.IsZero() { itr.max = max.UnixNano() } // Retrieve the policy. // Ignore if there are no shard groups created on the retention policy. rp := dbi.db.policies[dbi.db.defaultRetentionPolicy] if len(rp.shardGroups) == 0 { return itr } // Find all shards which match the the time range and series id. // TODO: Support multiple groups. g := rp.shardGroups[0] // Ignore shard groups that our time range does not cross. if !timeBetweenInclusive(g.StartTime, min, max) && !timeBetweenInclusive(g.EndTime, min, max) { return itr } // Find appropriate shard by series id. sh := g.ShardBySeriesID(seriesID) // Open a transaction on the shard. tx, err := sh.store.Begin(false) assert(err == nil, "read-only tx error: %s", err) itr.tx = tx // Open and position cursor. b := tx.Bucket(u32tob(seriesID)) if b != nil { cur := b.Cursor() itr.k, itr.v = cur.Seek(u64tob(uint64(itr.min))) itr.cur = cur } return itr } // iterator represents a series data iterator for a shard. // It can iterate over all data for a given time range for multiple series in a shard. type iterator struct { tx *bolt.Tx cur *bolt.Cursor seriesID uint32 fieldID uint8 typ influxql.DataType k, v []byte // lookahead buffer min, max int64 // time range imin, imax int64 // interval time range interval int64 // interval duration } // close closes the iterator. func (i *iterator) Close() error { if i.tx != nil { return i.tx.Rollback() } return nil } // Next returns the next value from the iterator. func (i *iterator) Next() (key int64, value interface{}) { for { // Read raw key/value from lookhead buffer, if available. // Otherwise read from cursor. var k, v []byte if i.k != nil { k, v = i.k, i.v i.k, i.v = nil, nil } else if i.cur != nil { k, v = i.cur.Next() } // Exit at the end of the cursor. if k == nil { return 0, nil } // Extract timestamp & field value. key = int64(btou64(k)) value = unmarshalValue(v, i.fieldID) // If timestamp is beyond interval time range then push onto lookahead buffer. if key >= i.imax && i.imax != 0 { i.k, i.v = k, v return 0, nil } // Return value if it is non-nil. // Otherwise loop again and try the next point. if value != nil { return } } } // NextIterval moves to the next iterval. Returns true unless EOF. func (i *iterator) NextIterval() bool { // Determine the next interval's lower bound. imin := i.imin + i.interval // Initialize or move interval forward. if i.imin == -1 { // initialize first interval i.imin = i.min } else if i.interval != 0 && (i.max == 0 || imin < i.max) { // move forward i.imin = imin } else { // no interval or beyond max time. return false } // Interval end time should be the start time plus interval duration. // If the end time is beyond the iterator end time then shorten it. i.imax = i.imin + i.interval if max := i.max; i.imax > max { i.imax = max } return true } // Time returns start time of the current interval. func (i *iterator) Time() int64 { return i.imin } // Interval returns the group by duration. func (i *iterator) Interval() time.Duration { return time.Duration(i.interval) }
package main import ( "fmt" "math/big" "github.com/jackytck/projecteuler/tools" ) func count(limit int) int { var cnt int d := big.NewInt(3) n := big.NewInt(2) for i := 1; i < limit; i++ { p := big.NewInt(0) p.Set(n) n.Add(d, n) d.Add(n, p) if len(tools.DigitsBig(d)) > len(tools.DigitsBig(n)) { cnt++ } } return cnt } func main() { fmt.Println(count(1000)) } // In the first one-thousand expansions of square root of 2, // how many fractions contain a numerator with more digits than denominator?
package chapter3 import ( "net/http" "fmt" "html" "io/ioutil" ) func init() { fmt.Println("=== Web Operation ====") listen() } func listen() { resp, err := http.Get("http://www.google.com") if err != nil { panic(err) } defer resp.Body.Close() body, err := ioutil.ReadAll(resp.Body) fmt.Println(string(body)) /*http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request){ fmt.Fprintf(w, "Hello, %q", html.EscapeString(r.URL.Path)) })*/ http.HandleFunc("/",handler) http.ListenAndServe("localhost:8181", nil) } func handler(w http.ResponseWriter, r *http.Request){ fmt.Fprintf(w, "Hello, %q", html.EscapeString(r.URL.Path)) }
package persist_lib func AmazingUniarySelectQuery(tx Runable, req AmazingUniarySelectQueryParams) *Result { row := tx.QueryRow( "SELECT * from example_table Where id=$1 AND start_time>$2 ", req.GetId(), req.GetStartTime(), ) return newResultFromRow(row) } func AmazingUniarySelectWithHooksQuery(tx Runable, req AmazingUniarySelectWithHooksQueryParams) *Result { row := tx.QueryRow( "SELECT * from example_table Where id=$1 AND start_time>$2 ", req.GetId(), req.GetStartTime(), ) return newResultFromRow(row) } func AmazingServerStreamQuery(tx Runable, req AmazingServerStreamQueryParams) *Result { res, err := tx.Query( "SELECT * FROM example_table WHERE name=$1 ", req.GetName(), ) if err != nil { return newResultFromErr(err) } return newResultFromRows(res) } func AmazingServerStreamWithHooksQuery(tx Runable, req AmazingServerStreamWithHooksQueryParams) *Result { res, err := tx.Query( "SELECT * FROM example_table WHERE name=$1 ", req.GetName(), ) if err != nil { return newResultFromErr(err) } return newResultFromRows(res) } func AmazingBidirectionalQuery(tx Runable, req AmazingBidirectionalQueryParams) *Result { row := tx.QueryRow( "UPDATE example_table SET (start_time, name) = ($2, $3) WHERE id=$1 RETURNING * ", req.GetId(), req.GetStartTime(), req.GetName(), ) return newResultFromRow(row) } func AmazingBidirectionalWithHooksQuery(tx Runable, req AmazingBidirectionalWithHooksQueryParams) *Result { row := tx.QueryRow( "UPDATE example_table SET (start_time, name) = ($2, $3) WHERE id=$1 RETURNING * ", req.GetId(), req.GetStartTime(), req.GetName(), ) return newResultFromRow(row) } func AmazingClientStreamQuery(tx Runable, req AmazingClientStreamQueryParams) *Result { res, err := tx.Exec( "INSERT INTO example_table (id, start_time, name) VALUES ($1, $2, $3) ", req.GetId(), req.GetStartTime(), req.GetName(), ) if err != nil { return newResultFromErr(err) } return newResultFromSqlResult(res) } func AmazingClientStreamWithHookQuery(tx Runable, req AmazingClientStreamWithHookQueryParams) *Result { res, err := tx.Exec( "INSERT INTO example_table (id, start_time, name) VALUES ($1, $2, $3) ", req.GetId(), req.GetStartTime(), req.GetName(), ) if err != nil { return newResultFromErr(err) } return newResultFromSqlResult(res) } type AmazingUniarySelectQueryParams interface { GetId() int64 GetStartTime() interface{} } type AmazingUniarySelectWithHooksQueryParams interface { GetStartTime() interface{} GetId() int64 } type AmazingServerStreamQueryParams interface { GetName() string } type AmazingServerStreamWithHooksQueryParams interface { GetName() string } type AmazingBidirectionalQueryParams interface { GetId() int64 GetStartTime() interface{} GetName() string } type AmazingBidirectionalWithHooksQueryParams interface { GetStartTime() interface{} GetName() string GetId() int64 } type AmazingClientStreamQueryParams interface { GetStartTime() interface{} GetName() string GetId() int64 } type AmazingClientStreamWithHookQueryParams interface { GetId() int64 GetStartTime() interface{} GetName() string }
package main import ( "log" "net" "google.golang.org/grpc/reflection" "golang.org/x/net/context" pb "./public" "google.golang.org/grpc" data "./data" core "./core" "sort" "flag" ) var ( indexFile = flag.String("index", "", "the index cid file") dictFile = flag.String("dict", "", "the dict cid file") ) type ImiServiceImpl struct { index *core.Index dictionary *data.Dataset } type Docs []*pb.SearchDoc func (c Docs) Len() int { return len(c) } func (c Docs) Swap(i, j int) { c[i], c[j] = c[j], c[i] } func (c Docs) Less(i, j int) bool { return c[i].Score < c[j].Score } func (s *ImiServiceImpl) Search(ctx context.Context, in *pb.SearchRequest) (*pb.SearchResult, error) { log.Printf("search %s", in.Cid) out := make(chan int) defer close(out) id, ok := s.dictionary.Index[in.Cid] if !ok { return &pb.SearchResult{}, nil } p := s.dictionary.Points[id] go func() { s.index.Query(p, 2000, out) }() docs := []*pb.SearchDoc{} for { key := <- out if key == -1 { break } docs = append(docs, &pb.SearchDoc{s.index.D.Points[key].Id, p.L2(s.index.D.Points[key]), "", }) } sort.Sort(Docs(docs)) return &pb.SearchResult{docs, int32(len(docs)), }, nil } func main() { flag.Parse() lis, err := net.Listen("tcp", ":8999") if err != nil { log.Fatal("failed to listen: %v", err) } indexData, err := data.NewDatasetWithHeader(*indexFile, "cid", "col_") if err != nil { log.Fatalln("failed loading index") } index := core.NewIndex(indexData, 100, 100) log.Printf("Finish building index %d", index.D.Rows) dictionary, err := data.NewDatasetWithHeader(*dictFile, "cid", "col_") serviceImpl := &ImiServiceImpl{index, dictionary} s := grpc.NewServer() pb.RegisterIMIServer(s, serviceImpl) reflection.Register(s) log.Printf("start serving, port%s\n", ":8999") if err := s.Serve(lis); err != nil { log.Fatalf("failed to serve: %v", err) } }
package main import "fmt" //testType is test type type testType struct { a int b string } //String string func for print func (t *testType) String() string { return fmt.Sprint(t.a) + " " + t.b } func main() { //init testType t := &testType{77, "Sunset Strip"} //print testType fmt.Println(t) }
package minnow type ProcessorPool struct { processor Processor runRequestQueue chan RunRequest } func NewProcessorPool(processor Processor, poolSize int) *ProcessorPool { runRequestQueue := make(chan RunRequest, 100*poolSize) for i := 0; i < poolSize; i++ { go processor.Run(runRequestQueue) } return &ProcessorPool{processor, runRequestQueue} } func (pool *ProcessorPool) Run(runRequest RunRequest) { pool.runRequestQueue <- runRequest } func (pool *ProcessorPool) Stop() { close(pool.runRequestQueue) } func (pool *ProcessorPool) GetProcessorName() string { return pool.processor.GetName() } func (pool *ProcessorPool) GetProcessorId() ProcessorId { return pool.processor.GetId() } func (pool *ProcessorPool) ProcessorHookMatches(properties Properties) bool { return pool.processor.HookMatches(properties) }
// Copyright (c) 2018-2020 Double All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package captcha import ( "net/http" "strconv" "github.com/2637309949/bulrush" "github.com/gin-gonic/gin" "github.com/mojocn/base64Captcha" ) // Captcha provide Digit Captcha type Captcha struct { Period int Secret string Config base64Captcha.ConfigDigit URLPrefix string } // New defined return Captcha with default params func New() *Captcha { c := &Captcha{ URLPrefix: "/captcha", Secret: "123abc#@%", Period: 60, } c.Config = base64Captcha.ConfigDigit{ Height: 80, Width: 240, MaxSkew: 0.7, DotCount: 80, CaptchaLen: 5, } return c } // Init defined Captcha init func (c *Captcha) Init(init func(*Captcha)) *Captcha { init(c) return c } // Plugin for gin func (c *Captcha) Plugin(cfg *bulrush.Config, router *gin.RouterGroup, httpProxy *gin.Engine) { router.Use(func(ctx *gin.Context) { if data, err := ctx.Cookie("captcha"); err == nil && data != "" { decData := decrypt([]byte(data), c.Secret) dataStr := string(decData) ctx.Set("captcha", dataStr) } ctx.Next() }) router.GET(c.URLPrefix, func(ctx *gin.Context) { if height, err := strconv.Atoi(ctx.Query("height")); err != nil && height != 0 { c.Config.Height = height } if width, err := strconv.Atoi(ctx.Query("width")); err != nil && width != 0 { c.Config.Width = width } idKey, captcha := base64Captcha.GenerateCaptcha("", c.Config) encryptData := encrypt([]byte(idKey), c.Secret) base64 := base64Captcha.CaptchaWriteToBase64Encoding(captcha) ctx.SetCookie("captcha", string(encryptData), Some(c.Period, 60).(int), "/", "", false, false) ctx.String(http.StatusOK, base64) }) }
// Copyright (C) 2018 Storj Labs, Inc. // See LICENSE for copying information. package redis import ( "time" "github.com/gogo/protobuf/proto" "storj.io/storj/protos/overlay" ) const defaultNodeExpiration = 61 * time.Minute // OverlayClient is used to store overlay data in Redis type OverlayClient struct { DB Client } // NewOverlayClient returns a pointer to a new OverlayClient instance with an initalized connection to Redis. func NewOverlayClient(address, password string, db int) (*OverlayClient, error) { rc, err := NewRedisClient(address, password, db) if err != nil { return nil, err } return &OverlayClient{ DB: rc, }, nil } // Get looks up the provided nodeID from the redis cache func (o *OverlayClient) Get(key string) (*overlay.NodeAddress, error) { d, err := o.DB.Get(key) if err != nil { return nil, err } na := &overlay.NodeAddress{} return na, proto.Unmarshal(d, na) } // Set adds a nodeID to the redis cache with a binary representation of proto defined NodeAddress func (o *OverlayClient) Set(nodeID string, value overlay.NodeAddress) error { data, err := proto.Marshal(&value) if err != nil { return err } return o.DB.Set(nodeID, data, defaultNodeExpiration) }
package main import ( "basic-rabbitmq/RabbitMQ" "fmt" ) func main() { // Subscriber 02 rabbitmq := RabbitMQ.NewRabbitMQPubSub("newProduct") fmt.Println("Subscriber 02 start listening...") rabbitmq.RecieveSub() }
package tgo import ( "sync" ) var ( cacheConfigMux sync.Mutex cacheConfig *ConfigCache ) type ConfigCache struct { Redis ConfigCacheRedis RedisP ConfigCacheRedis // 持久化Redis Dynamic ConfigCacheDynamic } type ConfigCacheRedis struct { Address []string Prefix string Expire int ReadTimeout int WriteTimeout int ConnectTimeout int PoolMaxIdle int PoolMaxActive int PoolIdleTimeout int PoolMinActive int Password string } type ConfigCacheDynamic struct { DynamicAddress string IsDynamic bool CycleTime int } func configCacheGet() (err error) { if cacheConfig == nil || len(cacheConfig.Redis.Address) == 0 { cacheConfigMux.Lock() defer cacheConfigMux.Unlock() cacheConfig = new(ConfigCache) return configGet("cache", cacheConfig, nil) } return } func configCacheReload() { cacheConfigMux.Lock() defer cacheConfigMux.Unlock() cacheConfig = nil configCacheGet() } func ConfigCacheGetRedis() *ConfigCacheRedis { configCacheGet() if cacheConfig == nil { return new(ConfigCacheRedis) } return &cacheConfig.Redis } func ConfigCacheGetRedisWithConn(persistent bool) *ConfigCacheRedis { configCacheGet() var redisConfig ConfigCacheRedis if !persistent { redisConfig = cacheConfig.Redis } else { redisConfig = cacheConfig.RedisP } return &redisConfig } func ConfigCacheGetRedisDynamic() *ConfigCacheDynamic { configCacheGet() return &cacheConfig.Dynamic }
package rados /* #cgo LDFLAGS: -lrados #include "stdlib.h" #include "stdint.h" #include "rados/librados.h" #include "libradosext.h" */ import "C" import ( "time" "unsafe" ) // Sub-read operation. type SubReadOperation interface { resolve() Release() } // Stat read sub-operation. type StatReadOperation struct { size C.uint64_t mtime C.time_t rval C.int } func (s *StatReadOperation) Result() (stat *ObjectInfo, err error) { if s.rval < 0 { return nil, radosReturnCodeError(s.rval) } return &ObjectInfo{ Size: uint64(s.size), ModTime: time.Unix(int64(s.mtime), int64(0)), }, nil } func (s *StatReadOperation) resolve() { } func (s *StatReadOperation) Release() { } // Xattrs retrieval read sub-operation. type GetXattrsReadOperation struct { iter C.radosext_xattrs_iter_t rval C.int result map[string][]byte } func (s *GetXattrsReadOperation) resolve() { defer s.Release() if s.rval < 0 { return } s.result = make(map[string][]byte) for { var name, value *C.char var length C.size_t if C.radosext_getxattrs_next(s.iter, &name, &value, &length) < C.int(0) { break } if name == nil { break } s.result[C.GoString(name)] = C.GoBytes(unsafe.Pointer(value), C.int(length)) } } func (s *GetXattrsReadOperation) Release() { if s.iter != nil { C.radosext_getxattrs_end(s.iter) s.iter = nil } } func (s *GetXattrsReadOperation) Result() (map[string][]byte, error) { if s.rval < 0 { return nil, radosReturnCodeError(s.rval) } return s.result, nil } // Read at read sub-operation. type ReadAtReadOperation struct { buf C.radosext_buffer_t rval C.int result []byte } func (s *ReadAtReadOperation) resolve() { defer s.Release() if s.rval < 0 { return } s.result = C.GoBytes(unsafe.Pointer(C.radosext_buffer_data(s.buf)), C.int(C.radosext_buffer_length(s.buf))) } func (s *ReadAtReadOperation) Release() { if s.buf != nil { C.radosext_release_buffer(s.buf) s.buf = nil } } func (s *ReadAtReadOperation) Result() ([]byte, error) { if s.rval < 0 { return nil, radosReturnCodeError(s.rval) } return s.result, nil } // Object read operation. // // Grouping of operations to be executed atomically. type ReadOperation struct { op C.radosext_read_op_t sub []SubReadOperation } // Create new object read operation. func NewReadOperation() (o *ReadOperation, err error) { op := C.radosext_create_read_op() if op == nil { return nil, ErrNoMemory } return &ReadOperation{ op: op, sub: make([]SubReadOperation, 0), }, nil } // Release object read operation. func (o *ReadOperation) Release() { if o.op != nil { C.radosext_release_read_op(o.op) o.op = nil } if o.sub != nil { for _, s := range o.sub { s.Release() } o.sub = nil } } // Execute the object read operation. func (o *ReadOperation) ExecuteInContext(key string, ctx *Context) (err error) { if o.op == nil { return ErrAlreadyExecuted } ckey := C.CString(key) defer C.free(unsafe.Pointer(ckey)) cerr := C.radosext_read_op_operate(o.op, ctx.ctx, ckey) if cerr < 0 { err = radosReturnCodeError(cerr) } for _, s := range o.sub { s.resolve() } o.Release() return } // Stat an object. func (o *ReadOperation) Stat() (s *StatReadOperation, err error) { if o.op == nil { return nil, ErrAlreadyExecuted } s = &StatReadOperation{} C.radosext_read_op_stat(o.op, &s.size, &s.mtime, &s.rval) o.sub = append(o.sub, s) return } // Assert the value of an xattr. func (o *ReadOperation) AssertXattrEquals(name string, value []byte) error { if o.op == nil { return ErrAlreadyExecuted } cname := C.CString(name) defer C.free(unsafe.Pointer(cname)) cdata, cdatalen := byteSliceToBuffer(value) C.radosext_read_op_cmpxattr(o.op, cname, C.LIBRADOS_CMPXATTR_OP_EQ, cdata, cdatalen) return nil } // Get the xattrs. func (o *ReadOperation) GetXattrs() (s *GetXattrsReadOperation, err error) { if o.op == nil { return nil, ErrAlreadyExecuted } s = &GetXattrsReadOperation{} C.radosext_read_op_getxattrs(o.op, &s.iter, &s.rval) o.sub = append(o.sub, s) return } // Read data. func (o *ReadOperation) ReadAt(off uint64, size int) (s *ReadAtReadOperation, err error) { if o.op == nil { return nil, ErrAlreadyExecuted } s = &ReadAtReadOperation{} C.radosext_read_op_read(o.op, C.uint64_t(off), C.size_t(size), &s.buf, &s.rval) o.sub = append(o.sub, s) return }
package netgo import ( "fmt" "io" "io/ioutil" "log" "net/http" "os" "time" ) type Logger interface { Printf(string, ...interface{}) } // Client represents http client type Client struct { Inner *http.Client Logger Retry } // NewClient represents new http client func NewClient() *Client { return defaultClient } var defaultClient = &Client{ Inner: &http.Client{ Timeout: 30 * time.Second, Transport: defaultTransport, }, Logger: log.New(os.Stderr, "", log.LstdFlags), Retry: Retry{ WaitMin: 2 * time.Second, WaitMax: 8 * time.Second, Max: 4, }, } // Do sends an HTTP request and returns an HTTP response func (c *Client) Do(req *Request) (resp *http.Response, err error) { for i := 0; ; i++ { var code int if req.body != nil { body, err := req.body() if err != nil { return resp, err } if c, ok := body.(io.ReadCloser); ok { req.Body = c } else { req.Body = ioutil.NopCloser(body) } } resp, err = c.Inner.Do(req.Request) if resp != nil { code = resp.StatusCode } if err != nil { c.Logger.Printf("netter: %s request failed: %v", req.URL, err) } retryable, checkErr := c.Retry.isRetry(req.Context(), resp, err) if !retryable { if checkErr != nil { err = checkErr } return resp, err } remain := c.Retry.Max - i if remain <= 0 { break } if err == nil && resp != nil { c.drainBody(resp.Body) } wait := c.Retry.backoff(c.Retry.WaitMin, c.Retry.WaitMax, i) desc := fmt.Sprintf("%s (status: %d)", req.URL, code) c.Logger.Printf("netter: %s retrying in %s (%d left)", desc, wait, remain) select { case <-req.Context().Done(): return nil, req.Context().Err() case <-time.After(wait): } } if resp != nil { if err := resp.Body.Close(); err != nil { c.Logger.Printf(err.Error()) } } return nil, fmt.Errorf("netter: %s giving up after %d attempts", req.URL, c.Max+1) } func (c *Client) drainBody(body io.ReadCloser) { _, err := io.Copy(ioutil.Discard, io.LimitReader(body, 4096)) if err != nil { c.Logger.Printf("netter: reading response body: %v", err) } err = body.Close() if err != nil { c.Logger.Printf(err.Error()) } } // Get sends get request func Get(url string) (*http.Response, error) { return defaultClient.Get(url) } // Get sends get request func (c *Client) Get(url string) (*http.Response, error) { req, err := NewRequest("GET", url, nil) if err != nil { return nil, err } return c.Do(req) } // Post sends post request func Post(url, bodyType string, body interface{}) (*http.Response, error) { return defaultClient.Post(url, bodyType, body) } // Post sends post request func (c *Client) Post(url, bodyType string, body interface{}) (*http.Response, error) { req, err := NewRequest("POST", url, body) if err != nil { return nil, err } req.Header.Set("Content-Type", bodyType) return c.Do(req) }
/* Copyright 2021 The KubeVela Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package mongodb import ( "context" "math/rand" "strings" "time" "github.com/google/go-cmp/cmp" "github.com/google/go-cmp/cmp/cmpopts" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" "github.com/oam-dev/kubevela/pkg/apiserver/datastore" "github.com/oam-dev/kubevela/pkg/apiserver/model" ) var mongodbDriver datastore.DataStore var _ = BeforeSuite(func(done Done) { rand.Seed(time.Now().UnixNano()) By("bootstrapping mongodb test environment") var err error mongodbDriver, err = New(context.TODO(), datastore.Config{ URL: "mongodb://localhost:27017", Database: "kubevela", }) Expect(err).ToNot(HaveOccurred()) Expect(mongodbDriver).ToNot(BeNil()) mongodbDriver, err = New(context.TODO(), datastore.Config{ URL: "localhost:27017", Database: "kubevela", }) Expect(err).ToNot(HaveOccurred()) Expect(mongodbDriver).ToNot(BeNil()) By("create mongodb driver success") close(done) }, 120) var _ = Describe("Test mongodb datastore driver", func() { It("Test add function", func() { err := mongodbDriver.Add(context.TODO(), &model.Application{Name: "kubevela-app", Description: "default"}) Expect(err).ToNot(HaveOccurred()) }) It("Test batch add function", func() { var datas = []datastore.Entity{ &model.Application{Name: "kubevela-app-2", Description: "this is demo 2"}, &model.Application{Namespace: "test-namespace", Name: "kubevela-app-3", Description: "this is demo 3"}, &model.Application{Namespace: "test-namespace2", Name: "kubevela-app-4", Description: "this is demo 4"}, } err := mongodbDriver.BatchAdd(context.TODO(), datas) Expect(err).ToNot(HaveOccurred()) var datas2 = []datastore.Entity{ &model.Application{Namespace: "test-namespace", Name: "can-delete", Description: "this is demo can-delete"}, &model.Application{Name: "kubevela-app-2", Description: "this is demo 2"}, } err = mongodbDriver.BatchAdd(context.TODO(), datas2) equal := cmp.Diff(strings.Contains(err.Error(), "save components occur error"), true) Expect(equal).To(BeEmpty()) }) It("Test get function", func() { app := &model.Application{Name: "kubevela-app"} err := mongodbDriver.Get(context.TODO(), app) Expect(err).Should(BeNil()) diff := cmp.Diff(app.Description, "default") Expect(diff).Should(BeEmpty()) }) It("Test put function", func() { err := mongodbDriver.Put(context.TODO(), &model.Application{Name: "kubevela-app", Description: "this is demo"}) Expect(err).ToNot(HaveOccurred()) }) It("Test list function", func() { var app model.Application list, err := mongodbDriver.List(context.TODO(), &app, &datastore.ListOptions{Page: -1}) Expect(err).ShouldNot(HaveOccurred()) diff := cmp.Diff(len(list), 4) Expect(diff).Should(BeEmpty()) list, err = mongodbDriver.List(context.TODO(), &app, &datastore.ListOptions{Page: 2, PageSize: 2}) Expect(err).ShouldNot(HaveOccurred()) diff = cmp.Diff(len(list), 2) Expect(diff).Should(BeEmpty()) list, err = mongodbDriver.List(context.TODO(), &app, &datastore.ListOptions{Page: 1, PageSize: 2}) Expect(err).ShouldNot(HaveOccurred()) diff = cmp.Diff(len(list), 2) Expect(diff).Should(BeEmpty()) list, err = mongodbDriver.List(context.TODO(), &app, nil) Expect(err).ShouldNot(HaveOccurred()) diff = cmp.Diff(len(list), 4) Expect(diff).Should(BeEmpty()) app.Namespace = "test-namespace" list, err = mongodbDriver.List(context.TODO(), &app, nil) Expect(err).ShouldNot(HaveOccurred()) diff = cmp.Diff(len(list), 1) Expect(diff).Should(BeEmpty()) }) It("Test list clusters with sort and fuzzy query", func() { clusters, err := mongodbDriver.List(context.TODO(), &model.Cluster{}, nil) Expect(err).Should(Succeed()) for _, cluster := range clusters { Expect(mongodbDriver.Delete(context.TODO(), cluster)).Should(Succeed()) } for _, name := range []string{"first", "second", "third"} { Expect(mongodbDriver.Add(context.TODO(), &model.Cluster{Name: name})).Should(Succeed()) time.Sleep(time.Millisecond * 100) } entities, err := mongodbDriver.List(context.TODO(), &model.Cluster{}, &datastore.ListOptions{SortBy: []datastore.SortOption{{Key: "model.createTime", Order: datastore.SortOrderAscending}}}) Expect(err).Should(Succeed()) Expect(len(entities)).Should(Equal(3)) for i, name := range []string{"first", "second", "third"} { Expect(entities[i].(*model.Cluster).Name).Should(Equal(name)) } entities, err = mongodbDriver.List(context.TODO(), &model.Cluster{}, &datastore.ListOptions{ SortBy: []datastore.SortOption{{Key: "model.createTime", Order: datastore.SortOrderDescending}}, Page: 2, PageSize: 2, }) Expect(err).Should(Succeed()) Expect(len(entities)).Should(Equal(1)) for i, name := range []string{"first"} { Expect(entities[i].(*model.Cluster).Name).Should(Equal(name)) } entities, err = mongodbDriver.List(context.TODO(), &model.Cluster{}, &datastore.ListOptions{ SortBy: []datastore.SortOption{{Key: "model.createTime", Order: datastore.SortOrderDescending}}, FilterOptions: datastore.FilterOptions{ Queries: []datastore.FuzzyQueryOption{{Key: "name", Query: "ir"}}, }, }) Expect(err).Should(Succeed()) Expect(len(entities)).Should(Equal(2)) for i, name := range []string{"third", "first"} { Expect(entities[i].(*model.Cluster).Name).Should(Equal(name)) } }) It("Test count function", func() { var app model.Application count, err := mongodbDriver.Count(context.TODO(), &app, nil) Expect(err).ShouldNot(HaveOccurred()) Expect(count).Should(Equal(int64(4))) app.Namespace = "test-namespace" count, err = mongodbDriver.Count(context.TODO(), &app, nil) Expect(err).ShouldNot(HaveOccurred()) Expect(count).Should(Equal(int64(1))) count, err = mongodbDriver.Count(context.TODO(), &model.Cluster{}, &datastore.FilterOptions{ Queries: []datastore.FuzzyQueryOption{{Key: "name", Query: "ir"}}, }) Expect(err).Should(Succeed()) Expect(count).Should(Equal(int64(2))) }) It("Test isExist function", func() { var app model.Application app.Name = "kubevela-app-3" exist, err := mongodbDriver.IsExist(context.TODO(), &app) Expect(err).ShouldNot(HaveOccurred()) diff := cmp.Diff(exist, true) Expect(diff).Should(BeEmpty()) app.Name = "kubevela-app-5" notexist, err := mongodbDriver.IsExist(context.TODO(), &app) Expect(err).ShouldNot(HaveOccurred()) diff = cmp.Diff(notexist, false) Expect(diff).Should(BeEmpty()) }) It("Test delete function", func() { var app model.Application app.Name = "kubevela-app" err := mongodbDriver.Delete(context.TODO(), &app) Expect(err).ShouldNot(HaveOccurred()) app.Name = "kubevela-app-2" err = mongodbDriver.Delete(context.TODO(), &app) Expect(err).ShouldNot(HaveOccurred()) app.Name = "kubevela-app-3" err = mongodbDriver.Delete(context.TODO(), &app) Expect(err).ShouldNot(HaveOccurred()) app.Name = "kubevela-app-4" err = mongodbDriver.Delete(context.TODO(), &app) Expect(err).ShouldNot(HaveOccurred()) app.Name = "kubevela-app-4" err = mongodbDriver.Delete(context.TODO(), &app) equal := cmp.Equal(err, datastore.ErrRecordNotExist, cmpopts.EquateErrors()) Expect(equal).Should(BeTrue()) }) })
/* * @lc app=leetcode.cn id=237 lang=golang * * [237] 删除链表中的节点 */ // @lc code=start /** * Definition for singly-linked list. * type ListNode struct { * Val int * Next *ListNode * } */ package main import "fmt" type ListNode struct { Val int Next *ListNode } var head *ListNode func main() { l1 := &ListNode{Val: 1} l2 := &ListNode{Val: 2} l3 := &ListNode{Val: 6} l4 := &ListNode{Val: 3} l5 := &ListNode{Val: 4} l6 := &ListNode{Val: 5} l7 := &ListNode{Val: 6} l1.Next = l2 l2.Next = l3 l3.Next = l4 l4.Next = l5 l5.Next = l6 l6.Next = l7 head = l1 print(head) deleteNode(l1) print(head) } func print(head *ListNode){ cur := head for cur != nil { fmt.Printf("%d ", cur.Val) cur = cur.Next } fmt.Println() } func deleteNode(node *ListNode) { if head == nil { return } cur := head newHead := &ListNode{} prev := newHead for cur != nil { if cur == node { prev.Next = cur.Next cur = cur.Next } else { prev.Next = cur prev = cur cur = cur.Next } } head = newHead.Next return } // @lc code=end
// Package powervs extracts Power VS metadata from install configurations. package powervs import ( "context" icpowervs "github.com/openshift/installer/pkg/asset/installconfig/powervs" "github.com/openshift/installer/pkg/types" "github.com/openshift/installer/pkg/types/powervs" ) // Metadata converts an install configuration to PowerVS metadata. func Metadata(config *types.InstallConfig, meta *icpowervs.Metadata) *powervs.Metadata { cisCRN, _ := meta.CISInstanceCRN(context.TODO()) dnsCRN, _ := meta.DNSInstanceCRN(context.TODO()) return &powervs.Metadata{ BaseDomain: config.BaseDomain, PowerVSResourceGroup: config.Platform.PowerVS.PowerVSResourceGroup, CISInstanceCRN: cisCRN, DNSInstanceCRN: dnsCRN, Region: config.Platform.PowerVS.Region, VPCRegion: config.Platform.PowerVS.VPCRegion, Zone: config.Platform.PowerVS.Zone, ServiceInstanceGUID: config.Platform.PowerVS.ServiceInstanceID, } }
//////////////////////////////////////////////////////////////////////////////// // // // Copyright 2019 Broadcom. The term Broadcom refers to Broadcom Inc. and/or // // its subsidiaries. // // // // 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 db implements a wrapper over the go-redis/redis. */ package db import ( // "fmt" // "strconv" // "reflect" // "errors" // "strings" // "github.com/go-redis/redis/v7" "github.com/golang/glog" // "github.com/Azure/sonic-mgmt-common/cvl" "github.com/Azure/sonic-mgmt-common/translib/tlerr" ) func init() { } func (d *DB) GetMap(ts *TableSpec, mapKey string) (string, error) { if glog.V(3) { glog.Info("GetMap: Begin: ", "ts: ", ts, " mapKey: ", mapKey) } v, e := d.client.HGet(ts.Name, mapKey).Result() if glog.V(3) { glog.Info("GetMap: End: ", "v: ", v, " e: ", e) } return v, e } func (d *DB) GetMapAll(ts *TableSpec) (Value, error) { if glog.V(3) { glog.Info("GetMapAll: Begin: ", "ts: ", ts) } var value Value v, e := d.client.HGetAll(ts.Name).Result() if len(v) != 0 { value = Value{Field: v} } else { if glog.V(1) { glog.Info("GetMapAll: HGetAll(): empty map") } e = tlerr.TranslibRedisClientEntryNotExist { Entry: ts.Name } } if glog.V(3) { glog.Info("GetMapAll: End: ", "value: ", value, " e: ", e) } return value, e } // For Testing only. Do Not Use!!! ============================== // SetMap - There is no transaction support on these. func (d *DB) SetMap(ts *TableSpec, mapKey string, mapValue string) error { if glog.V(3) { glog.Info("SetMap: Begin: ", "ts: ", ts, " ", mapKey, ":", mapValue) } b, e := d.client.HSet(ts.Name, mapKey, mapValue).Result() if glog.V(3) { glog.Info("GetMap: End: ", "b: ", b, " e: ", e) } return e } // For Testing only. Do Not Use!!! ============================== // DeleteMapAll - There is no transaction support on these. func (d *DB) DeleteMapAll(ts *TableSpec) error { if glog.V(3) { glog.Info("DeleteMapAll: Begin: ", "ts: ", ts) } e := d.client.Del(ts.Name).Err() if glog.V(3) { glog.Info("DeleteMapAll: End: ", " e: ", e) } return e } // For Testing only. Do Not Use!!! ==============================
package nginxClient import ( "fmt" "io/ioutil" "net/http" "strconv" "strings" ) // NginxClient allows you to fetch NGINX metrics from the stub_status page. type NginxClient struct { apiEndpoint string httpClient *http.Client } // StubStats represents NGINX stub_status metrics. type StubStats struct { Connections StubConnections Requests int64 } // StubConnections represents connections related metrics. type StubConnections struct { Active int64 Accepted int64 Handled int64 Reading int64 Writing int64 Waiting int64 } // NewNginxClient creates an NginxClient. func NewNginxClient(httpClient *http.Client, apiEndpoint string) (*NginxClient, error) { client := &NginxClient{ apiEndpoint: apiEndpoint, httpClient: httpClient, } if _, err := client.GetStubStats(); err != nil { return nil, fmt.Errorf("Failed to create NginxClient: %v", err) } return client, nil } // GetStubStats fetches the stub_status metrics. func (client *NginxClient) GetStubStats() (*StubStats, error) { resp, err := client.httpClient.Get(client.apiEndpoint) if err != nil { return nil, fmt.Errorf("failed to get %v: %v", client.apiEndpoint, err) } defer resp.Body.Close() if resp.StatusCode != http.StatusOK { return nil, fmt.Errorf("expected %v response, got %v", http.StatusOK, resp.StatusCode) } body, err := ioutil.ReadAll(resp.Body) if err != nil { return nil, fmt.Errorf("failed to read the response body: %v", err) } var stats StubStats err = parseStubStats(body, &stats) if err != nil { return nil, fmt.Errorf("failed to parse response body %q: %v", string(body), err) } return &stats, nil } func parseStubStats(data []byte, stats *StubStats) error { dataStr := string(data) parts := strings.Split(dataStr, "\n") if len(parts) != 5 { return fmt.Errorf("invalid input %q", dataStr) } activeConsParts := strings.Split(strings.TrimSpace(parts[0]), " ") if len(activeConsParts) != 3 { return fmt.Errorf("invalid input for active connections %q", parts[0]) } actCons, err := strconv.ParseInt(activeConsParts[2], 10, 64) if err != nil { return fmt.Errorf("invalid input for active connections %q: %v", activeConsParts[2], err) } stats.Connections.Active = actCons miscParts := strings.Split(strings.TrimSpace(parts[2]), " ") if len(miscParts) != 3 { return fmt.Errorf("invalid input for connections and requests %q", parts[2]) } acceptedCons, err := strconv.ParseInt(miscParts[0], 10, 64) if err != nil { return fmt.Errorf("invalid input for accepted connections %q: %v", miscParts[0], err) } stats.Connections.Accepted = acceptedCons handledCons, err := strconv.ParseInt(miscParts[1], 10, 64) if err != nil { return fmt.Errorf("invalid input for handled connections %q: %v", miscParts[1], err) } stats.Connections.Handled = handledCons requests, err := strconv.ParseInt(miscParts[2], 10, 64) if err != nil { return fmt.Errorf("invalid input for requests %q: %v", miscParts[2], err) } stats.Requests = requests consParts := strings.Split(strings.TrimSpace(parts[3]), " ") if len(consParts) != 6 { return fmt.Errorf("invalid input for connections %q", parts[3]) } readingCons, err := strconv.ParseInt(consParts[1], 10, 64) if err != nil { return fmt.Errorf("invalid input for reading connections %q: %v", consParts[1], err) } stats.Connections.Reading = readingCons writingCons, err := strconv.ParseInt(consParts[3], 10, 64) if err != nil { return fmt.Errorf("invalid input for writing connections %q: %v", consParts[3], err) } stats.Connections.Writing = writingCons waitingCons, err := strconv.ParseInt(consParts[5], 10, 64) if err != nil { return fmt.Errorf("invalid input for waiting connections %q: %v", consParts[5], err) } stats.Connections.Waiting = waitingCons return nil }
package config import ( "testing" ) func TestIniFile(t *testing.T) { iniconf, err := NewConfig(IniProtocol, "config.ini") if err != nil { t.Fatal(err) } if name := iniconf.GetString("server.name"); name != "testserver" { t.Errorf("server.name = %s", name) } if name := iniconf.GetString("server.namedef", "testserver"); name != "testserver" { t.Errorf("server.namedef = %s", name) } if platform := iniconf.GetStrings("server.platform"); len(platform) != 2 { t.Errorf("server.platform = %q", platform) } if platform := iniconf.GetStrings("server.platformdef", "ios,android"); len(platform) != 2 { t.Errorf("server.platformdef = %q", platform) } if b, _ := iniconf.GetBool("server.enablessl"); !b { t.Errorf("server.enablessl = %t", b) } if b, _ := iniconf.GetBool("server.enablessldef", true); !b { t.Errorf("server.enablessldef = %t", b) } if port, _ := iniconf.GetInt("server.port"); port != 8080 { t.Errorf("server.port = %d", port) } if port, _ := iniconf.GetInt("server.portdef", 80); port != 80 { t.Errorf("server.port = %d", port) } if pi, _ := iniconf.GetFloat("server.PI"); pi != 3.14 { t.Errorf("server.port = %d", pi) } if pi, _ := iniconf.GetFloat("server.PIdef", 3.141); pi != 3.141 { t.Errorf("server.port = %d", pi) } } var iniTestData = `[server] name = testserver platform = android,ios port = 8080 enablessl = true PI = 3.14` func TestIniData(t *testing.T) { iniconf, err := NewConfigData(IniProtocol, []byte(iniTestData)) if err != nil { t.Fatal(err) } if name := iniconf.GetString("server.name"); name != "testserver" { t.Errorf("server.name = %s", name) } if name := iniconf.GetString("server.namedef", "testserver"); name != "testserver" { t.Errorf("server.namedef = %s", name) } if platform := iniconf.GetStrings("server.platform"); len(platform) != 2 { t.Errorf("server.platform = %q", platform) } if platform := iniconf.GetStrings("server.platformdef", "ios,android"); len(platform) != 2 { t.Errorf("server.platformdef = %q", platform) } if b, _ := iniconf.GetBool("server.enablessl"); !b { t.Errorf("server.enablessl = %t", b) } if b, _ := iniconf.GetBool("server.enablessldef", true); !b { t.Errorf("server.enablessldef = %t", b) } if port, _ := iniconf.GetInt("server.port"); port != 8080 { t.Errorf("server.port = %d", port) } if port, _ := iniconf.GetInt("server.portdef", 80); port != 80 { t.Errorf("server.port = %d", port) } if pi, _ := iniconf.GetFloat("server.PI"); pi != 3.14 { t.Errorf("server.port = %d", pi) } if pi, _ := iniconf.GetFloat("server.PIdef", 3.141); pi != 3.141 { t.Errorf("server.port = %d", pi) } }
package main import ( "context" "fmt" "io" "log" "os" "github.com/docker/docker/api/types" "github.com/docker/docker/api/types/container" docker "github.com/docker/docker/client" dotenv "github.com/joho/godotenv" amqp "github.com/streadway/amqp" ) // LogPublisher A io.Writer implementation to write data to a Publisher channel. type LogPublisher struct { Channel *amqp.Channel Repository string } func (publisher *LogPublisher) Write(data []byte) (length int, error error) { error = publisher.Channel.Publish("statikk.build.logs", "build-logs", false, false, amqp.Publishing{ Body: data, Headers: amqp.Table{ "repository": publisher.Repository, }, }) return len(data), error } // Consumer a AQMP consumer type Consumer struct { Connection *amqp.Connection Channel *amqp.Channel PublishChannel *amqp.Channel Tag string Done chan error } // NewConsumer Creates a new AQMP consumer func NewConsumer(amqpURL string, consumerTag string) error { consumer := &Consumer{ Connection: nil, Channel: nil, Tag: consumerTag, } var error error log.Printf("Connecting to the RabbitMQ server...\n") consumer.Connection, error = amqp.Dial(amqpURL) if error != nil { return fmt.Errorf("Errored while trying to connect to the RabbitMQ server: %s", error) } log.Printf("Successfully connected to RabbitMQ server.\n") log.Printf("Creating channel connection...\n") consumer.Channel, error = consumer.Connection.Channel() if error != nil { return fmt.Errorf("Errored while creating a channel for consumer %s: %s", consumerTag, error) } log.Printf("Channel connection has been succesfully done.\n") log.Printf("Creating publisher channel connection...\n") consumer.PublishChannel, error = consumer.Connection.Channel() if error != nil { return fmt.Errorf("Errored while creating a channel for publisher %s: %s", consumerTag, error) } log.Printf("Publsher channel connection has been succesfully done.\n") log.Printf("Declaring `builds` queue exchange...\n") buildQueue, error := consumer.Channel.QueueDeclare("builds", true, false, false, true, nil) if error != nil { return fmt.Errorf("Errored while declaring `builds` queue: %s", error) } log.Printf("The queue `%s` has been declared!\n", buildQueue.Name) log.Printf("Declaring `build-logs` exchange for logs...\n") exchangeError := consumer.Channel.ExchangeDeclare("statikk.build.logs", "fanout", true, false, false, true, nil) if exchangeError != nil { return fmt.Errorf("Errored while declaring fanout exchange for `statikk.build.logs`: %s", error) } log.Printf("Connecting to `%s` queue.\n", buildQueue.Name) deliveries, error := consumer.Channel.Consume(buildQueue.Name, consumer.Tag, true, false, true, true, nil) if error != nil { return fmt.Errorf("Errored while trying consume messages from the `%s` queue: %s", buildQueue.Name, error) } log.Printf("Ready.") go HandleDelivery(consumer, deliveries) for consumer.Connection.IsClosed() != true { } log.Fatal("Connection closed.") return nil } var dockerClient *docker.Client // HandleCreateContainer internal for handling build `start` messages. func HandleCreateContainer(channel *amqp.Channel, repository string, repositoryID string) { log.Printf("Build started for %s.\n", repositoryID) context := context.Background() container, error := dockerClient.ContainerCreate(context, &container.Config{ Image: "statikk:builder", Env: []string{"REPOSITORY=" + repository}, }, nil, nil, repositoryID) if error != nil { log.Printf("Cannot create container %s: %s\n", repositoryID, error.Error()) return } if error := dockerClient.ContainerStart(context, container.ID, types.ContainerStartOptions{}); error != nil { log.Printf("Cannot start container %s: %s\n", container.ID, error.Error()) return } logs, error := dockerClient.ContainerLogs(context, repositoryID, types.ContainerLogsOptions{ ShowStdout: true, ShowStderr: true, Follow: true, Timestamps: true, }) if error != nil { log.Printf("Cannot get logs of container %s: %s\n", repositoryID, error) return } logPublisher := LogPublisher{ Channel: channel, Repository: repositoryID, } if _, error := io.Copy(&logPublisher, logs); error != nil { log.Printf("Cannot publish log output of %s: %s\n", repositoryID, error.Error()) return } } // HandleStopContainer internal for handling build `stop` messages func HandleStopContainer(repositoryID string) { log.Printf("Stopping build for %s.\n", repositoryID) context := context.Background() error := dockerClient.ContainerRemove(context, repositoryID, types.ContainerRemoveOptions{ Force: true, }) if error != nil { log.Printf("Cannot remove container %s: %s\n", repositoryID, error.Error()) } else { log.Printf("Build stoped for %s.\n", repositoryID) } } // HandleDelivery internal for handling `builds` queue messages func HandleDelivery(consumer *Consumer, deliveries <-chan amqp.Delivery) { for delivery := range deliveries { action := delivery.Headers["action"].(string) repository := delivery.Headers["repository"] repositoryID := delivery.Headers["repository-id"] switch action { case "start": if repository != nil && repositoryID != nil { go HandleCreateContainer(consumer.PublishChannel, repository.(string), repositoryID.(string)) } else { log.Printf("Cannot start build: The field `repository` or `repository-id` is missing from message headers.") } case "stop": if repositoryID != nil { go HandleStopContainer(repositoryID.(string)) } else { log.Printf("Cannot stop build: The field `repository-id` is missing from message headers.") } } } log.Printf("Deliveries channel closed.") consumer.Done <- nil } func main() { // .env if error := dotenv.Load(); error != nil { panic(error) } // Docker dockerClientConnection, error := docker.NewEnvClient() if error != nil { panic(fmt.Errorf("Cannot connect to Docker")) } dockerClient = dockerClientConnection // RabbitMQ if error := NewConsumer(os.Getenv("AQMP_CONNECTION_URL"), "build-server"); error != nil { panic(error) } }
package csrf import ( "errors" "net/textproto" "strings" "time" "github.com/gofiber/fiber/v2" ) // New creates a new middleware handler func New(config ...Config) fiber.Handler { // Set default config cfg := configDefault(config...) // Create manager to simplify storage operations ( see manager.go ) manager := newManager(cfg.Storage) // Generate the correct extractor to get the token from the correct location selectors := strings.Split(cfg.KeyLookup, ":") if len(selectors) != 2 { panic("[CSRF] KeyLookup must in the form of <source>:<key>") } // By default we extract from a header extractor := csrfFromHeader(textproto.CanonicalMIMEHeaderKey(selectors[1])) switch selectors[0] { case "form": extractor = csrfFromForm(selectors[1]) case "query": extractor = csrfFromQuery(selectors[1]) case "param": extractor = csrfFromParam(selectors[1]) case "cookie": extractor = csrfFromCookie(selectors[1]) } dummyValue := []byte{'+'} // Return new handler return func(c *fiber.Ctx) (err error) { // Don't execute middleware if Next returns true if cfg.Next != nil && cfg.Next(c) { return c.Next() } var token string // Action depends on the HTTP method switch c.Method() { case fiber.MethodGet: // Declare empty token and try to get existing CSRF from cookie token = c.Cookies(cfg.CookieName) // Generate CSRF token if not exist if token == "" { // Generate new CSRF token token = cfg.KeyGenerator() // Add token to Storage manager.setRaw(token, dummyValue, cfg.Expiration) } // Create cookie to pass token to client cookie := &fiber.Cookie{ Name: cfg.CookieName, Value: token, Domain: cfg.CookieDomain, Path: cfg.CookiePath, Expires: time.Now().Add(cfg.Expiration), Secure: cfg.CookieSecure, HTTPOnly: cfg.CookieHTTPOnly, SameSite: cfg.CookieSameSite, } // Set cookie to response c.Cookie(cookie) case fiber.MethodPost, fiber.MethodDelete, fiber.MethodPatch, fiber.MethodPut: // Extract token from client request i.e. header, query, param, form or cookie token, err = extractor(c) if err != nil { return fiber.ErrForbidden } // 403 if token does not exist in Storage if manager.getRaw(token) == nil { // Expire cookie c.Cookie(&fiber.Cookie{ Name: cfg.CookieName, Domain: cfg.CookieDomain, Path: cfg.CookiePath, Expires: time.Now().Add(-1 * time.Minute), Secure: cfg.CookieSecure, HTTPOnly: cfg.CookieHTTPOnly, SameSite: cfg.CookieSameSite, }) // Return 403 Forbidden return fiber.ErrForbidden } // The token is validated, time to delete it manager.delete(token) } // Protect clients from caching the response by telling the browser // a new header value is generated c.Vary(fiber.HeaderCookie) // Store token in context if set if cfg.ContextKey != "" { c.Locals(cfg.ContextKey, token) } // Continue stack return c.Next() } } var ( errMissingHeader = errors.New("missing csrf token in header") errMissingQuery = errors.New("missing csrf token in query") errMissingParam = errors.New("missing csrf token in param") errMissingForm = errors.New("missing csrf token in form") errMissingCookie = errors.New("missing csrf token in cookie") ) // csrfFromHeader returns a function that extracts token from the request header. func csrfFromHeader(param string) func(c *fiber.Ctx) (string, error) { return func(c *fiber.Ctx) (string, error) { token := c.Get(param) if token == "" { return "", errMissingHeader } return token, nil } } // csrfFromQuery returns a function that extracts token from the query string. func csrfFromQuery(param string) func(c *fiber.Ctx) (string, error) { return func(c *fiber.Ctx) (string, error) { token := c.Query(param) if token == "" { return "", errMissingQuery } return token, nil } } // csrfFromParam returns a function that extracts token from the url param string. func csrfFromParam(param string) func(c *fiber.Ctx) (string, error) { return func(c *fiber.Ctx) (string, error) { token := c.Params(param) if token == "" { return "", errMissingParam } return token, nil } } // csrfFromForm returns a function that extracts a token from a multipart-form. func csrfFromForm(param string) func(c *fiber.Ctx) (string, error) { return func(c *fiber.Ctx) (string, error) { token := c.FormValue(param) if token == "" { return "", errMissingForm } return token, nil } } // csrfFromCookie returns a function that extracts token from the cookie header. func csrfFromCookie(param string) func(c *fiber.Ctx) (string, error) { return func(c *fiber.Ctx) (string, error) { token := c.Cookies(param) if token == "" { return "", errMissingCookie } return token, nil } }
package Home import ( "encoding/json" "fmt" "github.com/gin-gonic/gin" "net/http" "webchat/Controller/Base" ) type IndexController struct { this Base.BaseController } /** 当前登录用户列表 */ type userList struct { Code int `json:"code"` Msg string `json:"msg"` Data userData `json:"data"` } /** 用户信息 */ type userData struct { Mine userMine `json:"mine"` Friend []UserFried `json:"friend"` Group []GroupList `json:"group"` } /** 登录用户详情 */ type userMine struct { Username string `json:"username"` ID int `json:"id"` Status string `json:"status"` Sign string `json:"sign"` Avatar string `json:"avatar"` //图片地址 } /** 所属朋友 */ type UserFried struct { Groupname string `json:"groupname"` ID int `json:"id"` Online int `json:"online"` List []FriedList `json:"list"` } /** 朋友详情 */ type FriedList struct { Username string `json:"username"` ID int `json:"id"` Avatar string `json:"avatar"` Sign string `json:"sign"` } /** 分组列表 */ type GroupList struct { Groupname string `json:"groupname"` ID int `json:"id"` Avatar string `json:"avatar"` } func (this *IndexController) chatIndex() { fmt.Print("哈哈哈") } func ChatIndex(c *gin.Context) { fmt.Print("我被请求到了") c.HTML(http.StatusOK, "index.html", gin.H{ "title": "Main website", }) } func UseList(c *gin.Context) { var data userList //信息 //临时模拟 var mine userMine mine.Username = "纸飞机" mine.ID = 1000 mine.Status = "online" mine.Sign = "在深邃的编码世界,做一枚轻盈的纸飞机" mine.Avatar = "http://cdn.firstlinkapp.com/upload/2016_6/1465575923433_33812.jpg" var flist []FriedList flist = make([]FriedList,1) flist[0].ID = 100001 flist[0].Username = "贤心" flist[0].Avatar = "http://tp1.sinaimg.cn/1571889140/180/40030060651/1" flist[0].Sign = "这些都是测试数据,实际使用请严格按照该格式返回" var grouplist []GroupList grouplist = make([]GroupList,2) grouplist[0].Avatar = "前端群" grouplist[0].ID = 101 grouplist[0].Avatar = "http://tp2.sinaimg.cn/2211874245/180/40050524279/0" grouplist[1].Avatar = "Fly社区官方群" grouplist[1].ID = 102 grouplist[1].Avatar = "http://tp2.sinaimg.cn/5488749285/50/5719808192/1" var friend []UserFried friend = make([]UserFried,1) friend[0].ID = 2000 friend[0].Groupname = "前端码屌" friend[0].Online = 2 friend[0].List = flist var userInfo userData userInfo.Group = grouplist userInfo.Friend = friend userInfo.Mine = mine data.Code = 0 data.Data = userInfo data.Msg = "获取成功" a,_ := json.Marshal(data) fmt.Print(string(a)) c.JSON(200,data) } func UserMembers(c *gin.Context) { var data string = `{ "code": 0 ,"msg": "" ,"data": { "owner": { "username": "贤心" ,"id": "100001" ,"avatar": "http://tp1.sinaimg.cn/1571889140/180/40030060651/1" ,"sign": "这些都是测试数据,实际使用请严格按照该格式返回" } ,"members": 12 ,"list": [{ "username": "贤心" ,"id": "100001" ,"avatar": "http://tp1.sinaimg.cn/1571889140/180/40030060651/1" ,"sign": "这些都是测试数据,实际使用请严格按照该格式返回" },{ "username": "Z_子晴" ,"id": "108101" ,"avatar": "http://tva3.sinaimg.cn/crop.0.0.512.512.180/8693225ajw8f2rt20ptykj20e80e8weu.jpg" ,"sign": "微电商达人" },{ "username": "Lemon_CC" ,"id": "102101" ,"avatar": "http://tp2.sinaimg.cn/1833062053/180/5643591594/0" ,"sign": "" },{ "username": "马小云" ,"id": "168168" ,"avatar": "http://tp4.sinaimg.cn/2145291155/180/5601307179/1" ,"sign": "让天下没有难写的代码" },{ "username": "徐小峥" ,"id": "666666" ,"avatar": "http://tp2.sinaimg.cn/1783286485/180/5677568891/1" ,"sign": "代码在囧途,也要写到底" },{ "username": "罗玉凤" ,"id": "121286" ,"avatar": "http://tp1.sinaimg.cn/1241679004/180/5743814375/0" ,"sign": "在自己实力不济的时候,不要去相信什么媒体和记者。他们不是善良的人,有时候候他们的采访对当事人而言就是陷阱" },{ "username": "长泽梓Azusa" ,"id": "100001222" ,"avatar": "http://tva1.sinaimg.cn/crop.0.0.180.180.180/86b15b6cjw1e8qgp5bmzyj2050050aa8.jpg" ,"sign": "我是日本女艺人长泽あずさ" },{ "username": "大鱼_MsYuyu" ,"id": "12123454" ,"avatar": "http://tp1.sinaimg.cn/5286730964/50/5745125631/0" ,"sign": "我瘋了!這也太準了吧 超級笑點低" },{ "username": "谢楠" ,"id": "10034001" ,"avatar": "http://tp4.sinaimg.cn/1665074831/180/5617130952/0" ,"sign": "" },{ "username": "柏雪近在它香" ,"id": "3435343" ,"avatar": "http://tp2.sinaimg.cn/2518326245/180/5636099025/0" ,"sign": "" },{ "username": "林心如" ,"id": "76543" ,"avatar": "http://tp3.sinaimg.cn/1223762662/180/5741707953/0" ,"sign": "我爱贤心" },{ "username": "佟丽娅" ,"id": "4803920" ,"avatar": "http://tp4.sinaimg.cn/1345566427/180/5730976522/0" ,"sign": "我也爱贤心吖吖啊" }] } }` c.JSON(200,data) }
package main // 坐标结构体 type Node struct { x, y int } var dx []int // x变化向量 var dy []int // y变化向量 var hasBeenHandled map[int]bool // 用于记录节点是否被处理过 // BFS调用者 func updateMatrix(matrix [][]int) [][]int { if len(matrix) == 0 { return matrix } hasBeenHandled = make(map[int]bool) /* 1. 确定搜索方向dx、dy */ dx = []int{0, 0, -1, 1} dy = []int{1, -1, 0, 0} /* 2. 将需要进行BFS的坐标入队 */ m, n := len(matrix), len(matrix[0]) queue := make([]Node, 0, m*n) // 由于go语言没有队列,这里采用切片模拟队列 for i := 0; i < m; i++ { for t := 0; t < n; t++ { if matrix[i][t] == 0 { queue = append(queue, Node{i, t}) } } } /* 3. 执行BFS */ BFS(matrix, queue) return matrix } // BFS func BFS(matrix [][]int, queue []Node) { level := 0 for len(queue) != 0 { size := len(queue) for size != 0 { size -- top := queue[0] queue = queue[1:] hashNumber := hash(top.x, top.y) // 这里采用哈希,把二维坐标哈希为一个数字 /* 4. 判断进行BFS的坐标是否符合要求 */ if top.x < 0 || top.y < 0 || top.x >= len(matrix) || top.y >= len(matrix[top.x]) || hasBeenHandled[hashNumber] { // 不满足要求时 continue } /* 5. 对坐标进行标记,防止走回头路 */ hasBeenHandled[hashNumber] = true matrix[top.x][top.y] = level /* 6.遍历所有方向 */ for i := 0; i < len(dx); i++ { /* 7. 将下一个坐标入队 */ nx, ny := top.x+dx[i], top.y+dy[i] queue = append(queue, Node{nx, ny}) } } level++ } } func hash(x, y int) int { return (x << 20) | y } /* 题目链接: https://leetcode-cn.com/problems/01-matrix/ 01矩阵 */ /* 总结 1. 这题就是求1位于的层数,我们可以以0为第0层,之后每一层每一层的拓展,采用BFS的思路。 */
package generate const LINKER_TEMPLATE = `package no.fint.consumer.models.{{ modelPkg .Package }}{{ ToLower .Name }}; import {{ resourcePkg .Package }}.{{ .Name }}Resource; import {{ resourcePkg .Package }}.{{ .Name }}Resources; import no.fint.relations.FintLinker; import org.springframework.stereotype.Component; import java.util.Collection; import java.util.stream.IntStream; import java.util.stream.Stream; import static java.util.Objects.isNull; import static org.springframework.util.StringUtils.isEmpty; @Component public class {{ .Name }}Linker extends FintLinker<{{ .Name }}Resource> { public {{ .Name }}Linker() { super({{ .Name }}Resource.class); } public void mapLinks({{.Name}}Resource resource) { super.mapLinks(resource); } @Override public {{ .Name }}Resources toResources(Collection<{{ .Name }}Resource> collection) { return toResources(collection.stream(), 0, 0, collection.size()); } @Override public {{ .Name }}Resources toResources(Stream<{{ .Name }}Resource> stream, int offset, int size, int totalItems) { {{ .Name }}Resources resources = new {{ .Name }}Resources(); stream.map(this::toResource).forEach(resources::addResource); addPagination(resources, offset, size, totalItems); return resources; } @Override public String getSelfHref({{ $.Name }}Resource {{ ToLower $.Name }}) { return getAllSelfHrefs({{ ToLower $.Name }}).findFirst().orElse(null); } @Override public Stream<String> getAllSelfHrefs({{ $.Name }}Resource {{ ToLower $.Name }}) { Stream.Builder<String> builder = Stream.builder(); {{ range $i, $ident := .Identifiers -}} if (!isNull({{ ToLower $.Name }}.get{{ ToTitle $ident.Name }}()) && !isEmpty({{ ToLower $.Name }}.get{{ ToTitle $ident.Name }}().getIdentifikatorverdi())) { builder.add(createHrefWithId({{ ToLower $.Name }}.get{{ ToTitle $ident.Name }}().getIdentifikatorverdi(), "{{ ToLower $ident.Name }}")); } {{ end }} return builder.build(); } int[] hashCodes({{ $.Name }}Resource {{ ToLower $.Name }}) { IntStream.Builder builder = IntStream.builder(); {{ range $i, $ident := .Identifiers -}} if (!isNull({{ ToLower $.Name }}.get{{ ToTitle $ident.Name }}()) && !isEmpty({{ ToLower $.Name }}.get{{ ToTitle $ident.Name }}().getIdentifikatorverdi())) { builder.add({{ ToLower $.Name }}.get{{ ToTitle $ident.Name }}().getIdentifikatorverdi().hashCode()); } {{ end }} return builder.build().toArray(); } } `
// Package conf provides all functionality required for parsing and accessing // configuration files. // You can use a hjson/json/env files as configurations and access them recursively // with dots package conf import ( "flag" "fmt" "github.com/hjson/hjson-go" "github.com/joho/godotenv" "io/ioutil" "os" "path/filepath" "reflect" "strconv" "strings" "math" ) // New creates a new config parser with config files at path configDir. // Argument envDir can be an empty string which will cause the function to ignore .env parsing // Config files with extensions .hjson and .json will be opened at this point and all files will be parsed // resulting in a fast access time // If there are any Evaluation needed those will be applied when accessing variables // All folders inside configDir will recursively scanned for .hjson and .json files and // any config will be accessible by its relative path connected with dots // An error may happen during reading files like access denied // if the error causes func New(configDir string, envDir string, evalFunctions []EvaluatorFunction) (config *Config, err error) { config = new(Config) err = nil var configFiles []string configFiles = iterateForConfig(configDir, configFiles) config.ConfigsMap = make(map[string]interface{}) for _, file := range configFiles { if !strings.HasSuffix(file, ".hjson") && !strings.HasSuffix(file, ".json") { continue } content, errF := ioutil.ReadFile(file) if errF != nil { config = nil err = errF return } var conf map[string]interface{} err = hjson.Unmarshal(content, &conf) if err != nil { config = nil return } dirname, filename := filepath.Split(file) extension := filepath.Ext(file) filename = filename[:len(filename)-len(extension)] if strings.Trim(dirname, "/\\") != strings.Trim(configDir, "/\\") { dirname = dirname[len(configDir):] dirname = strings.Replace(strings.Trim(dirname, "/\\"), "/", ".", -1) + "." + filename folders := strings.Split(dirname, ".") lenFolders := len(folders) filename = folders[0] for index := lenFolders - 1; index > 0; index-- { conf = map[string]interface{}{ folders[index]: conf, } } } config.ConfigsMap[filename] = conf } if envDir != "" { err = godotenv.Load(filepath.Join(envDir, ".env")) if err == nil { if flag.Lookup("test.v") != nil { err = godotenv.Overload(filepath.Join(envDir, ".env.test")) } } } envEval := new(envEvaluator) config.EvaluatorFunctionsMap = map[string]EvaluatorFunction{ envEval.GetFunctionName(): envEval, } if evalFunctions != nil { for _, evalFunc := range evalFunctions { config.EvaluatorFunctionsMap[evalFunc.GetFunctionName()] = evalFunc } } return } func iterateForConfig(topPath string, configFiles []string) []string { filepath.Walk(topPath, func(path string, info os.FileInfo, err error) error { if info != nil { if info.IsDir() && path != topPath { if info.Name() == "test" { if flag.Lookup("test.v") == nil { return nil } } iterateForConfig(path, configFiles) } else { configFiles = append(configFiles, path) } } return nil }) return configFiles } func get(config *Config, key string, def interface{}) interface{} { keys := strings.Split(key, ".") if len(keys) < 1 { return def } return iterateForKey(config, &keys, config.ConfigsMap, def) } func iterateForKey(config *Config, keys *[]string, conf map[string]interface{}, def interface{}) interface{} { if len(*keys) < 1 { return def } key := (*keys)[0] isArray := false var arrayIndex int var err error if strings.Contains(key, "[") && strings.Contains(key, "]") { indexStart := strings.Index(key, "[") indexEnd := strings.Index(key, "]") keyName := key[:indexStart] isArray = true arrayIndex, err = strconv.Atoi(key[indexStart+1 : indexEnd]) if err != nil { return def } key = keyName } if len(*keys) == 1 { if conf[key] != nil { if isArray { return conf[key].([]interface{})[arrayIndex] } if reflect.TypeOf(conf[key]).Kind() == reflect.String { strKey := conf[key].(string) return evalStringValue(config, strKey, def) } return conf[key] } return def } if conf[key] != nil { if isArray { newKeys := (*keys)[1:] arr := conf[key].([]interface{}) return iterateForKey(config, &newKeys, arr[arrayIndex].(map[string]interface{}), def) } newKeys := (*keys)[1:] return iterateForKey(config, &newKeys, conf[key].(map[string]interface{}), def) } return def } func evalStringValue(config *Config, content string, def interface{}) interface{} { evalStartIndex := strings.Index(content, "(") evalEndIndex := strings.Index(content, ")") if evalStartIndex > 0 && evalEndIndex > 0 { methodName := strings.Trim(content[:evalStartIndex], "\"\t' ") if config.EvaluatorFunctionsMap[methodName] != nil { evalParamsString := content[evalStartIndex+1 : evalEndIndex] evalParams := strings.Split(evalParamsString, ",") var evalParamsSanitized []string for _, param := range evalParams { evalParamsSanitized = append(evalParamsSanitized, strings.Trim(param, "\"\t' ")) } return config.EvaluatorFunctionsMap[methodName].Eval(evalParamsSanitized, def) } } return content } // EvaluatorFunction lets you create dynamic config values // they act like functions inside your hjson/json files // each function when called inside config files can have any number of // arguments and they are passed to the Eval function. type EvaluatorFunction interface { // Evaluate the input arguments and return the value // if an error happened just return the def value Eval(params []string, def interface{}) interface{} // Get the name of the function // Returned value of this function is the string // that is used inside config files to call this evaluator GetFunctionName() string } // Config object for accessing configurations as a map // all files are parsed at Creation time and recursively added // to the ConfigsMap. // Its much better and easier to use Getter functions of the struct. // But when accessing full config objects are needed they are available with GetMap function or // throw the ConfigsMap object type Config struct { ConfigsMap map[string]interface{} EvaluatorFunctionsMap map[string]EvaluatorFunction } // IsSet returns true if there is value for key, false otherwise func (c *Config) IsSet(key string) bool { return get(c, key, nil) != nil } // Get returns the raw interface{} value of a key // You have to convert it to your desired type // If you have used a custom EvaluatorFunction to generate the value // simply cast the interface{} to your desired type func (c *Config) Get(key string, def interface{}) interface{} { return get(c, key, def) } // GetString checks if the value of the key can be converted to string or not // if not or if the key does not exist returns the def value func (c *Config) GetString(key string, def string) string { strVal, ok := c.Get(key, def).(string) if ok { return strVal } return def } // GetInt checks if the value of the key can be converted to int or not // if not or if the key does not exist returns the def value func (c *Config) GetInt(key string, def int) int { floatVal, ok := c.Get(key, def).(float64) if ok { return int(floatVal) } return def } // GetInt64 checks if the value of the key can be converted to int64 or not // if not or if the key does not exist returns the def value func (c *Config) GetInt64(key string, def int64) int64 { floatVal, ok := c.Get(key, def).(float64) if ok && floatVal > math.MinInt64 && floatVal < math.MaxInt64 { return int64(floatVal) } return def } // GetInt64 checks if the value of the key can be converted to int64 or not // if not or if the key does not exist returns the def value func (c *Config) GetUInt64(key string, def uint64) uint64 { floatVal, ok := c.Get(key, def).(float64) if ok { return uint64(floatVal) } return def } // GetFloat checks if the value of the key can be converted to float64 or not // if not or if the key does not exist returns the def value func (c *Config) GetFloat(key string, def float64) float64 { floatVal, ok := c.Get(key, def).(float64) if ok { return floatVal } return def } // GetBoolean checks if the value of the key can be converted to boolean or not // if not or if the key does not exist returns the def value // valid values are true,false,1,0 func (c *Config) GetBoolean(key string, def bool) bool { val, ok := c.Get(key, def).(bool) if !ok { val, ok := c.Get(key, def).(float64) if ok { return val == 1 } return def } return val } // GetStringArray checks if the value of the key can be converted to []string or not // if not or if the key does not exist returns the def value func (c *Config) GetStringArray(key string, def []string) []string { arr, ok := c.Get(key, def).([]string) if ok { return arr } arrS := c.Get(key, def).([]interface{}) var foundStrings = make([]string, len(arrS)) for index, item := range arrS { foundStrings[index] = evalStringValue(c, item.(string), item.(string)).(string) } return foundStrings } // GetIntArray checks if the value of the key can be converted to []int or not // if not or if the key does not exist returns the def value func (c *Config) GetIntArray(key string, def []int) []int { arr, ok := c.Get(key, def).([]int) if ok { return arr } arrI := c.Get(key, def).([]interface{}) var foundArray = make([]int, len(arrI)) for index, item := range arrI { foundArray[index] = int(item.(float64)) } return foundArray } // GetFloatArray checks if the value of the key can be converted to []float64 or not // if not or if the key does not exist returns the def value func (c *Config) GetFloatArray(key string, def []float64) []float64 { arr, ok := c.Get(key, def).([]float64) if ok { return arr } arrF := c.Get(key, def).([]interface{}) var foundArray = make([]float64, len(arrF)) for index, item := range arrF { foundArray[index] = item.(float64) } return foundArray } // GetMap returns the raw config object as map of strings func (c *Config) GetMap(key string, def map[string]interface{}) map[string]interface{} { mapVal, ok := c.Get(key, def).(map[string]interface{}) if ok { return mapVal } return def } // GetAsString converts the value of the key to string and returns it, // if the key does not exist returns the def value func (c *Config) GetAsString(key string, def string) string { val := c.Get(key, def) switch val.(type) { case string: return val.(string) case int: return strconv.Itoa(val.(int)) case float64: return strconv.FormatFloat(val.(float64), 'f', -1, 64) default: return fmt.Sprintf("%v", val) } }
package main import ( "fmt" "sort" ) func sum(a, b int) int { // Return type put after the parameters return a + b } func meanAndMedian(n ...float64) (float64, float64) { // Ellipsis to define listed inputs. Function returns tuple total := 0.0 for _, v := range n { // range keyword iterates through will tuple that is (index, value) total += v } count := len(n) mean := total / float64(count) sort.Float64s(n) middleIdx := count / 2 // Integer division takes the floor var median float64 if middleIdx%2 == 0 { median = (n[middleIdx-1] + n[middleIdx]) / 2.0 } else { median = n[middleIdx] } return mean, median } func main() { i := sum(23, 20) fmt.Println(i) mean, median := meanAndMedian(1.0, 2.0, 6.0, 8.0) // Unpacking similar to python fmt.Println(mean, median) }
package other import ( "fmt" "testing" ) func TestJinZhiConversion(t *testing.T) { Conversion(1348, 2) Conversion(1348, 8) Conversion(1348, 16) } /** @param n : 要转换的数值 @param d : 要转换成的进制数 */ func Conversion(n int, d int) { var stack []int for n != 0 { stack = append(stack, n%d) n /= d } // 输出 START for i := len(stack) - 1; i >= 0; i-- { fmt.Printf("%d ", stack[i]) } fmt.Println() // 输出 END }
package logs import ( "encoding/json" "fmt" "log" "os" "strings" "sync" "time" ) const ( dateFmt string = "2006-01-02" dateTimeFmt string = "2006-01-02-15-04-05" //1M的大小 msize = 1048576 ) type MutexFileWriter struct { sync.Mutex fd *os.File } func (this *MutexFileWriter) SetFd(fd *os.File) { if this.fd != nil { this.fd.Close() } this.fd = fd } func (this *MutexFileWriter) Write(b []byte) (int, error) { this.Lock() defer this.Unlock() return this.fd.Write(b) } //usage: Init(`{"filename":"testfilename.log","maxsize":0,"daily":"true","dailycuttime":"00:00"}`) type FileLogOutput struct { lg *log.Logger mw *MutexFileWriter FileName string `json:"filename"` curFileName string //cut max size,单位M CutMaxSize int `json:"maxsize"` cutmaxsize_cursize int //cut daily,每日切割日志 Daily bool `json:daily` //05:00 DailyCutTimeFmt string `json:"dailycuttime"` dailyCutTimeSecond int dailyOpenDate int //prefix Prefix string `json:"prefix"` Level int `json:"level"` headLen int //cut cutLock sync.Mutex } func NewFileLogOutput() LoggerOutputInf { fileLog := &FileLogOutput{FileName: "", CutMaxSize: 10240000, Daily: true, DailyCutTimeFmt: "00:00", dailyCutTimeSecond: 0, Prefix: ""} mw := &MutexFileWriter{} fileLog.mw = mw fileLog.lg = log.New(mw, "", log.Ldate|log.Ltime) return fileLog } func (this *FileLogOutput) Init(config string) error { if len(config) <= 0 { return nil } err := json.Unmarshal([]byte(config), this) if err != nil { return err } this.CutMaxSize = this.CutMaxSize * 1024 * 1024 this.headLen = len(this.Prefix) + len("[T]2012-06-06 09:88:88 ") return this.startLogger() } func (this *FileLogOutput) startLogger() error { this.cutmaxsize_cursize = 0 fd, err := this.createLogFile() if err != nil { return err } this.mw.SetFd(fd) return this.initFd() } func (this *FileLogOutput) initFd() error { fd := this.mw.fd finfo, err := fd.Stat() if err != nil { return fmt.Errorf("get stat err: %s\n", err) } this.cutmaxsize_cursize = int(finfo.Size()) this.dailyOpenDate = time.Now().Day() return nil } func (this *FileLogOutput) createLogFile() (*os.File, error) { // Open the log file filePath := "" postfix := "log" posIndex := strings.LastIndex(this.FileName, ".") if posIndex > 0 && posIndex < len(this.FileName)-1 { filePath = this.FileName[0:posIndex] postfix = this.FileName[posIndex+1:] } if len(filePath) == 0 { filePath = this.FileName } filePath = filePath + "_" + time.Now().Format(dateTimeFmt) + "." + postfix this.curFileName = filePath //如果文件已经存在,则会被覆盖,这个地方可以考虑加文件下标来区别开来 fd, err := os.OpenFile(filePath, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0660) return fd, err } func (this *FileLogOutput) WriteMsg(level int, msg string) error { if level < this.Level { return nil } n := this.headLen + len(msg) this.docheck(n) this.lg.SetPrefix(this.Prefix + levelPrefix[level]) this.lg.Output(2, msg) return nil } func (this *FileLogOutput) docheck(size int) { this.cutLock.Lock() defer this.cutLock.Unlock() if (this.Daily && time.Now().Day() != this.dailyOpenDate) || (this.CutMaxSize > 0 && this.cutmaxsize_cursize >= this.CutMaxSize) { if err := this.doCutLog(); err != nil { fmt.Fprintf(os.Stderr, "FileLogOutput(%q):%s\n", this.FileName, err) return } } this.cutmaxsize_cursize += size } func (this *FileLogOutput) doCutLog() error { println("docutlog") this.mw.Lock() defer this.mw.Unlock() this.mw.fd.Close() // re-start logger err := this.startLogger() if err != nil { return fmt.Errorf("Rotate StartLogger: %s\n", err) } return nil } func (this *FileLogOutput) Flush() { this.mw.fd.Sync() } func (this *FileLogOutput) Destroy() { this.mw.fd.Close() } func init() { println("register file log output") RegisterLoggerAppender("file", NewFileLogOutput) }
package log import ( "sync" ) var levelMap = make(map[string]int) var appLogger *Logger var once = sync.Once{} func init() { levelMap["DEBUG"] = 1 levelMap["INFO"] = 2 levelMap["WARN"] = 3 levelMap["ERROR"] = 4 appLogger = newStdoutLogger("DEBUG") } func InitAppLogger(path string, level string) { once.Do(func() { appLogger = NewLogger(path, level) }) } func Debug(format string, values ...interface{}) { appLogger.Debug(format, values...) } func Info(format string, values ...interface{}) { appLogger.Info(format, values...) } func Warn(format string, values ...interface{}) { appLogger.Warn(format, values...) } func Error(format string, values ...interface{}) { appLogger.Error(format, values...) } func Fatal(format string, values ...interface{}) { appLogger.Fatal(format, values...) }