text
stringlengths
11
4.05M
func peakIndexInMountainArray(A []int) int { for i:=0;i<len(A);i++{ if A[i+1]<A[i] && A[i-1]<A[i]{ return i } } return 0 }
package freshbooks import ( "bytes" "encoding/xml" "io/ioutil" "net/http" "os" ) type Request struct { XMLName xml.Name `xml:"request"` Method string `xml:"method,attr"` } func Do(request interface{}) ([]byte, error) { api := os.Getenv("FRESHBOOKS_API_URL") apiKey := os.Getenv("AUTHENTICATION_TOKEN") client := &http.Client{} output, err := xml.Marshal(request) if err != nil { return []byte{}, err } req, err := http.NewRequest("POST", api, bytes.NewReader(output)) if err != nil { return []byte{}, err } req.SetBasicAuth(apiKey, "X") resp, err := client.Do(req) if err != nil { return []byte{}, err } defer resp.Body.Close() return ioutil.ReadAll(resp.Body) }
package main import ( "encoding/json" "fmt" ) type matrix struct{ rows int cols int elements [][]int } func (m matrix) numberOfRows() int{ return m.rows } func (m matrix) numberOfCols() int{ return m.cols } func (m matrix) setElements(i,j,element int){ m.elements[i][j]=element } func (m *matrix) printMatrix(){ data , err := json.MarshalIndent(m,""," ") if err!=nil{ fmt.Println(err) } fmt.Println(string(data)) } func (m *matrix) addMatrices(addMatrix matrix) [][]int{ for i:=0 ; i<len(m.elements) ; i++ { for j:=0 ; j<len(m.elements[0]) ; j++ { m.elements[i][j] = m.elements[i][j] + addMatrix.elements[i][j] } } return m.elements } func main(){ var e =[][]int { {1,2,3}, {4,5,6},{7,8,9}} var e2 =[][]int { {2,2,2}, {2,2,2},{2,2,2}} m:= matrix{ 3, 3, e, } m2:= matrix{ 3, 3, e2, } fmt.Println(m.numberOfCols()) fmt.Println(m.numberOfRows()) m.setElements(1,1,6) fmt.Println(m.elements[0][0]) fmt.Println(m.addMatrices(m2)) m2.printMatrix() m.printMatrix() }
package usecase import ( "github.com/taniwhy/mochi-match-rest/domain/models" "github.com/taniwhy/mochi-match-rest/domain/repository" ) // GameTitleUseCase : type GameTitleUseCase interface { FindAllGameTitle() ([]*models.GameTitle, error) InsertGameTitle(gameTitle *models.GameTitle) error UpdateGameTitle(gameTitle *models.GameTitle) error DeleteGameTitle(gameTitle *models.GameTitle) error } type gameTitleUsecase struct { gameTitleRepository repository.GameTitleRepository } // NewGameTitleUsecase : func NewGameTitleUsecase(gR repository.GameTitleRepository) GameTitleUseCase { return &gameTitleUsecase{ gameTitleRepository: gR, } } func (gU gameTitleUsecase) FindAllGameTitle() ([]*models.GameTitle, error) { gameTitles, err := gU.gameTitleRepository.FindAllGameTitle() if err != nil { return nil, err } return gameTitles, nil } func (gU gameTitleUsecase) InsertGameTitle(gameTitle *models.GameTitle) error { err := gU.gameTitleRepository.InsertGameTitle(gameTitle) if err != nil { return err } return nil } func (gU gameTitleUsecase) UpdateGameTitle(gameTitle *models.GameTitle) error { err := gU.gameTitleRepository.UpdateGameTitle(gameTitle) if err != nil { return err } return nil } func (gU gameTitleUsecase) DeleteGameTitle(gameTitle *models.GameTitle) error { err := gU.gameTitleRepository.DeleteGameTitle(gameTitle) if err != nil { return err } return nil }
package models import "errors" var ( //ErrSnapshotNotFound used when snapshot is not found ErrSnapshotNotFound = errors.New("not found") ) // Snapshot represents specific version of protodescriptorset type Snapshot struct { ID int64 `binding:"required"` Namespace string `binding:"required"` Name string `binding:"required"` Version string `binding:"required,version"` Latest bool `binding:"required"` }
package dropbox import ( "bufio" "bytes" "github.com/container-storage-interface/spec/lib/go/csi" "github.com/golang/glog" "golang.org/x/net/context" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" "k8s.io/utils/mount" "os" "os/exec" "path" "strings" ) type nodeServer struct { nodeID string } func NewNodeServer(nodeId string) *nodeServer { return &nodeServer{ nodeID: nodeId, } } const ( rootDir = "/mnt/csi-dropbox" dataDir = rootDir + "/data" ) func (n *nodeServer) NodeGetInfo(context.Context, *csi.NodeGetInfoRequest) (*csi.NodeGetInfoResponse, error) { return &csi.NodeGetInfoResponse{ NodeId: n.nodeID, }, nil } func (n nodeServer) NodeStageVolume(ctx context.Context, req *csi.NodeStageVolumeRequest) (*csi.NodeStageVolumeResponse, error) { if len(req.GetVolumeId()) == 0 { return nil, status.Error(codes.InvalidArgument, "Volume ID missing in request") } if len(req.GetStagingTargetPath()) == 0 { return nil, status.Error(codes.InvalidArgument, "Target path missing in request") } if req.GetVolumeCapability() == nil { return nil, status.Error(codes.InvalidArgument, "Volume Capability missing in request") } token, exists := req.Secrets["token"] if !exists { return nil, status.Error(codes.InvalidArgument, "Token not exists") } glog.Infof("targetPath: %v", req.GetStagingTargetPath()) glog.Infof("dataDir: %v", dataDir) err := os.MkdirAll(dataDir, 0777) if err != nil { glog.Error("Can't create dataDir %s", dataDir) return nil, err } dbxfsConfigPath := path.Join(rootDir, "dbxfs_config.json") dbxfsTokenPath := path.Join(rootDir, "dbxfs_token") err = writeFile(dbxfsConfigPath, "{\"access_token_command\": [\"cat\", \""+dbxfsTokenPath+"\"], \"send_error_reports\": true, \"asked_send_error_reports\": true}") if err != nil { glog.Error("Can't create dbxfs config file") return nil, err } err = writeFile(dbxfsTokenPath, token) if err != nil { glog.Error("Can't create dbxfs token file") return nil, err } cmd := exec.Command("dbxfs", dataDir, "-c", dbxfsConfigPath) var stdout bytes.Buffer var stderr bytes.Buffer cmd.Stdout = &stdout cmd.Stderr = &stderr err = cmd.Run() if err != nil { glog.Errorf("Cant mount dbxfs: %s %s", stdout.String(), stderr.String()) return nil, err } glog.V(4).Infof("dropbox-csi: volume %s is mounted %s", dataDir, stdout.String()) return &csi.NodeStageVolumeResponse{}, nil } func writeFile(path, contents string) error { outfile, err := os.Create(path) if err != nil { glog.Error("Can't create %s", path) return err } writer := bufio.NewWriter(outfile) _, err = writer.WriteString(contents) if err != nil { glog.Error("Can't write %s", path) return err } writer.Flush() outfile.Close() return nil } func (n nodeServer) NodeUnstageVolume(ctx context.Context, req *csi.NodeUnstageVolumeRequest) (*csi.NodeUnstageVolumeResponse, error) { if len(req.GetVolumeId()) == 0 { return nil, status.Error(codes.InvalidArgument, "Volume ID missing in request") } if len(req.GetStagingTargetPath()) == 0 { return nil, status.Error(codes.InvalidArgument, "Target path missing in request") } err := mount.New("").Unmount(dataDir) if err != nil { return nil, status.Error(codes.Internal, err.Error()) } glog.V(4).Infof("dropbox-csi: volume %s is unmounted,", dataDir) return &csi.NodeUnstageVolumeResponse{}, nil } func (n nodeServer) NodePublishVolume(ctx context.Context, req *csi.NodePublishVolumeRequest) (*csi.NodePublishVolumeResponse, error) { if req.GetVolumeCapability() == nil { return nil, status.Error(codes.InvalidArgument, "Volume capability missing in request") } if len(req.GetVolumeId()) == 0 { return nil, status.Error(codes.InvalidArgument, "Volume ID missing in request") } if len(req.GetTargetPath()) == 0 { return nil, status.Error(codes.InvalidArgument, "Target path missing in request") } targetPath := req.GetTargetPath() notMnt, err := mount.New("").IsLikelyNotMountPoint(targetPath) if err != nil { if os.IsNotExist(err) { if err = os.MkdirAll(targetPath, 0750); err != nil { return nil, status.Error(codes.Internal, err.Error()) } notMnt = true } else { return nil, status.Error(codes.Internal, err.Error()) } } if !notMnt { return &csi.NodePublishVolumeResponse{}, nil } options := []string{"bind"} if req.GetReadonly() { options = append(options, "ro") } dirToMountInDropbox := dataDir if len(req.VolumeContext["path"]) != 0 { dirToMountInDropbox = path.Join(dirToMountInDropbox, req.VolumeContext["path"]) } mounter := mount.New("") if err := mounter.Mount(dirToMountInDropbox, targetPath, "", options); err != nil { var errList strings.Builder errList.WriteString(err.Error()) } glog.V(4).Infof("dropbox-csi: volume %s is mount to %s.", dirToMountInDropbox, targetPath) return &csi.NodePublishVolumeResponse{}, nil } func (n nodeServer) NodeUnpublishVolume(ctx context.Context, req *csi.NodeUnpublishVolumeRequest) (*csi.NodeUnpublishVolumeResponse, error) { if len(req.GetVolumeId()) == 0 { return nil, status.Error(codes.InvalidArgument, "Volume ID missing in request") } if len(req.GetTargetPath()) == 0 { return nil, status.Error(codes.InvalidArgument, "Target path missing in request") } targetPath := req.GetTargetPath() err := mount.New("").Unmount(targetPath) if err != nil { return nil, status.Error(codes.Internal, err.Error()) } glog.V(4).Infof("dropbox-csi: volume %s is unmounted,", targetPath) return &csi.NodeUnpublishVolumeResponse{}, nil } func (n *nodeServer) NodeGetCapabilities(context.Context, *csi.NodeGetCapabilitiesRequest) (*csi.NodeGetCapabilitiesResponse, error) { return &csi.NodeGetCapabilitiesResponse{ Capabilities: []*csi.NodeServiceCapability{ { Type: &csi.NodeServiceCapability_Rpc{ Rpc: &csi.NodeServiceCapability_RPC{ Type: csi.NodeServiceCapability_RPC_STAGE_UNSTAGE_VOLUME, }, }, }, }, }, nil } func (n nodeServer) NodeGetVolumeStats(context.Context, *csi.NodeGetVolumeStatsRequest) (*csi.NodeGetVolumeStatsResponse, error) { panic("implement me node volumestats") } func (n nodeServer) NodeExpandVolume(context.Context, *csi.NodeExpandVolumeRequest) (*csi.NodeExpandVolumeResponse, error) { panic("implement me node expand") }
package main type User struct { Name string } func main() { u := User{Name: "Leto"} println(u.Name) Modify(u) println(u.Name) arr := []int{} println(arr) M(&arr) println(arr) } func Modify(u User) { u.Name = "Duncan" } func M(arr *[]int) { *arr = append(*arr, 1) }
// Copyright 2019 Radiation Detection and Imaging (RDI), LLC // Use of this source code is governed by the BSD 3-clause // license that can be found in the LICENSE file. package data import ( "encoding/binary" "log" "github.com/rditech/rdi-live/model/rdi/currentmode" "github.com/proio-org/go-proio" ) func AssembleFrame(event *proio.Event) { if len(event.Metadata["UID"]) < 8 { return } uid := binary.BigEndian.Uint64(event.Metadata["UID"]) frame := &currentmode.Frame{} for i, sampleId := range event.TaggedEntries("Sample") { hpsSample, ok := event.GetEntry(sampleId).(*currentmode.HpsSample) if !ok { if event.Err != nil { log.Println(event.Err) event.Err = nil } continue } sampleTs := uint64(hpsSample.SampleNumber) * 171799 if i == 0 { frame.Timestamp = sampleTs } sample := &currentmode.Sample{ Timestamp: sampleTs - frame.Timestamp, Hps: make(map[uint64]*currentmode.HpsSample), } sample.Hps[uid] = hpsSample frame.Sample = append(frame.Sample, sample) } if len(frame.Sample) > 0 { event.AddEntry("Frame", frame) } }
package example import ( "log" "os" "syscall" "github.com/Beyond-simplechain/foundation/allocator/shmallocator" ) type Item struct { id uint32 name [4]byte //p *byte } const _TestMemorySize = 1024 * 1024 * 1024 * 4 const _TestMemoryFilePath = "/tmp/data/mmap.bin" var defaultAlloc = shmallocator.New(func() []byte { f, err := os.OpenFile(_TestMemoryFilePath, os.O_RDWR|os.O_CREATE, 0644) // if nil != err { log.Fatalln(err) } // // // extend file if _, err := f.WriteAt([]byte{0}, _TestMemorySize); nil != err { log.Fatalln("extend error: ", err) } data, err := syscall.Mmap(int(f.Fd()), 0, _TestMemorySize, syscall.PROT_WRITE, syscall.MAP_SHARED|syscall.MAP_COPY) if nil != err { log.Fatalln(err) } if err := f.Close(); nil != err { log.Fatalln(err) } return data }, nil) //go:generate go install "foundation/allocator/" //go:generate go install "foundation/offsetptr/" //go:generate go install "foundation/container/list/..." //go:generate gotemplate "foundation/container/list" ExampleList(Item,defaultAlloc) //go:generate go build .
package handler import "time" const ( // TokenAvailableDuration 是用户登录后所获得登录凭证的有效期 TokenAvailableDuration = time.Hour * 24 )
// Copyright (c) 2016 Nicolas Martyanoff <khaelin@gmail.com> // // Permission to use, copy, modify, and distribute this software for any // purpose with or without fee is hereby granted, provided that the above // copyright notice and this permission notice appear in all copies. // // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES // WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF // MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR // ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES // WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN // ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF // OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. package irc import ( "bytes" "fmt" "strings" ) func IsChanName(s string) bool { if len(s) == 0 { return false } return s[0] == '#' || s[0] == '&' || s[0] == '+' || s[0] == '!' } type Cmd struct { Prefix string Cmd string Params []string } func (c *Cmd) Equal(c2 *Cmd) bool { if c.Prefix != c2.Prefix { return false } if c.Cmd != c2.Cmd { return false } if len(c.Params) != len(c2.Params) { return false } for i, param := range c.Params { if param != c2.Params[i] { return false } } return true } func (c *Cmd) Parse(buf []byte) error { // Prefix (optional) if buf[0] == ':' { idx := bytes.IndexByte(buf, ' ') if idx == -1 { return fmt.Errorf("truncated message") } c.Prefix = string(buf[1:idx]) buf = buf[idx+1:] } // Command idx := bytes.IndexAny(buf, " \r") if idx == -1 { return fmt.Errorf("truncated message") } c.Cmd = string(buf[:idx]) buf = buf[idx+1:] // Parameters for len(buf) > 0 && buf[0] != '\r' && buf[0] != '\n' { var param string if buf[0] == ':' || len(c.Params) == 14 { // Trailing parameter idx := bytes.IndexByte(buf, '\r') if idx == -1 { return fmt.Errorf("truncated trailing " + "parameter") } if buf[0] == ':' { param = string(buf[1:idx]) } else { param = string(buf[:idx]) } buf = buf[idx+1:] } else { // Middle parameter idx := bytes.IndexAny(buf, " \r") if idx == -1 { return fmt.Errorf("truncated parameter") } param = string(buf[:idx]) buf = buf[idx+1:] } c.Params = append(c.Params, param) } return nil } func (c *Cmd) Serialize() []byte { buf := bytes.NewBuffer([]byte{}) if c.Prefix != "" { fmt.Fprintf(buf, ":%s ", c.Prefix) } buf.WriteString(c.Cmd) if len(c.Params) > 0 { for i := 0; i < len(c.Params)-1; i++ { fmt.Fprintf(buf, " %s", c.Params[i]) } fmt.Fprintf(buf, " :%s", c.Params[len(c.Params)-1]) } buf.WriteString("\r\n") return buf.Bytes() } func (cmd *Cmd) PrefixNickname() string { idx := strings.IndexAny(cmd.Prefix, "!@") if idx == -1 { return "" } return cmd.Prefix[:idx] }
package dao import ( "database/sql" "errors" "fmt" _ "github.com/go-sql-driver/mysql" xerrors "github.com/pkg/errors" "geektime/Go-000/Week02/model" ) const ( MYSQLSRC = "root:123456@tcp(192.168.141.181:3306)/testdb?charset=utf8" ) var ( db *sql.DB ErrDaoNotFound = errors.New("Dao:No rows found") ) func init() { var err error db, err = sql.Open("mysql", MYSQLSRC) fmt.Println(1) if err != nil { panic(err) } } func DBConn() *sql.DB { return db } func GetUserInfo(name string) (*model.User, error) { user := &model.User{} stmt, err := DBConn().Prepare( "select user_name,user_age from tbl_user where user_name=? limit 1") if err != nil { return nil, xerrors.Wrap(err, "Prepare statement failed") } defer stmt.Close() err = stmt.QueryRow(name).Scan(&user.Name, &user.Age) if err != nil { if xerrors.Is(err, sql.ErrNoRows) { err = xerrors.Wrap(ErrDaoNotFound, "no result found in sql") } else { err = xerrors.Wrap(err, "QueryRow failed") } return nil, err } return user, nil }
package userstorage import ( "crypto/md5" "encoding/hex" "errors" "fmt" "io/ioutil" "math/rand" "os" "strconv" "strings" ) // ErrWrongPassword : f var ErrWrongPassword error = errors.New("wrong password") // ErrWrongLoginOrPassword : u var ErrWrongLoginOrPassword error = errors.New("wrong login or password") // ErrAlreadyUsedLogin : c var ErrAlreadyUsedLogin error = errors.New("already used login") // ErrBadUid : k var ErrBadUid error = errors.New("bad uid") // ErrShortPassword : d var ErrShortPassword error = errors.New("short password") // ErrWrongLogin : o var ErrBadLogin error = errors.New("bad login at id getting") type UsValid interface { GetUid(login string) (string, error) Valid(login, pass string) error } type UsSignUp interface { SignUp(login, pass string) } type UsAuth interface { Check(uid, role string) (bool, error) } type UsReader interface { readUs(filename string) (*os.File, error) } type UsTxt struct { Filename string // fileLine: "login salt md5 uid role" Location string RolesFilename string // fileLine: "uid role" //RolesLocation string } func NewUsTxt(filename, location, rolesfilename string) *UsTxt { return &UsTxt{Filename: filename, Location: location, RolesFilename: rolesfilename} } func (storage *UsTxt) readUs(filename string) (*os.File, error) { return os.OpenFile((storage.Location + filename), os.O_APPEND|os.O_RDWR|os.O_CREATE, os.ModePerm) } func getUsData(i UsReader, filename string) ([]byte, error) { var data []byte file, err := i.readUs(filename) if err != nil { return nil, err } defer file.Close() data, err = ioutil.ReadAll(file) return data, err } // getMD5hash : pass + salt to md5 func getMD5hash(salt, pass string) (string, error) { hash := md5.New() _, err := hash.Write([]byte(pass)) if err != nil { return "", err } _, err = hash.Write([]byte(salt)) if err != nil { return "", err } return hex.EncodeToString(hash.Sum(nil)), nil } // Valid : Authentification func (storage *UsTxt) Valid(login string, pass string) error { file, err := getUsData(storage, storage.Filename) if err != nil { return err } fileLines := strings.Split(string(file), "\n") for i := 0; i < len(fileLines); i++ { if fileLines[i] != "" { fileLine := strings.Split(string(fileLines[i]), " ") if fileLine[0] == login { // check typed login hash, err := getMD5hash(fileLine[1], pass) if err != nil { return err } if hash == fileLine[2] { // check typed pass return nil } return ErrWrongPassword } } } return ErrWrongLoginOrPassword } // Check : check your priveleges func (storage *UsTxt) Check(uid, role string) (bool, error) { rolesfile, err := getUsData(storage, storage.RolesFilename) if err != nil { return false, err } fileLines := strings.Split(string(rolesfile), "\n") for i := 0; i < len(fileLines); i++ { if fileLines[i] != "" { fileLine := strings.Split(string(fileLines[i]), " ") if fileLine[0] == uid { if err != nil { return false, err } if role == "banned" { return true, nil } return false, nil } } } return false, ErrBadUid } // SignUp : registration func (storage *UsTxt) SignUp(login, pass string) error { takenUid := 0 file, err := getUsData(storage, storage.Filename) if err != nil { return err } fileLines := strings.Split(string(file), "\n") // check new login for being takened for takenUid < len(fileLines) { if fileLines[takenUid] != "" { fileLine := strings.Split(string(fileLines[takenUid]), " ") if login == fileLine[0] { return ErrAlreadyUsedLogin } } takenUid++ } if len(pass) > 0 { // check new pass and write userdata to storage salt := strconv.Itoa(rand.Intn(5000)) hash, err := getMD5hash(salt, pass) if err != nil { return err } file, err := storage.readUs(storage.Filename) // write to userstorage if err != nil { return err } defer file.Close() _, err = file.WriteString(login + " " + salt + " " + hash + " " + strconv.Itoa(takenUid) + "\n") if err != nil { return err } rolesfile, err := storage.readUs(storage.RolesFilename) // write to rolesstorage if err != nil { return err } defer rolesfile.Close() _, err = rolesfile.WriteString(strconv.Itoa(takenUid) + " " + "смерд\n") return err } return ErrShortPassword } // GetUid : fuck func (storage *UsTxt) GetUid(login string) (string, error) { file, err := getUsData(storage, storage.Filename) if err != nil { return "", err } fileLines := strings.Split(string(file), "\n") for i := 0; i < len(fileLines); i++ { if fileLines[i] != "" { fileLine := strings.Split(string(fileLines[i]), " ") fmt.Println(fileLine[0] + " - " + login) if fileLine[0] == login { // check typed login return fileLine[3], nil } } } return "", ErrBadLogin }
package slack import ( "encoding/json" "fmt" "testing" "github.com/stretchr/testify/assert" ) var simpleMessage = `{ "type": "message", "channel": "C2147483705", "user": "U2147483697", "text": "Hello world", "ts": "1355517523.000005" }` func unmarshalMessage(j string) (*Message, error) { message := &Message{} if err := json.Unmarshal([]byte(j), &message); err != nil { return nil, err } return message, nil } func TestSimpleMessage(t *testing.T) { message, err := unmarshalMessage(simpleMessage) assert.Nil(t, err) assert.NotNil(t, message) assert.Equal(t, "message", message.Type) assert.Equal(t, "C2147483705", message.Channel) assert.Equal(t, "U2147483697", message.User) assert.Equal(t, "Hello world", message.Text) assert.Equal(t, "1355517523.000005", message.Timestamp) } var starredMessage = `{ "text": "is testing", "type": "message", "subtype": "me_message", "user": "U2147483697", "ts": "1433314126.000003", "is_starred": true }` func TestStarredMessage(t *testing.T) { message, err := unmarshalMessage(starredMessage) assert.Nil(t, err) assert.NotNil(t, message) assert.Equal(t, "is testing", message.Text) assert.Equal(t, "message", message.Type) assert.Equal(t, MsgSubTypeMeMessage, message.SubType) assert.Equal(t, "U2147483697", message.User) assert.Equal(t, "1433314126.000003", message.Timestamp) assert.Equal(t, true, message.IsStarred) } var editedMessage = `{ "type": "message", "user": "U2147483697", "text": "hello edited", "edited": { "user": "U2147483697", "ts": "1433314416.000000" }, "ts": "1433314408.000004" }` func TestEditedMessage(t *testing.T) { message, err := unmarshalMessage(editedMessage) assert.Nil(t, err) assert.NotNil(t, message) assert.Equal(t, "message", message.Type) assert.Equal(t, "U2147483697", message.User) assert.Equal(t, "hello edited", message.Text) assert.NotNil(t, message.Edited) assert.Equal(t, "U2147483697", message.Edited.User) assert.Equal(t, "1433314416.000000", message.Edited.Timestamp) assert.Equal(t, "1433314408.000004", message.Timestamp) } var uploadedFile = `{ "type": "message", "subtype": "file_share", "text": "<@U2147483697|tester> uploaded a file: <https:\/\/test.slack.com\/files\/tester\/abc\/test.txt|test.txt> and commented: test comment here", "files": [{ "id": "abc", "created": 1433314757, "timestamp": 1433314757, "name": "test.txt", "title": "test.txt", "mimetype": "text\/plain", "filetype": "text", "pretty_type": "Plain Text", "user": "U2147483697", "editable": true, "size": 5, "mode": "snippet", "is_external": false, "external_type": "", "is_public": true, "public_url_shared": false, "url": "https:\/\/slack-files.com\/files-pub\/abc-def-ghi\/test.txt", "url_download": "https:\/\/slack-files.com\/files-pub\/abc-def-ghi\/download\/test.txt", "url_private": "https:\/\/files.slack.com\/files-pri\/abc-def\/test.txt", "url_private_download": "https:\/\/files.slack.com\/files-pri\/abc-def\/download\/test.txt", "permalink": "https:\/\/test.slack.com\/files\/tester\/abc\/test.txt", "permalink_public": "https:\/\/slack-files.com\/abc-def-ghi", "edit_link": "https:\/\/test.slack.com\/files\/tester\/abc\/test.txt\/edit", "preview": "test\n", "preview_highlight": "<div class=\"sssh-code\"><div class=\"sssh-line\"><pre>test<\/pre><\/div>\n<div class=\"sssh-line\"><pre><\/pre><\/div>\n<\/div>", "lines": 2, "lines_more": 0, "channels": [ "C2147483705" ], "groups": [], "ims": [], "comments_count": 1, "initial_comment": { "id": "Fc066YLGKH", "created": 1433314757, "timestamp": 1433314757, "user": "U2147483697", "comment": "test comment here" } }], "user": "U2147483697", "upload": true, "ts": "1433314757.000006" }` func TestUploadedFile(t *testing.T) { message, err := unmarshalMessage(uploadedFile) assert.Nil(t, err) assert.NotNil(t, message) assert.Equal(t, "message", message.Type) assert.Equal(t, MsgSubTypeFileShare, message.SubType) assert.Equal(t, "<@U2147483697|tester> uploaded a file: <https://test.slack.com/files/tester/abc/test.txt|test.txt> and commented: test comment here", message.Text) // TODO: Assert File assert.Equal(t, "U2147483697", message.User) assert.True(t, message.Upload) assert.Equal(t, "1433314757.000006", message.Timestamp) } var testPost = `{ "type": "message", "subtype": "file_share", "text": "<@U2147483697|tester> shared a file: <https:\/\/test.slack.com\/files\/tester\/abc\/test_post|test post>", "files": [{ "id": "abc", "created": 1433315398, "timestamp": 1433315398, "name": "test_post", "title": "test post", "mimetype": "text\/plain", "filetype": "post", "pretty_type": "Post", "user": "U2147483697", "editable": true, "size": 14, "mode": "post", "is_external": false, "external_type": "", "is_public": true, "public_url_shared": false, "url": "https:\/\/slack-files.com\/files-pub\/abc-def-ghi\/test_post", "url_download": "https:\/\/slack-files.com\/files-pub\/abc-def-ghi\/download\/test_post", "url_private": "https:\/\/files.slack.com\/files-pri\/abc-def\/test_post", "url_private_download": "https:\/\/files.slack.com\/files-pri\/abc-def\/download\/test_post", "permalink": "https:\/\/test.slack.com\/files\/tester\/abc\/test_post", "permalink_public": "https:\/\/slack-files.com\/abc-def-ghi", "edit_link": "https:\/\/test.slack.com\/files\/tester\/abc\/test_post\/edit", "preview": "test post body", "channels": [ "C2147483705" ], "groups": [], "ims": [], "comments_count": 1 }], "user": "U2147483697", "upload": false, "ts": "1433315416.000008" }` func TestPost(t *testing.T) { message, err := unmarshalMessage(testPost) assert.Nil(t, err) assert.NotNil(t, message) assert.Equal(t, "message", message.Type) assert.Equal(t, MsgSubTypeFileShare, message.SubType) assert.Equal(t, "<@U2147483697|tester> shared a file: <https://test.slack.com/files/tester/abc/test_post|test post>", message.Text) // TODO: Assert File assert.Equal(t, "U2147483697", message.User) assert.False(t, message.Upload) assert.Equal(t, "1433315416.000008", message.Timestamp) } var testComment = `{ "type": "message", "subtype": "file_comment", "text": "<@U2147483697|tester> commented on <@U2147483697|tester>'s file <https:\/\/test.slack.com\/files\/tester\/abc\/test_post|test post>: another comment", "files": [{ "id": "abc", "created": 1433315398, "timestamp": 1433315398, "name": "test_post", "title": "test post", "mimetype": "text\/plain", "filetype": "post", "pretty_type": "Post", "user": "U2147483697", "editable": true, "size": 14, "mode": "post", "is_external": false, "external_type": "", "is_public": true, "public_url_shared": false, "url": "https:\/\/slack-files.com\/files-pub\/abc-def-ghi\/test_post", "url_download": "https:\/\/slack-files.com\/files-pub\/abc-def-ghi\/download\/test_post", "url_private": "https:\/\/files.slack.com\/files-pri\/abc-def\/test_post", "url_private_download": "https:\/\/files.slack.com\/files-pri\/abc-def\/download\/test_post", "permalink": "https:\/\/test.slack.com\/files\/tester\/abc\/test_post", "permalink_public": "https:\/\/slack-files.com\/abc-def-ghi", "edit_link": "https:\/\/test.slack.com\/files\/tester\/abc\/test_post\/edit", "preview": "test post body", "channels": [ "C2147483705" ], "groups": [], "ims": [], "comments_count": 2 }], "comment": { "id": "xyz", "created": 1433316360, "timestamp": 1433316360, "user": "U2147483697", "comment": "another comment" }, "ts": "1433316360.000009" }` func TestComment(t *testing.T) { message, err := unmarshalMessage(testComment) fmt.Println(err) assert.Nil(t, err) assert.NotNil(t, message) assert.Equal(t, "message", message.Type) assert.Equal(t, MsgSubTypeFileComment, message.SubType) assert.Equal(t, "<@U2147483697|tester> commented on <@U2147483697|tester>'s file <https://test.slack.com/files/tester/abc/test_post|test post>: another comment", message.Text) // TODO: Assert File // TODO: Assert Comment assert.Equal(t, "1433316360.000009", message.Timestamp) } var botMessage = `{ "type": "message", "subtype": "bot_message", "text": "Pushing is the answer", "suppress_notification": false, "bot_id": "BB12033", "username": "github", "icons": {}, "team": "T01A9CUMPQA", "bot_profile": { "id": "BB12033", "deleted": false, "name": "github", "updated": 1599574335, "app_id": "A6DB2SWUW", "icons": { "image_36": "https://slack-files2.s3-us-west-2.amazonaws.com/avatars/2017-10-24/261138718469_ada58732a18da119678d_36.png", "image_48": "https://slack-files2.s3-us-west-2.amazonaws.com/avatars/2017-10-24/261138718469_ada58732a18da119678d_48.png", "image_72": "https://slack-files2.s3-us-west-2.amazonaws.com/avatars/2017-10-24/261138718469_ada58732a18da119678d_72.png" }, "team_id": "T01A9CUMPQA" }, "blocks": [], "channel": "C01AZ844Z32", "event_ts": "1358877455.000010", "ts": "1358877455.000010" }` func TestBotMessage(t *testing.T) { message, err := unmarshalMessage(botMessage) assert.Nil(t, err) assert.NotNil(t, message) assert.Equal(t, "message", message.Type) assert.Equal(t, MsgSubTypeBotMessage, message.SubType) assert.Equal(t, "1358877455.000010", message.Timestamp) assert.Equal(t, "Pushing is the answer", message.Text) assert.Equal(t, "BB12033", message.BotID) assert.Equal(t, "github", message.Username) assert.NotNil(t, message.Icons) assert.Empty(t, message.Icons.IconURL) assert.Empty(t, message.Icons.IconEmoji) assert.Equal(t, "github", message.BotProfile.Name) assert.Equal(t, "BB12033", message.BotProfile.ID) assert.Equal(t, false, message.BotProfile.Deleted) assert.Equal(t, int64(1599574335), message.BotProfile.Updated) assert.Equal(t, "A6DB2SWUW", message.BotProfile.AppID) assert.Equal(t, "https://slack-files2.s3-us-west-2.amazonaws.com/avatars/2017-10-24/261138718469_ada58732a18da119678d_36.png", message.BotProfile.Icons.Image36) assert.Equal(t, "https://slack-files2.s3-us-west-2.amazonaws.com/avatars/2017-10-24/261138718469_ada58732a18da119678d_48.png", message.BotProfile.Icons.Image48) assert.Equal(t, "https://slack-files2.s3-us-west-2.amazonaws.com/avatars/2017-10-24/261138718469_ada58732a18da119678d_72.png", message.BotProfile.Icons.Image72) assert.Equal(t, "T01A9CUMPQA", message.BotProfile.TeamID) assert.Equal(t, "C01AZ844Z32", message.Channel) assert.Equal(t, "1358877455.000010", message.EventTimestamp) } var meMessage = `{ "type": "message", "subtype": "me_message", "channel": "C2147483705", "user": "U2147483697", "text": "is doing that thing", "ts": "1355517523.000005" }` func TestMeMessage(t *testing.T) { message, err := unmarshalMessage(meMessage) assert.Nil(t, err) assert.NotNil(t, message) assert.Equal(t, "message", message.Type) assert.Equal(t, MsgSubTypeMeMessage, message.SubType) assert.Equal(t, "C2147483705", message.Channel) assert.Equal(t, "U2147483697", message.User) assert.Equal(t, "is doing that thing", message.Text) assert.Equal(t, "1355517523.000005", message.Timestamp) } var messageChangedMessage = `{ "type": "message", "subtype": "message_changed", "hidden": true, "channel": "C2147483705", "ts": "1358878755.000001", "message": { "type": "message", "user": "U2147483697", "text": "Hello, world!", "ts": "1355517523.000005", "edited": { "user": "U2147483697", "ts": "1358878755.000001" } } }` func TestMessageChangedMessage(t *testing.T) { message, err := unmarshalMessage(messageChangedMessage) assert.Nil(t, err) assert.NotNil(t, message) assert.Equal(t, "message", message.Type) assert.Equal(t, MsgSubTypeMessageChanged, message.SubType) assert.True(t, message.Hidden) assert.Equal(t, "C2147483705", message.Channel) assert.NotNil(t, message.SubMessage) assert.Equal(t, "message", message.SubMessage.Type) assert.Equal(t, "U2147483697", message.SubMessage.User) assert.Equal(t, "Hello, world!", message.SubMessage.Text) assert.Equal(t, "1355517523.000005", message.SubMessage.Timestamp) assert.NotNil(t, message.SubMessage.Edited) assert.Equal(t, "U2147483697", message.SubMessage.Edited.User) assert.Equal(t, "1358878755.000001", message.SubMessage.Edited.Timestamp) assert.Equal(t, "1358878755.000001", message.Timestamp) } var messageDeletedMessage = `{ "type": "message", "subtype": "message_deleted", "hidden": true, "channel": "C2147483705", "ts": "1358878755.000001", "deleted_ts": "1358878749.000002" }` func TestMessageDeletedMessage(t *testing.T) { message, err := unmarshalMessage(messageDeletedMessage) assert.Nil(t, err) assert.NotNil(t, message) assert.Equal(t, "message", message.Type) assert.Equal(t, MsgSubTypeMessageDeleted, message.SubType) assert.True(t, message.Hidden) assert.Equal(t, "C2147483705", message.Channel) assert.Equal(t, "1358878755.000001", message.Timestamp) assert.Equal(t, "1358878749.000002", message.DeletedTimestamp) } var channelJoinMessage = `{ "type": "message", "subtype": "channel_join", "ts": "1358877458.000011", "user": "U2147483828", "text": "<@U2147483828|cal> has joined the channel" }` func TestChannelJoinMessage(t *testing.T) { message, err := unmarshalMessage(channelJoinMessage) assert.Nil(t, err) assert.NotNil(t, message) assert.Equal(t, "message", message.Type) assert.Equal(t, MsgSubTypeChannelJoin, message.SubType) assert.Equal(t, "1358877458.000011", message.Timestamp) assert.Equal(t, "U2147483828", message.User) assert.Equal(t, "<@U2147483828|cal> has joined the channel", message.Text) } var channelJoinInvitedMessage = `{ "type": "message", "subtype": "channel_join", "ts": "1358877458.000011", "user": "U2147483828", "text": "<@U2147483828|cal> has joined the channel", "inviter": "U2147483829" }` func TestChannelJoinInvitedMessage(t *testing.T) { message, err := unmarshalMessage(channelJoinInvitedMessage) assert.Nil(t, err) assert.NotNil(t, message) assert.Equal(t, "message", message.Type) assert.Equal(t, MsgSubTypeChannelJoin, message.SubType) assert.Equal(t, "1358877458.000011", message.Timestamp) assert.Equal(t, "U2147483828", message.User) assert.Equal(t, "<@U2147483828|cal> has joined the channel", message.Text) assert.Equal(t, "U2147483829", message.Inviter) } var channelLeaveMessage = `{ "type": "message", "subtype": "channel_leave", "ts": "1358877455.000010", "user": "U2147483828", "text": "<@U2147483828|cal> has left the channel" }` func TestChannelLeaveMessage(t *testing.T) { message, err := unmarshalMessage(channelLeaveMessage) assert.Nil(t, err) assert.NotNil(t, message) assert.Equal(t, "message", message.Type) assert.Equal(t, MsgSubTypeChannelLeave, message.SubType) assert.Equal(t, "1358877455.000010", message.Timestamp) assert.Equal(t, "U2147483828", message.User) assert.Equal(t, "<@U2147483828|cal> has left the channel", message.Text) } var channelTopicMessage = `{ "type": "message", "subtype": "channel_topic", "ts": "1358877455.000010", "user": "U2147483828", "topic": "hello world", "text": "<@U2147483828|cal> set the channel topic: hello world" }` func TestChannelTopicMessage(t *testing.T) { message, err := unmarshalMessage(channelTopicMessage) assert.Nil(t, err) assert.NotNil(t, message) assert.Equal(t, "message", message.Type) assert.Equal(t, MsgSubTypeChannelTopic, message.SubType) assert.Equal(t, "1358877455.000010", message.Timestamp) assert.Equal(t, "U2147483828", message.User) assert.Equal(t, "hello world", message.Topic) assert.Equal(t, "<@U2147483828|cal> set the channel topic: hello world", message.Text) } var channelPurposeMessage = `{ "type": "message", "subtype": "channel_purpose", "ts": "1358877455.000010", "user": "U2147483828", "purpose": "whatever", "text": "<@U2147483828|cal> set the channel purpose: whatever" }` func TestChannelPurposeMessage(t *testing.T) { message, err := unmarshalMessage(channelPurposeMessage) assert.Nil(t, err) assert.NotNil(t, message) assert.Equal(t, "message", message.Type) assert.Equal(t, MsgSubTypeChannelPurpose, message.SubType) assert.Equal(t, "1358877455.000010", message.Timestamp) assert.Equal(t, "U2147483828", message.User) assert.Equal(t, "whatever", message.Purpose) assert.Equal(t, "<@U2147483828|cal> set the channel purpose: whatever", message.Text) } var channelNameMessage = `{ "type": "message", "subtype": "channel_name", "ts": "1358877455.000010", "user": "U2147483828", "old_name": "random", "name": "watercooler", "text": "<@U2147483828|cal> has renamed the channel from \"random\" to \"watercooler\"" }` func TestChannelNameMessage(t *testing.T) { message, err := unmarshalMessage(channelNameMessage) assert.Nil(t, err) assert.NotNil(t, message) assert.Equal(t, "message", message.Type) assert.Equal(t, MsgSubTypeChannelName, message.SubType) assert.Equal(t, "1358877455.000010", message.Timestamp) assert.Equal(t, "U2147483828", message.User) assert.Equal(t, "random", message.OldName) assert.Equal(t, "watercooler", message.Name) assert.Equal(t, "<@U2147483828|cal> has renamed the channel from \"random\" to \"watercooler\"", message.Text) } var channelArchiveMessage = `{ "type": "message", "subtype": "channel_archive", "ts": "1361482916.000003", "text": "<U1234|@cal> archived the channel", "user": "U1234", "members": ["U1234", "U5678"] }` func TestChannelArchiveMessage(t *testing.T) { message, err := unmarshalMessage(channelArchiveMessage) assert.Nil(t, err) assert.NotNil(t, message) assert.Equal(t, "message", message.Type) assert.Equal(t, MsgSubTypeChannelArchive, message.SubType) assert.Equal(t, "1361482916.000003", message.Timestamp) assert.Equal(t, "<U1234|@cal> archived the channel", message.Text) assert.Equal(t, "U1234", message.User) assert.NotNil(t, message.Members) assert.Equal(t, 2, len(message.Members)) } var channelUnarchiveMessage = `{ "type": "message", "subtype": "channel_unarchive", "ts": "1361482916.000003", "text": "<U1234|@cal> un-archived the channel", "user": "U1234" }` func TestChannelUnarchiveMessage(t *testing.T) { message, err := unmarshalMessage(channelUnarchiveMessage) assert.Nil(t, err) assert.NotNil(t, message) assert.Equal(t, "message", message.Type) assert.Equal(t, MsgSubTypeChannelUnarchive, message.SubType) assert.Equal(t, "1361482916.000003", message.Timestamp) assert.Equal(t, "<U1234|@cal> un-archived the channel", message.Text) assert.Equal(t, "U1234", message.User) } var channelRepliesParentMessage = `{ "type": "message", "user": "U1234", "text": "test", "thread_ts": "1493305433.915644", "reply_count": 2, "replies": [ { "user": "U5678", "ts": "1493305444.920992" }, { "user": "U9012", "ts": "1493305894.133936" } ], "subscribed": true, "last_read": "1493305894.133936", "unread_count": 0, "ts": "1493305433.915644" }` func TestChannelRepliesParentMessage(t *testing.T) { message, err := unmarshalMessage(channelRepliesParentMessage) assert.Nil(t, err) assert.NotNil(t, message) assert.Equal(t, "message", message.Type) assert.Equal(t, "U1234", message.User) assert.Equal(t, "test", message.Text) assert.Equal(t, "1493305433.915644", message.ThreadTimestamp) assert.Equal(t, 2, message.ReplyCount) assert.Equal(t, "U5678", message.Replies[0].User) assert.Equal(t, "1493305444.920992", message.Replies[0].Timestamp) assert.Equal(t, "U9012", message.Replies[1].User) assert.Equal(t, "1493305894.133936", message.Replies[1].Timestamp) assert.Equal(t, "1493305433.915644", message.Timestamp) } var channelRepliesChildMessage = `{ "type": "message", "user": "U5678", "text": "foo", "thread_ts": "1493305433.915644", "parent_user_id": "U1234", "ts": "1493305444.920992" }` func TestChannelRepliesChildMessage(t *testing.T) { message, err := unmarshalMessage(channelRepliesChildMessage) assert.Nil(t, err) assert.NotNil(t, message) assert.Equal(t, "message", message.Type) assert.Equal(t, "U5678", message.User) assert.Equal(t, "foo", message.Text) assert.Equal(t, "1493305433.915644", message.ThreadTimestamp) assert.Equal(t, "U1234", message.ParentUserId) assert.Equal(t, "1493305444.920992", message.Timestamp) } var groupJoinMessage = `{ "type": "message", "subtype": "group_join", "ts": "1358877458.000011", "user": "U2147483828", "text": "<@U2147483828|cal> has joined the group" }` func TestGroupJoinMessage(t *testing.T) { message, err := unmarshalMessage(groupJoinMessage) assert.Nil(t, err) assert.NotNil(t, message) assert.Equal(t, "message", message.Type) assert.Equal(t, MsgSubTypeGroupJoin, message.SubType) assert.Equal(t, "1358877458.000011", message.Timestamp) assert.Equal(t, "U2147483828", message.User) assert.Equal(t, "<@U2147483828|cal> has joined the group", message.Text) } var groupJoinInvitedMessage = `{ "type": "message", "subtype": "group_join", "ts": "1358877458.000011", "user": "U2147483828", "text": "<@U2147483828|cal> has joined the group", "inviter": "U2147483829" }` func TestGroupJoinInvitedMessage(t *testing.T) { message, err := unmarshalMessage(groupJoinInvitedMessage) assert.Nil(t, err) assert.NotNil(t, message) assert.Equal(t, "message", message.Type) assert.Equal(t, MsgSubTypeGroupJoin, message.SubType) assert.Equal(t, "1358877458.000011", message.Timestamp) assert.Equal(t, "U2147483828", message.User) assert.Equal(t, "<@U2147483828|cal> has joined the group", message.Text) assert.Equal(t, "U2147483829", message.Inviter) } var groupLeaveMessage = `{ "type": "message", "subtype": "group_leave", "ts": "1358877455.000010", "user": "U2147483828", "text": "<@U2147483828|cal> has left the group" }` func TestGroupLeaveMessage(t *testing.T) { message, err := unmarshalMessage(groupLeaveMessage) assert.Nil(t, err) assert.NotNil(t, message) assert.Equal(t, "message", message.Type) assert.Equal(t, MsgSubTypeGroupLeave, message.SubType) assert.Equal(t, "1358877455.000010", message.Timestamp) assert.Equal(t, "U2147483828", message.User) assert.Equal(t, "<@U2147483828|cal> has left the group", message.Text) } var groupTopicMessage = `{ "type": "message", "subtype": "group_topic", "ts": "1358877455.000010", "user": "U2147483828", "topic": "hello world", "text": "<@U2147483828|cal> set the group topic: hello world" }` func TestGroupTopicMessage(t *testing.T) { message, err := unmarshalMessage(groupTopicMessage) assert.Nil(t, err) assert.NotNil(t, message) assert.Equal(t, "message", message.Type) assert.Equal(t, MsgSubTypeGroupTopic, message.SubType) assert.Equal(t, "1358877455.000010", message.Timestamp) assert.Equal(t, "U2147483828", message.User) assert.Equal(t, "hello world", message.Topic) assert.Equal(t, "<@U2147483828|cal> set the group topic: hello world", message.Text) } var groupPurposeMessage = `{ "type": "message", "subtype": "group_purpose", "ts": "1358877455.000010", "user": "U2147483828", "purpose": "whatever", "text": "<@U2147483828|cal> set the group purpose: whatever" }` func TestGroupPurposeMessage(t *testing.T) { message, err := unmarshalMessage(groupPurposeMessage) assert.Nil(t, err) assert.NotNil(t, message) assert.Equal(t, "message", message.Type) assert.Equal(t, MsgSubTypeGroupPurpose, message.SubType) assert.Equal(t, "1358877455.000010", message.Timestamp) assert.Equal(t, "U2147483828", message.User) assert.Equal(t, "whatever", message.Purpose) assert.Equal(t, "<@U2147483828|cal> set the group purpose: whatever", message.Text) } var groupNameMessage = `{ "type": "message", "subtype": "group_name", "ts": "1358877455.000010", "user": "U2147483828", "old_name": "random", "name": "watercooler", "text": "<@U2147483828|cal> has renamed the group from \"random\" to \"watercooler\"" }` func TestGroupNameMessage(t *testing.T) { message, err := unmarshalMessage(groupNameMessage) assert.Nil(t, err) assert.NotNil(t, message) assert.Equal(t, "message", message.Type) assert.Equal(t, MsgSubTypeGroupName, message.SubType) assert.Equal(t, "1358877455.000010", message.Timestamp) assert.Equal(t, "U2147483828", message.User) assert.Equal(t, "random", message.OldName) assert.Equal(t, "watercooler", message.Name) assert.Equal(t, "<@U2147483828|cal> has renamed the group from \"random\" to \"watercooler\"", message.Text) } var groupArchiveMessage = `{ "type": "message", "subtype": "group_archive", "ts": "1361482916.000003", "text": "<U1234|@cal> archived the group", "user": "U1234", "members": ["U1234", "U5678"] }` func TestGroupArchiveMessage(t *testing.T) { message, err := unmarshalMessage(groupArchiveMessage) assert.Nil(t, err) assert.NotNil(t, message) assert.Equal(t, "message", message.Type) assert.Equal(t, MsgSubTypeGroupArchive, message.SubType) assert.Equal(t, "1361482916.000003", message.Timestamp) assert.Equal(t, "<U1234|@cal> archived the group", message.Text) assert.Equal(t, "U1234", message.User) assert.NotNil(t, message.Members) assert.Equal(t, 2, len(message.Members)) } var groupUnarchiveMessage = `{ "type": "message", "subtype": "group_unarchive", "ts": "1361482916.000003", "text": "<U1234|@cal> un-archived the group", "user": "U1234" }` func TestGroupUnarchiveMessage(t *testing.T) { message, err := unmarshalMessage(groupUnarchiveMessage) assert.Nil(t, err) assert.NotNil(t, message) assert.Equal(t, "message", message.Type) assert.Equal(t, MsgSubTypeGroupUnarchive, message.SubType) assert.Equal(t, "1361482916.000003", message.Timestamp) assert.Equal(t, "<U1234|@cal> un-archived the group", message.Text) assert.Equal(t, "U1234", message.User) } var fileShareMessage = `{ "type": "message", "subtype": "file_share", "ts": "1358877455.000010", "text": "<@cal> uploaded a file: <https:...7.png|7.png>", "files": [{ "id" : "F2147483862", "created" : 1356032811, "timestamp" : 1356032811, "name" : "file.htm", "title" : "My HTML file", "mimetype" : "text\/plain", "filetype" : "text", "pretty_type": "Text", "user" : "U2147483697", "mode" : "hosted", "editable" : true, "is_external": false, "external_type": "", "size" : 12345, "url": "https:\/\/slack-files.com\/files-pub\/T024BE7LD-F024BERPE-09acb6\/1.png", "url_download": "https:\/\/slack-files.com\/files-pub\/T024BE7LD-F024BERPE-09acb6\/download\/1.png", "url_private": "https:\/\/slack.com\/files-pri\/T024BE7LD-F024BERPE\/1.png", "url_private_download": "https:\/\/slack.com\/files-pri\/T024BE7LD-F024BERPE\/download\/1.png", "thumb_64": "https:\/\/slack-files.com\/files-tmb\/T024BE7LD-F024BERPE-c66246\/1_64.png", "thumb_80": "https:\/\/slack-files.com\/files-tmb\/T024BE7LD-F024BERPE-c66246\/1_80.png", "thumb_360": "https:\/\/slack-files.com\/files-tmb\/T024BE7LD-F024BERPE-c66246\/1_360.png", "thumb_360_gif": "https:\/\/slack-files.com\/files-tmb\/T024BE7LD-F024BERPE-c66246\/1_360.gif", "thumb_360_w": 100, "thumb_360_h": 100, "permalink" : "https:\/\/tinyspeck.slack.com\/files\/cal\/F024BERPE\/1.png", "edit_link" : "https:\/\/tinyspeck.slack.com\/files\/cal\/F024BERPE\/1.png/edit", "preview" : "&lt;!DOCTYPE html&gt;\n&lt;html&gt;\n&lt;meta charset='utf-8'&gt;", "preview_highlight" : "&lt;div class=\"sssh-code\"&gt;&lt;div class=\"sssh-line\"&gt;&lt;pre&gt;&lt;!DOCTYPE html...", "lines" : 123, "lines_more": 118, "is_public": true, "public_url_shared": false, "channels": ["C024BE7LT"], "groups": ["G12345"], "ims": ["D12345"], "initial_comment": {}, "num_stars": 7, "is_starred": true }], "user": "U2147483697", "upload": true }` func TestFileShareMessage(t *testing.T) { message, err := unmarshalMessage(fileShareMessage) fmt.Println(err) assert.Nil(t, err) assert.NotNil(t, message) assert.Equal(t, "message", message.Type) assert.Equal(t, MsgSubTypeFileShare, message.SubType) assert.Equal(t, "1358877455.000010", message.Timestamp) assert.Equal(t, "<@cal> uploaded a file: <https:...7.png|7.png>", message.Text) assert.Equal(t, "U2147483697", message.User) assert.True(t, message.Upload) assert.NotNil(t, message.Files[0]) }
package http import ( "github.com/asppj/droneDeploy/conf" "github.com/kataras/iris/v12" ) type ( request struct { Firstname string `json:"firstname"` Lastname string `json:"lastname"` } response struct { ID uint64 `json:"id"` // id Message string `json:"message"` // msg Platform string `json:"platform"` // platform } ) func Init() { app := iris.New() app.Get("/health", healthCheck) if err := app.Listen(":18080"); err != nil { panic(err) } } func healthCheck(ctx iris.Context) { ctx.WriteString("GET successfully\n" + conf.BuildVersion()) }
package utils import ( "crypto/rand" "encoding/base64" "fmt" "time" "golang.org/x/crypto/bcrypt" ) // GenerateHash hash strings func GenerateHash(raw string) (string, error) { hash, err := bcrypt.GenerateFromPassword([]byte(raw), bcrypt.DefaultCost) if err != nil { return "", err } return string(hash), nil } // CompareHash hash comparison of raw string func CompareHash(hashed, password string) bool { if err := bcrypt.CompareHashAndPassword([]byte(hashed), []byte(password)); err != nil { return false } return true } // GenerateToken random tokens func GenerateToken() (string, error) { b := make([]byte, 16) _, err := rand.Read(b) if err != nil { return "", err } uuid := fmt.Sprintf("%x-%x-%x-%x-%x", b[0:4], b[4:6], b[6:8], b[8:10], b[10:]) src := []byte(uuid + time.Now().UTC().Format(time.RFC850)) return base64.StdEncoding.EncodeToString(src), nil }
package usecase import ( "context" "go.uber.org/zap" "github.com/silverspase/todo/internal/modules/auth" "github.com/silverspase/todo/internal/modules/auth/model" ) type useCase struct { repo auth.Repository logger *zap.Logger } func NewUseCase(logger *zap.Logger, repo auth.Repository) auth.UseCase { return &useCase{ repo: repo, logger: logger, } } func (u useCase) CreateUser(ctx context.Context, entry model.User) (string, error) { return u.repo.CreateUser(ctx, entry) } func (u useCase) GetAllUsers(ctx context.Context, page int) ([]model.User, error) { return u.repo.GetAllUsers(ctx, page) } func (u useCase) GetUser(ctx context.Context, id string) (model.User, error) { return u.repo.GetUser(ctx, id) } func (u useCase) UpdateUser(ctx context.Context, entry model.User) (string, error) { return u.repo.UpdateUser(ctx, entry) } func (u useCase) DeleteUser(ctx context.Context, id string) (string, error) { return u.repo.DeleteUser(ctx, id) }
package main type Problem15A struct { } func (this *Problem15A) Solve() { Log.Info("Problem 15A solver beginning!") system := DiskSlotSystem{}; err := system.Load("source-data/input-day-15a.txt"); if(err != nil){ Log.FatalError(err); } time := 0; for{ if(system.Simulate(time)){ Log.Info("First valid time was %d", time); break; } time++; } }
// Copyright 2019 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 importer import ( "context" "database/sql" "fmt" "math" "strconv" "strings" "github.com/pingcap/errors" "github.com/pingcap/tidb/br/pkg/lightning/checkpoints" "github.com/pingcap/tidb/br/pkg/lightning/common" "github.com/pingcap/tidb/br/pkg/lightning/config" "github.com/pingcap/tidb/br/pkg/lightning/log" "github.com/pingcap/tidb/br/pkg/lightning/metric" "github.com/pingcap/tidb/br/pkg/lightning/mydump" "github.com/pingcap/tidb/parser" "github.com/pingcap/tidb/parser/ast" "github.com/pingcap/tidb/parser/format" "github.com/pingcap/tidb/parser/model" "github.com/pingcap/tidb/parser/mysql" "github.com/pingcap/tidb/sessionctx/variable" "github.com/tikv/client-go/v2/util" "go.uber.org/zap" "golang.org/x/exp/maps" ) // TiDBManager is a wrapper of *sql.DB which provides some helper methods for type TiDBManager struct { db *sql.DB parser *parser.Parser } // DBFromConfig creates a new connection to the TiDB database. func DBFromConfig(ctx context.Context, dsn config.DBStore) (*sql.DB, error) { param := common.MySQLConnectParam{ Host: dsn.Host, Port: dsn.Port, User: dsn.User, Password: dsn.Psw, SQLMode: dsn.StrSQLMode, MaxAllowedPacket: dsn.MaxAllowedPacket, TLSConfig: dsn.Security.TLSConfig, AllowFallbackToPlaintext: dsn.Security.AllowFallbackToPlaintext, Net: dsn.UUID, } db, err := param.Connect() if err != nil { return nil, errors.Trace(err) } vars := map[string]string{ variable.TiDBBuildStatsConcurrency: strconv.Itoa(dsn.BuildStatsConcurrency), variable.TiDBDistSQLScanConcurrency: strconv.Itoa(dsn.DistSQLScanConcurrency), variable.TiDBIndexSerialScanConcurrency: strconv.Itoa(dsn.IndexSerialScanConcurrency), variable.TiDBChecksumTableConcurrency: strconv.Itoa(dsn.ChecksumTableConcurrency), // after https://github.com/pingcap/tidb/pull/17102 merge, // we need set session to true for insert auto_random value in TiDB Backend variable.TiDBAllowAutoRandExplicitInsert: "1", // allow use _tidb_rowid in sql statement variable.TiDBOptWriteRowID: "1", // always set auto-commit to ON variable.AutoCommit: "1", // always set transaction mode to optimistic variable.TiDBTxnMode: "optimistic", // disable foreign key checks variable.ForeignKeyChecks: "0", variable.TiDBExplicitRequestSourceType: util.ExplicitTypeLightning, } if dsn.Vars != nil { maps.Copy(vars, dsn.Vars) } for k, v := range vars { q := fmt.Sprintf("SET SESSION %s = '%s';", k, v) if _, err1 := db.ExecContext(ctx, q); err1 != nil { log.FromContext(ctx).Warn("set session variable failed, will skip this query", zap.String("query", q), zap.Error(err1)) delete(vars, k) } } _ = db.Close() param.Vars = vars db, err = param.Connect() return db, errors.Trace(err) } // NewTiDBManager creates a new TiDB manager. func NewTiDBManager(ctx context.Context, dsn config.DBStore, _ *common.TLS) (*TiDBManager, error) { db, err := DBFromConfig(ctx, dsn) if err != nil { return nil, errors.Trace(err) } return NewTiDBManagerWithDB(db, dsn.SQLMode), nil } // NewTiDBManagerWithDB creates a new TiDB manager with an existing database // connection. func NewTiDBManagerWithDB(db *sql.DB, sqlMode mysql.SQLMode) *TiDBManager { parser := parser.New() parser.SetSQLMode(sqlMode) return &TiDBManager{ db: db, parser: parser, } } // Close closes the underlying database connection. func (timgr *TiDBManager) Close() { timgr.db.Close() } func createIfNotExistsStmt(p *parser.Parser, createTable, dbName, tblName string) ([]string, error) { stmts, _, err := p.ParseSQL(createTable) if err != nil { return []string{}, common.ErrInvalidSchemaStmt.Wrap(err).GenWithStackByArgs(createTable) } var res strings.Builder ctx := format.NewRestoreCtx(format.DefaultRestoreFlags|format.RestoreTiDBSpecialComment|format.RestoreWithTTLEnableOff, &res) retStmts := make([]string, 0, len(stmts)) for _, stmt := range stmts { switch node := stmt.(type) { case *ast.CreateDatabaseStmt: node.Name = model.NewCIStr(dbName) node.IfNotExists = true case *ast.DropDatabaseStmt: node.Name = model.NewCIStr(dbName) node.IfExists = true case *ast.CreateTableStmt: node.Table.Schema = model.NewCIStr(dbName) node.Table.Name = model.NewCIStr(tblName) node.IfNotExists = true case *ast.CreateViewStmt: node.ViewName.Schema = model.NewCIStr(dbName) node.ViewName.Name = model.NewCIStr(tblName) case *ast.DropTableStmt: node.Tables[0].Schema = model.NewCIStr(dbName) node.Tables[0].Name = model.NewCIStr(tblName) node.IfExists = true } if err := stmt.Restore(ctx); err != nil { return []string{}, common.ErrInvalidSchemaStmt.Wrap(err).GenWithStackByArgs(createTable) } ctx.WritePlain(";") retStmts = append(retStmts, res.String()) res.Reset() } return retStmts, nil } // DropTable drops a table. func (timgr *TiDBManager) DropTable(ctx context.Context, tableName string) error { sql := common.SQLWithRetry{ DB: timgr.db, Logger: log.FromContext(ctx).With(zap.String("table", tableName)), } return sql.Exec(ctx, "drop table", "DROP TABLE "+tableName) } // LoadSchemaInfo loads schema information from TiDB. func LoadSchemaInfo( ctx context.Context, schemas []*mydump.MDDatabaseMeta, getTables func(context.Context, string) ([]*model.TableInfo, error), ) (map[string]*checkpoints.TidbDBInfo, error) { result := make(map[string]*checkpoints.TidbDBInfo, len(schemas)) for _, schema := range schemas { tables, err := getTables(ctx, schema.Name) if err != nil { return nil, err } tableMap := make(map[string]*model.TableInfo, len(tables)) for _, tbl := range tables { tableMap[tbl.Name.L] = tbl } dbInfo := &checkpoints.TidbDBInfo{ Name: schema.Name, Tables: make(map[string]*checkpoints.TidbTableInfo), } for _, tbl := range schema.Tables { tblInfo, ok := tableMap[strings.ToLower(tbl.Name)] if !ok { return nil, common.ErrSchemaNotExists.GenWithStackByArgs(tbl.DB, tbl.Name) } tableName := tblInfo.Name.String() if tblInfo.State != model.StatePublic { err := errors.Errorf("table [%s.%s] state is not public", schema.Name, tableName) if m, ok := metric.FromContext(ctx); ok { m.RecordTableCount(metric.TableStatePending, err) } return nil, errors.Trace(err) } if m, ok := metric.FromContext(ctx); ok { m.RecordTableCount(metric.TableStatePending, err) } // Table names are case-sensitive in mydump.MDTableMeta. // We should always use the original tbl.Name in checkpoints. tableInfo := &checkpoints.TidbTableInfo{ ID: tblInfo.ID, DB: schema.Name, Name: tbl.Name, Core: tblInfo, Desired: tblInfo, } dbInfo.Tables[tbl.Name] = tableInfo } result[schema.Name] = dbInfo } return result, nil } // ObtainImportantVariables obtains the important variables from TiDB. func ObtainImportantVariables(ctx context.Context, db *sql.DB, needTiDBVars bool) map[string]string { var query strings.Builder query.WriteString("SHOW VARIABLES WHERE Variable_name IN ('") first := true for k := range common.DefaultImportantVariables { if first { first = false } else { query.WriteString("','") } query.WriteString(k) } if needTiDBVars { for k := range common.DefaultImportVariablesTiDB { query.WriteString("','") query.WriteString(k) } } query.WriteString("')") exec := common.SQLWithRetry{DB: db, Logger: log.FromContext(ctx)} kvs, err := exec.QueryStringRows(ctx, "obtain system variables", query.String()) if err != nil { // error is not fatal log.FromContext(ctx).Warn("obtain system variables failed, use default variables instead", log.ShortError(err)) } // convert result into a map. fill in any missing variables with default values. result := make(map[string]string, len(common.DefaultImportantVariables)+len(common.DefaultImportVariablesTiDB)) for _, kv := range kvs { result[kv[0]] = kv[1] } setDefaultValue := func(res map[string]string, vars map[string]string) { for k, defV := range vars { if _, ok := res[k]; !ok { res[k] = defV } } } setDefaultValue(result, common.DefaultImportantVariables) if needTiDBVars { setDefaultValue(result, common.DefaultImportVariablesTiDB) } return result } // ObtainNewCollationEnabled obtains the new collation enabled status from TiDB. func ObtainNewCollationEnabled(ctx context.Context, db *sql.DB) (bool, error) { newCollationEnabled := false var newCollationVal string exec := common.SQLWithRetry{DB: db, Logger: log.FromContext(ctx)} err := exec.QueryRow(ctx, "obtain new collation enabled", "SELECT variable_value FROM mysql.tidb WHERE variable_name = 'new_collation_enabled'", &newCollationVal) if err == nil && newCollationVal == "True" { newCollationEnabled = true } else if errors.ErrorEqual(err, sql.ErrNoRows) { // ignore if target variable is not found, this may happen if tidb < v4.0 newCollationEnabled = false err = nil } return newCollationEnabled, errors.Trace(err) } // AlterAutoIncrement rebase the table auto increment id // // NOTE: since tidb can make sure the auto id is always be rebase even if the `incr` value is smaller // than the auto increment base in tidb side, we needn't fetch currently auto increment value here. // See: https://github.com/pingcap/tidb/blob/64698ef9a3358bfd0fdc323996bb7928a56cadca/ddl/ddl_api.go#L2528-L2533 func AlterAutoIncrement(ctx context.Context, db *sql.DB, tableName string, incr uint64) error { logger := log.FromContext(ctx).With(zap.String("table", tableName), zap.Uint64("auto_increment", incr)) base := adjustIDBase(incr) var forceStr string if incr > math.MaxInt64 { // automatically set max value logger.Warn("auto_increment out of the maximum value TiDB supports, automatically set to the max", zap.Uint64("auto_increment", incr)) forceStr = "FORCE" } query := fmt.Sprintf("ALTER TABLE %s %s AUTO_INCREMENT=%d", tableName, forceStr, base) task := logger.Begin(zap.InfoLevel, "alter table auto_increment") exec := common.SQLWithRetry{DB: db, Logger: logger} err := exec.Exec(ctx, "alter table auto_increment", query) task.End(zap.ErrorLevel, err) if err != nil { task.Error( "alter table auto_increment failed, please perform the query manually (this is needed no matter the table has an auto-increment column or not)", zap.String("query", query), ) } return errors.Annotatef(err, "%s", query) } func adjustIDBase(incr uint64) int64 { if incr > math.MaxInt64 { return math.MaxInt64 } return int64(incr) } // AlterAutoRandom rebase the table auto random id func AlterAutoRandom(ctx context.Context, db *sql.DB, tableName string, randomBase uint64, maxAutoRandom uint64) error { logger := log.FromContext(ctx).With(zap.String("table", tableName), zap.Uint64("auto_random", randomBase)) if randomBase == maxAutoRandom+1 { // insert a tuple with key maxAutoRandom randomBase = maxAutoRandom } else if randomBase > maxAutoRandom { // TiDB does nothing when inserting an overflow value logger.Warn("auto_random out of the maximum value TiDB supports") return nil } // if new base is smaller than current, this query will success with a warning query := fmt.Sprintf("ALTER TABLE %s AUTO_RANDOM_BASE=%d", tableName, randomBase) task := logger.Begin(zap.InfoLevel, "alter table auto_random") exec := common.SQLWithRetry{DB: db, Logger: logger} err := exec.Exec(ctx, "alter table auto_random_base", query) task.End(zap.ErrorLevel, err) if err != nil { task.Error( "alter table auto_random_base failed, please perform the query manually (this is needed no matter the table has an auto-random column or not)", zap.String("query", query), ) } return errors.Annotatef(err, "%s", query) }
package main import ( "log" "net/http" "strings" "github.com/yanpozka/checkers/store" ) func gameWS(w http.ResponseWriter, r *http.Request) { parts := strings.Split(r.URL.Path, "/") gameID := parts[len(parts)-1] if gameID == "" { http.Error(w, http.StatusText(http.StatusNotFound), http.StatusNotFound) return } playerID := r.URL.Query().Get("player") if playerID == "" { http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest) return } if bg, err := ms.Get(playerID); err == store.ErrItemNotFound || string(bg) != gameID { log.Printf("PlayerID: %q doesn't have an associated gameID: %q\n", playerID, gameID) http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest) return } conn, err := upgrader.Upgrade(w, r, nil) // if Upgrade fails, it'll write an error message if err != nil { log.Println("Error trying to Upgrade: ", err) return } c := client{ conn: conn, send: make(chan []byte, 1), done: make(chan struct{}, 1), gameID: gameID, playerID: playerID, } go c.write() if err := c.startListenFromNats(); err != nil { log.Println("Error trying to subscribe:", err) c.done <- struct{}{} return } c.read() }
package main import ( "fmt" "github.com/gorilla/websocket" ) type ( MsgData struct { Dst string Data string Src string } PoolUnit struct { bus chan<- []byte out chan []byte } ) func (r *MsgData) Str() string { return fmt.Sprint("dst:", r.Dst, "data:", r.Data) } func NewPoolUnit(bus chan []byte) *PoolUnit { bean := &PoolUnit{ out: make(chan []byte, 10000), bus: bus, } return bean } func (r *PoolUnit) Loop(conn *websocket.Conn, id string) { go r.loopDispatch(conn, id) r.loopReceive(conn, id) } func (r *PoolUnit) loopDispatch(conn *websocket.Conn, id string) { fmt.Println(id, "---loopDispatch----") defer func() { if err := recover(); err != nil { fmt.Println("loopDispatch err", err) } }() for { select { case data, ok := <-r.out: if ok { if err := conn.WriteMessage(1, data); err != nil { fmt.Println("loopDispatch to peer err ", err) return } else { fmt.Println("loopDispatch to peer ok ") } } else { return } } } } func (r *PoolUnit) Dispatch(data []byte) error { r.out <- data return nil } func (r *PoolUnit) loopReceive(conn *websocket.Conn, id string) { defer func() { if err := recover(); err != nil { fmt.Println("err:", err) } }() for { _, msgData, err := conn.ReadMessage() if err != nil { fmt.Printf("**********conn read err:%s\n", err.Error()) return } fmt.Println("unit received from of ID: ", id, "---data->", string(msgData), "len(bus):", len(r.bus)) r.bus <- msgData } }
package models type Post struct { ID int `json:"id"` Author_id int `json:"author_id,omitempty"` Author *string `json:"author"` Forum_id int `json:"forum_id,omitempty"` Forum *string `json:"forum"` Thread int `json:"thread"` Thread_nickname string `json:"thread_slug"` Created *string `json:"created"` IsEdited bool `json:"isEdited"` Message string `json:"message"` Parent int `json:"parent"` } type Posts []*Post type PostDetails struct { Author *User `json:"author,omitempty"` Forum *Forum `json:"forum,omitempty"` Post *Post `json:"post,omitempty"` Thread *Thread `json:"thread,omitempty"` }
package gost512 import ( "bufio" "bytes" "fmt" "os" "strings" gkeys "github.com/number571/go-cryptopro/gost_r_34_10_2012" "github.com/number571/tendermint/crypto" "github.com/number571/tendermint/crypto/tmhash" tmjson "github.com/number571/tendermint/libs/json" ) //------------------------------------- var ( _ crypto.PrivKey = PrivKey{} ) const ( PrivKeyName = "tendermint/PrivKey512" PubKeyName = "tendermint/PubKey512" PubKeySize = gkeys.PubKeySize512 PrivKeySize = gkeys.PrivKeySize512 SignatureSize = gkeys.SignatureSize512 ProvType = "512" KeyType = gkeys.KeyType + " " + ProvType ) func init() { tmjson.RegisterType(PubKey{}, PubKeyName) tmjson.RegisterType(PrivKey{}, PrivKeyName) } type PrivKey gkeys.PrivKey512 func (privKey PrivKey) Bytes() []byte { return gkeys.PrivKey512(privKey).Bytes() } func (privKey PrivKey) Sign(msg []byte) ([]byte, error) { return gkeys.PrivKey512(privKey).Sign(msg) } func (privKey PrivKey) PubKey() crypto.PubKey { return PubKey(gkeys.PrivKey512(privKey).PubKey().(gkeys.PubKey512)) } func (privKey PrivKey) Equals(other crypto.PrivKey) bool { return bytes.Equal(gkeys.PrivKey512(privKey).Bytes(), other.Bytes()) } func (privKey PrivKey) Type() string { return gkeys.PrivKey512(privKey).Type() } func GenPrivKey() PrivKey { fmt.Printf("Generating private key [%s]...\n", KeyType) return GenPrivKeyWithInput( inputString("Subject >>> "), inputString("Password >>> "), ) } func GenPrivKeyWithInput(subject, password string) PrivKey { cfg := gkeys.NewConfig(gkeys.K512, subject, password) gkeys.GenPrivKey(cfg) priv, err := gkeys.NewPrivKey(cfg) if err != nil { panic(err) } return PrivKey(priv.(gkeys.PrivKey512)) } func inputString(begin string) string { fmt.Print(begin) data, err := bufio.NewReader(os.Stdin).ReadString('\n') if err != nil { panic(err) } return strings.TrimSpace(data) } //------------------------------------- var _ crypto.PubKey = PubKey{} type PubKey gkeys.PubKey512 func (pubKey PubKey) Address() crypto.Address { return crypto.Address(tmhash.SumTruncated(pubKey.Bytes())) } func (pubKey PubKey) Bytes() []byte { return gkeys.PubKey512(pubKey).Bytes() } func (pubKey PubKey) VerifySignature(msg []byte, sig []byte) bool { return gkeys.PubKey512(pubKey).VerifySignature(msg, sig) } func (pubKey PubKey) String() string { return gkeys.PubKey512(pubKey).String() } func (pubKey PubKey) Type() string { return gkeys.PubKey512(pubKey).Type() } func (pubKey PubKey) Equals(other crypto.PubKey) bool { return bytes.Equal(gkeys.PubKey512(pubKey).Bytes(), other.Bytes()) } //--- FROM NEW VERSION // var _ crypto.BatchVerifier = &BatchVerifier{} // type BatchVerifier gkeys.BatchVerifierX // func NewBatchVerifier() crypto.BatchVerifier { // return &BatchVerifier{} // } // func (b *BatchVerifier) Add(key crypto.PubKey, msg, signature []byte) error { // return (*gkeys.BatchVerifierX)(b).Add(gkeys.PubKey512(key.(PubKey)), msg, signature) // } // func (b *BatchVerifier) Verify() (bool, []bool) { // return (*gkeys.BatchVerifierX)(b).Verify() // }
package main import "fmt" func max(a, b int) int { if a > b { return a } return b } func rob(nums []int) int { if len(nums) == 0 { return 0 } maxLoot := nums[0] for i, _ := range nums { if i == 0 { continue } j := i - 2 k := i - 3 if j >= 0 { if k >= 0 { nums[i] = max(nums[i]+nums[j], nums[i]+nums[k]) } else { nums[i] += nums[j] } maxLoot = max(maxLoot, nums[i]) } else { maxLoot = max(nums[i], nums[i-1]) } } return maxLoot } func test1() { tests := [][]int{ []int{1, 2, 3, 1}, []int{4}, []int{2, 7, 9, 3, 1}, []int{12}, []int{5, 5, 10, 100, 10, 5}, []int{110}, []int{1, 2, 3}, []int{4}, []int{10, 1}, []int{10}, []int{10}, []int{10}, []int{1, 10}, []int{10}, []int{3, 2, 1}, []int{4}, } for i := 0; i < len(tests); i += 2 { result := rob(tests[i]) if result == tests[i+1][0] { fmt.Printf("Test case %d PASSED\n", i/2) } else { fmt.Printf("Test case %d FAILED. Expected: %d, got %d\n", i/2, tests[i+1][0], result) } } } func main() { test1() }
package docker import ( "fmt" "github.com/Sirupsen/logrus" dockerClient "github.com/fsouza/go-dockerclient" "sync" "time" ) const ( iamLabel = "com.swipely.iam-docker.iam-profile" iamExternalIdLabel = "com.swipely.iam-docker.iam-externalid" iamEnvironmentVariable = "IAM_ROLE" iamExternalIdEnvironmentVariable = "IAM_ROLE_EXTERNALID" retrySleepBase = time.Second retrySleepMultiplier = 2 maxRetries = 3 msiLabel = "com.swipely.iam-docker.msi-explicit-identity" msiEnvironmentVariable = "MSI_IDENTITY" ) var ( runningContainersOpts = dockerClient.ListContainersOptions{ All: false, Size: false, } ) type ComplexRole struct { Arn string ExternalId string } // NewContainerStore creates an empty container store. func NewContainerStore(client RawClient) ContainerStore { return &containerStore{ containerIDsByIP: make(map[string]string), configByContainerID: make(map[string]containerConfig), client: client, } } func (store *containerStore) AddContainerByID(id string) error { logger := log.WithFields(logrus.Fields{"id": id}) logger.Debug("Attempting to add container") config, err := store.findConfigForID(id) if err != nil { return err } for _, ip := range config.ips { logger.WithFields(logrus.Fields{ "ip": ip, "role": config.iamRole, "msi": config.msiIdentity, }).Debug("Adding new container") } store.mutex.Lock() for _, ip := range config.ips { store.containerIDsByIP[ip] = config.id } store.configByContainerID[config.id] = *config store.mutex.Unlock() return nil } func (store *containerStore) IAMRoles() []ComplexRole { log.Debug("Fetching unique IAM Roles in the store") store.mutex.RLock() iamSet := make(map[string]bool, len(store.configByContainerID)) externalId := make(map[string]string, len(store.configByContainerID)) for _, config := range store.configByContainerID { if config.iamRole != "" { iamSet[config.iamRole] = true externalId[config.iamRole] = config.externalId } } store.mutex.RUnlock() iamRoles := make([]ComplexRole, len(iamSet)) count := 0 for role := range iamSet { r := ComplexRole{ Arn: role, ExternalId: externalId[role], } iamRoles[count] = r count++ } return iamRoles } func (store *containerStore) IAMRoleForID(id string) (ComplexRole, error) { log.WithField("id", id).Debug("Looking up IAM role") store.mutex.RLock() defer store.mutex.RUnlock() config, hasKey := store.configByContainerID[id] if !hasKey || config.iamRole == "" { return ComplexRole{}, fmt.Errorf("Unable to find IAM Role config for container: %s", id) } iamRole := ComplexRole{ Arn: config.iamRole, ExternalId: config.externalId, } return iamRole, nil } func (store *containerStore) IAMRoleForIP(ip string) (ComplexRole, error) { log.WithField("ip", ip).Debug("Looking up IAM role") store.mutex.RLock() defer store.mutex.RUnlock() id, hasKey := store.containerIDsByIP[ip] if !hasKey { return ComplexRole{}, fmt.Errorf("Unable to find container for IP: %s", ip) } config, hasKey := store.configByContainerID[id] if !hasKey || config.iamRole == "" { return ComplexRole{}, fmt.Errorf("Unable to find IAM Role config for container: %s", id) } iamRole := ComplexRole{ Arn: config.iamRole, ExternalId: config.externalId, } return iamRole, nil } func (store *containerStore) MSIIdentities() []string { log.Debug("Fetching unique MSI Identities in the store") store.mutex.RLock() msiSet := make(map[string]bool, len(store.configByContainerID)) for _, config := range store.configByContainerID { if config.msiIdentity != "" { msiSet[config.msiIdentity] = true } } store.mutex.RUnlock() msiIdentities := make([]string, len(msiSet)) count := 0 for msiIdentity := range msiSet { msiIdentities[count] = msiIdentity count++ } return msiIdentities } func (store *containerStore) MSIIdentityForID(id string) (string, error) { log.WithField("id", id).Debug("Looking up MSI Identity") store.mutex.RLock() defer store.mutex.RUnlock() config, hasKey := store.configByContainerID[id] if !hasKey || config.msiIdentity == "" { return "", fmt.Errorf("Unable to find MSI config for container: %s", id) } msiIdentity := config.msiIdentity return msiIdentity, nil } func (store *containerStore) MSIIdentityForIP(ip string) (string, error) { log.WithField("ip", ip).Debug("Looking up MSI identity") store.mutex.RLock() defer store.mutex.RUnlock() id, hasKey := store.containerIDsByIP[ip] if !hasKey { return "", fmt.Errorf("Unable to find container for IP: %s", ip) } config, hasKey := store.configByContainerID[id] if !hasKey || config.msiIdentity == "" { return "", fmt.Errorf("Unable to find MSI config for container: %s", id) } msiIdentity := config.msiIdentity return msiIdentity, nil } func (store *containerStore) RemoveContainer(id string) { store.mutex.RLock() config, hasKey := store.configByContainerID[id] store.mutex.RUnlock() if hasKey { log.WithField("id", id).Debug("Removing container") store.mutex.Lock() for _, ip := range config.ips { delete(store.containerIDsByIP, ip) } delete(store.configByContainerID, id) store.mutex.Unlock() } } func (store *containerStore) SyncRunningContainers() error { log.Info("Syncing the running containers") apiContainers, err := store.listContainers() if err != nil { return err } store.mutex.Lock() defer store.mutex.Unlock() count := len(apiContainers) store.containerIDsByIP = make(map[string]string, count) store.configByContainerID = make(map[string]containerConfig, count) for _, container := range apiContainers { config, err := store.findConfigForID(container.ID) if err == nil { for _, ip := range config.ips { log.WithFields(logrus.Fields{ "id": config.id, "ip": ip, "role": config.iamRole, "msi": config.msiIdentity, }).Debug("Adding new container") store.containerIDsByIP[ip] = config.id } store.configByContainerID[config.id] = *config } } log.Info("Done syncing the running containers, ", len(store.configByContainerID), " now in the store") return nil } func (store *containerStore) findConfigForID(id string) (*containerConfig, error) { container, err := store.inspectContainer(id) if err != nil { return nil, err } else if container == nil { return nil, fmt.Errorf("Cannot inspect container: %s", id) } else if container.Config == nil { return nil, fmt.Errorf("Container has no config: %s", id) } else if container.NetworkSettings == nil { return nil, fmt.Errorf("Container has no network settings: %s", id) } externalId, _ := container.Config.Labels[iamExternalIdLabel] iamRole, hasIamLabel := container.Config.Labels[iamLabel] if !hasIamLabel { env := dockerClient.Env(container.Config.Env) envIamRole := env.Get(iamEnvironmentVariable) envExternalId := env.Get(iamExternalIdEnvironmentVariable) if envIamRole != "" { iamRole = envIamRole externalId = envExternalId } } msiIdentity, hasMsiLabel := container.Config.Labels[msiLabel] if !hasMsiLabel { env := dockerClient.Env(container.Config.Env) envMsiIdentity := env.Get(msiEnvironmentVariable) if envMsiIdentity != "" { msiIdentity = envMsiIdentity } } if iamRole == "" && msiIdentity == "" { return nil, fmt.Errorf("Unable to find label named '%s' / '%s' or environment variable '%s' / '%s' for container: %s", iamLabel, msiLabel, iamEnvironmentVariable, msiEnvironmentVariable, id) } ips := make([]string, 0, 2) for _, network := range container.NetworkSettings.Networks { ip := network.IPAddress if ip != "" { ips = append(ips, ip) } } if len(ips) == 0 { return nil, fmt.Errorf("Unable to find IP address for container: %s", id) } config := &containerConfig{ id: id, ips: ips, iamRole: iamRole, externalId: externalId, msiIdentity: msiIdentity, } return config, nil } func (store *containerStore) listContainers() ([]dockerClient.APIContainers, error) { log.Debug("Listing containers") var containers []dockerClient.APIContainers err := withRetries(func() error { var e error containers, e = store.client.ListContainers(runningContainersOpts) return e }) return containers, err } func (store *containerStore) inspectContainer(id string) (*dockerClient.Container, error) { log.WithField("id", id).Debug("Inspecting container") var container *dockerClient.Container err := withRetries(func() error { var e error container, e = store.client.InspectContainer(id) return e }) return container, err } func withRetries(lambda func() error) error { var err error sleepTime := retrySleepBase for attempt := 0; attempt < maxRetries; attempt++ { err = lambda() if err == nil { break } time.Sleep(sleepTime) sleepTime *= retrySleepMultiplier } return err } type containerConfig struct { id string ips []string iamRole string externalId string msiIdentity string } type containerStore struct { mutex sync.RWMutex containerIDsByIP map[string]string configByContainerID map[string]containerConfig client RawClient }
/* Take an input, and convert it from Two's Complement notation (binary where the first bit is negated, but the rest are taken as normal) into decimal. Input can be as a string, a list of digits, a number, or pretty much any other format which is recognizably Two's Complement. Leading zeroes must function properly. Examples: 0 -> 0 1 -> -1 111 -> -3 011 -> 3 100 -> -4 1001 -> -7 0001 -> 1 Example conversion: Say our input is 1101. We can see that the first bit is in position 4, so has a positional value of 2^3. Therefore, since it's a 1, we add -8 to our total. Then, the rest of the bits are converted just the same as regular binary (with 101 being the same as 5), so the result is -3. Example implementation (Mathematica, 40 characters): Rest@#~FromDigits~2 - 2^Length@#/2*#[[1]] & This implementation takes input as a list of digits. If there's no better solution in Mathematica, feel free to use the solution here and post it as a community wiki. */ package main import ( "fmt" "strconv" ) func main() { test("0", 0) test("1", -1) test("011", 3) test("100", -4) test("1001", -7) test("0001", 1) } func assert(x bool) { if !x { panic("assertion failed") } } func test(s string, r int64) { v, err := x2c(s) assert(err == nil) fmt.Printf("%s -> %d\n", s, v) assert(v == r) } func x2c(s string) (int64, error) { n := len(s) x, err := strconv.ParseInt(s, 2, 64) if err != nil { return 0, err } y := int64(1) << (n - 1) v := x if x >= y { v = -y + (x - y) } return v, nil }
package main import ( "fmt" ) func main() { sliceInt := []int{11, 2, 19, 220, 31, 5, 65, 70, 100} find := 65 fmt.Println(sliceInt) if len((sliceInt)) == 0 || (sliceInt)[0] == find { fmt.Println(sliceInt) return } if (sliceInt)[len(sliceInt)-1] == find { (sliceInt) = append([]int{find}, (sliceInt)[:len(sliceInt)-1]...) fmt.Println(sliceInt) return } for p, x := range sliceInt { if x == find { (sliceInt) = append([]int{find}, append((sliceInt)[:p], (sliceInt)[p+1:]...)...) break } } fmt.Println(sliceInt) }
// 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 v20180416 import ( "encoding/json" tchttp "github.com/tencentyun/tcecloud-sdk-go/tcecloud/common/http" ) type Block struct { // 区块编号 BlockNum *uint64 `json:"BlockNum,omitempty" name:"BlockNum"` // 区块Hash数值 DataHash *string `json:"DataHash,omitempty" name:"DataHash"` // 区块ID,与区块编号一致 BlockId *uint64 `json:"BlockId,omitempty" name:"BlockId"` // 前一个区块Hash(未使用),与区块Hash数值一致 PreHash *string `json:"PreHash,omitempty" name:"PreHash"` // 区块内的交易数量 TxCount *uint64 `json:"TxCount,omitempty" name:"TxCount"` } type GetBlockListRequest struct { *tchttp.BaseRequest // 模块名称,固定字段:block Module *string `json:"Module,omitempty" name:"Module"` // 操作名称,固定字段:block_list Operation *string `json:"Operation,omitempty" name:"Operation"` // 通道ID,固定字段:0 ChannelId *string `json:"ChannelId,omitempty" name:"ChannelId"` // 组织ID,固定字段:0 GroupId *string `json:"GroupId,omitempty" name:"GroupId"` // 需要查询的通道名称,可在通道详情或列表中获取 ChannelName *string `json:"ChannelName,omitempty" name:"ChannelName"` // 调用接口的组织名称,可以在组织管理列表中获取当前组织的名称 GroupName *string `json:"GroupName,omitempty" name:"GroupName"` // 区块链网络ID,可在区块链网络详情或列表中获取 ClusterId *string `json:"ClusterId,omitempty" name:"ClusterId"` // 需要获取的起始交易偏移 Offset *uint64 `json:"Offset,omitempty" name:"Offset"` // 需要获取的交易数量 Limit *uint64 `json:"Limit,omitempty" name:"Limit"` } func (r *GetBlockListRequest) ToJsonString() string { b, _ := json.Marshal(r) return string(b) } func (r *GetBlockListRequest) FromJsonString(s string) error { return json.Unmarshal([]byte(s), &r) } type GetBlockListResponse struct { *tchttp.BaseResponse Response *struct { // 区块数量 TotalCount *uint64 `json:"TotalCount,omitempty" name:"TotalCount"` // 区块列表 BlockList []*Block `json:"BlockList,omitempty" name:"BlockList" list` // 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 RequestId *string `json:"RequestId,omitempty" name:"RequestId"` } `json:"Response"` } func (r *GetBlockListResponse) ToJsonString() string { b, _ := json.Marshal(r) return string(b) } func (r *GetBlockListResponse) FromJsonString(s string) error { return json.Unmarshal([]byte(s), &r) } type GetClusterSummaryRequest struct { *tchttp.BaseRequest // 模块名称,固定字段:cluster_mng Module *string `json:"Module,omitempty" name:"Module"` // 操作名称,固定字段:cluster_summary Operation *string `json:"Operation,omitempty" name:"Operation"` // 区块链网络ID,可在区块链网络详情或列表中获取 ClusterId *string `json:"ClusterId,omitempty" name:"ClusterId"` // 组织ID,固定字段:0 GroupId *string `json:"GroupId,omitempty" name:"GroupId"` // 调用接口的组织名称,可以在组织管理列表中获取当前组织的名称 GroupName *string `json:"GroupName,omitempty" name:"GroupName"` } func (r *GetClusterSummaryRequest) ToJsonString() string { b, _ := json.Marshal(r) return string(b) } func (r *GetClusterSummaryRequest) FromJsonString(s string) error { return json.Unmarshal([]byte(s), &r) } type GetClusterSummaryResponse struct { *tchttp.BaseResponse Response *struct { // 网络通道总数量 TotalChannelCount *uint64 `json:"TotalChannelCount,omitempty" name:"TotalChannelCount"` // 当前组织创建的通道数量 MyChannelCount *uint64 `json:"MyChannelCount,omitempty" name:"MyChannelCount"` // 当前组织加入的通道数量 JoinChannelCount *uint64 `json:"JoinChannelCount,omitempty" name:"JoinChannelCount"` // 网络节点总数量 TotalPeerCount *uint64 `json:"TotalPeerCount,omitempty" name:"TotalPeerCount"` // 当前组织创建的节点数量 MyPeerCount *uint64 `json:"MyPeerCount,omitempty" name:"MyPeerCount"` // 其他组织创建的节点数量 OrderCount *uint64 `json:"OrderCount,omitempty" name:"OrderCount"` // 网络组织总数量 TotalGroupCount *uint64 `json:"TotalGroupCount,omitempty" name:"TotalGroupCount"` // 当前组织创建的组织数量 MyGroupCount *uint64 `json:"MyGroupCount,omitempty" name:"MyGroupCount"` // 网络智能合约总数量 TotalChaincodeCount *uint64 `json:"TotalChaincodeCount,omitempty" name:"TotalChaincodeCount"` // 最近7天发起的智能合约数量 RecentChaincodeCount *uint64 `json:"RecentChaincodeCount,omitempty" name:"RecentChaincodeCount"` // 当前组织发起的智能合约数量 MyChaincodeCount *uint64 `json:"MyChaincodeCount,omitempty" name:"MyChaincodeCount"` // 当前组织的证书总数量 TotalCertCount *uint64 `json:"TotalCertCount,omitempty" name:"TotalCertCount"` // 颁发给当前组织的证书数量 TlsCertCount *uint64 `json:"TlsCertCount,omitempty" name:"TlsCertCount"` // 网络背书节点证书数量 PeerCertCount *uint64 `json:"PeerCertCount,omitempty" name:"PeerCertCount"` // 当前组织业务证书数量 ClientCertCount *uint64 `json:"ClientCertCount,omitempty" name:"ClientCertCount"` // 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 RequestId *string `json:"RequestId,omitempty" name:"RequestId"` } `json:"Response"` } func (r *GetClusterSummaryResponse) ToJsonString() string { b, _ := json.Marshal(r) return string(b) } func (r *GetClusterSummaryResponse) FromJsonString(s string) error { return json.Unmarshal([]byte(s), &r) } type GetInvokeTxRequest struct { *tchttp.BaseRequest // 模块名,固定字段:transaction Module *string `json:"Module,omitempty" name:"Module"` // 操作名,固定字段:query_txid Operation *string `json:"Operation,omitempty" name:"Operation"` // 区块链网络ID,可在区块链网络详情或列表中获取 ClusterId *string `json:"ClusterId,omitempty" name:"ClusterId"` // 业务所属通道名称,可在通道详情或列表中获取 ChannelName *string `json:"ChannelName,omitempty" name:"ChannelName"` // 执行该查询交易的节点名称,可以在通道详情中获取该通道上的节点名称极其所属组织名称 PeerName *string `json:"PeerName,omitempty" name:"PeerName"` // 执行该查询交易的节点所属组织名称,可以在通道详情中获取该通道上的节点名称极其所属组织名称 PeerGroup *string `json:"PeerGroup,omitempty" name:"PeerGroup"` // 交易ID TxId *string `json:"TxId,omitempty" name:"TxId"` // 调用合约的组织名称,可以在组织管理列表中获取当前组织的名称 GroupName *string `json:"GroupName,omitempty" name:"GroupName"` } func (r *GetInvokeTxRequest) ToJsonString() string { b, _ := json.Marshal(r) return string(b) } func (r *GetInvokeTxRequest) FromJsonString(s string) error { return json.Unmarshal([]byte(s), &r) } type GetInvokeTxResponse struct { *tchttp.BaseResponse Response *struct { // 交易执行状态码 TxValidationCode *int64 `json:"TxValidationCode,omitempty" name:"TxValidationCode"` // 交易执行消息 TxValidationMsg *string `json:"TxValidationMsg,omitempty" name:"TxValidationMsg"` // 交易所在区块ID BlockId *int64 `json:"BlockId,omitempty" name:"BlockId"` // 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 RequestId *string `json:"RequestId,omitempty" name:"RequestId"` } `json:"Response"` } func (r *GetInvokeTxResponse) ToJsonString() string { b, _ := json.Marshal(r) return string(b) } func (r *GetInvokeTxResponse) FromJsonString(s string) error { return json.Unmarshal([]byte(s), &r) } type GetLatesdTransactionListRequest struct { *tchttp.BaseRequest // 模块名称,固定字段:transaction Module *string `json:"Module,omitempty" name:"Module"` // 操作名称,固定字段:latest_transaction_list Operation *string `json:"Operation,omitempty" name:"Operation"` // 组织ID,固定字段:0 GroupId *string `json:"GroupId,omitempty" name:"GroupId"` // 通道ID,固定字段:0 ChannelId *string `json:"ChannelId,omitempty" name:"ChannelId"` // 获取的最新交易的区块数量,取值范围1~5 LatestBlockNumber *uint64 `json:"LatestBlockNumber,omitempty" name:"LatestBlockNumber"` // 调用接口的组织名称,可以在组织管理列表中获取当前组织的名称 GroupName *string `json:"GroupName,omitempty" name:"GroupName"` // 需要查询的通道名称,可在通道详情或列表中获取 ChannelName *string `json:"ChannelName,omitempty" name:"ChannelName"` // 区块链网络ID,可在区块链网络详情或列表中获取 ClusterId *string `json:"ClusterId,omitempty" name:"ClusterId"` // 需要获取的起始交易偏移 Offset *uint64 `json:"Offset,omitempty" name:"Offset"` // 需要获取的交易数量 Limit *uint64 `json:"Limit,omitempty" name:"Limit"` } func (r *GetLatesdTransactionListRequest) ToJsonString() string { b, _ := json.Marshal(r) return string(b) } func (r *GetLatesdTransactionListRequest) FromJsonString(s string) error { return json.Unmarshal([]byte(s), &r) } type GetLatesdTransactionListResponse struct { *tchttp.BaseResponse Response *struct { // 交易总数量 TotalCount *uint64 `json:"TotalCount,omitempty" name:"TotalCount"` // 交易列表 TransactionList []*TransactionItem `json:"TransactionList,omitempty" name:"TransactionList" list` // 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 RequestId *string `json:"RequestId,omitempty" name:"RequestId"` } `json:"Response"` } func (r *GetLatesdTransactionListResponse) ToJsonString() string { b, _ := json.Marshal(r) return string(b) } func (r *GetLatesdTransactionListResponse) FromJsonString(s string) error { return json.Unmarshal([]byte(s), &r) } type InvokeRequest struct { *tchttp.BaseRequest // 模块名,固定字段:transaction Module *string `json:"Module,omitempty" name:"Module"` // 操作名,固定字段:invoke Operation *string `json:"Operation,omitempty" name:"Operation"` // 区块链网络ID,可在区块链网络详情或列表中获取 ClusterId *string `json:"ClusterId,omitempty" name:"ClusterId"` // 业务所属智能合约名称,可在智能合约详情或列表中获取 ChaincodeName *string `json:"ChaincodeName,omitempty" name:"ChaincodeName"` // 业务所属通道名称,可在通道详情或列表中获取 ChannelName *string `json:"ChannelName,omitempty" name:"ChannelName"` // 对该笔交易进行背书的节点列表(包括节点名称和节点所属组织名称,详见数据结构一节),可以在通道详情中获取该通道上的节点名称极其所属组织名称 Peers []*PeerSet `json:"Peers,omitempty" name:"Peers" list` // 该笔交易需要调用的智能合约中的函数名称 FuncName *string `json:"FuncName,omitempty" name:"FuncName"` // 调用合约的组织名称,可以在组织管理列表中获取当前组织的名称 GroupName *string `json:"GroupName,omitempty" name:"GroupName"` // 被调用的函数参数列表 Args []*string `json:"Args,omitempty" name:"Args" list` // 同步调用标识,可选参数,值为0或者不传表示使用同步方法调用,调用后会等待交易执行后再返回执行结果;值为1时表示使用异步方式调用Invoke,执行后会立即返回交易对应的Txid,后续需要通过GetInvokeTx这个API查询该交易的执行结果。(对于逻辑较为简单的交易,可以使用同步模式;对于逻辑较为复杂的交易,建议使用异步模式,否则容易导致API因等待时间过长,返回等待超时) AsyncFlag *uint64 `json:"AsyncFlag,omitempty" name:"AsyncFlag"` } func (r *InvokeRequest) ToJsonString() string { b, _ := json.Marshal(r) return string(b) } func (r *InvokeRequest) FromJsonString(s string) error { return json.Unmarshal([]byte(s), &r) } type InvokeResponse struct { *tchttp.BaseResponse Response *struct { // 交易ID Txid *string `json:"Txid,omitempty" name:"Txid"` // 交易执行结果 Events *string `json:"Events,omitempty" name:"Events"` // 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 RequestId *string `json:"RequestId,omitempty" name:"RequestId"` } `json:"Response"` } func (r *InvokeResponse) ToJsonString() string { b, _ := json.Marshal(r) return string(b) } func (r *InvokeResponse) FromJsonString(s string) error { return json.Unmarshal([]byte(s), &r) } type PeerSet struct { // 节点名称 PeerName *string `json:"PeerName,omitempty" name:"PeerName"` // 组织名称 OrgName *string `json:"OrgName,omitempty" name:"OrgName"` } type QueryRequest struct { *tchttp.BaseRequest // 模块名,固定字段:transaction Module *string `json:"Module,omitempty" name:"Module"` // 操作名,固定字段:query Operation *string `json:"Operation,omitempty" name:"Operation"` // 区块链网络ID,可在区块链网络详情或列表中获取 ClusterId *string `json:"ClusterId,omitempty" name:"ClusterId"` // 业务所属智能合约名称,可在智能合约详情或列表中获取 ChaincodeName *string `json:"ChaincodeName,omitempty" name:"ChaincodeName"` // 业务所属通道名称,可在通道详情或列表中获取 ChannelName *string `json:"ChannelName,omitempty" name:"ChannelName"` // 执行该查询交易的节点列表(包括节点名称和节点所属组织名称,详见数据结构一节),可以在通道详情中获取该通道上的节点名称极其所属组织名称 Peers []*PeerSet `json:"Peers,omitempty" name:"Peers" list` // 该笔交易查询需要调用的智能合约中的函数名称 FuncName *string `json:"FuncName,omitempty" name:"FuncName"` // 调用合约的组织名称,可以在组织管理列表中获取当前组织的名称 GroupName *string `json:"GroupName,omitempty" name:"GroupName"` // 被调用的函数参数列表 Args []*string `json:"Args,omitempty" name:"Args" list` } func (r *QueryRequest) ToJsonString() string { b, _ := json.Marshal(r) return string(b) } func (r *QueryRequest) FromJsonString(s string) error { return json.Unmarshal([]byte(s), &r) } type QueryResponse struct { *tchttp.BaseResponse Response *struct { // 查询结果数据 Data []*string `json:"Data,omitempty" name:"Data" list` // 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 RequestId *string `json:"RequestId,omitempty" name:"RequestId"` } `json:"Response"` } func (r *QueryResponse) ToJsonString() string { b, _ := json.Marshal(r) return string(b) } func (r *QueryResponse) FromJsonString(s string) error { return json.Unmarshal([]byte(s), &r) } type TransactionItem struct { // 交易ID TransactionId *string `json:"TransactionId,omitempty" name:"TransactionId"` // 交易hash TransactionHash *string `json:"TransactionHash,omitempty" name:"TransactionHash"` // 创建交易的组织名 CreateOrgName *string `json:"CreateOrgName,omitempty" name:"CreateOrgName"` // 交易所在区块号 BlockId *uint64 `json:"BlockId,omitempty" name:"BlockId"` // 交易类型(普通交易和配置交易) TransactionType *string `json:"TransactionType,omitempty" name:"TransactionType"` // 交易创建时间 CreateTime *string `json:"CreateTime,omitempty" name:"CreateTime"` // 交易所在区块高度 BlockHeight *uint64 `json:"BlockHeight,omitempty" name:"BlockHeight"` // 交易状态 TransactionStatus *string `json:"TransactionStatus,omitempty" name:"TransactionStatus"` }
package imageProcessingService import ( "bytes" "encoding/json" "errors" "fmt" "log" "net/http" ) func (client *ImageProcessingClient) ProcessPlate(data interface{}) error { log.Println("Sending ", fmt.Sprint(data)+" to image processing service...") reqBody, err := json.Marshal(data) if err != nil { print(err) } endpoint := fmt.Sprintf("%s/process", client.BaseUrl) resp, err := http.Post(endpoint, "application/json", bytes.NewBuffer(reqBody)) if err != nil { return err } defer resp.Body.Close() if resp.StatusCode < 200 || resp.StatusCode >= 300 { return errors.New("cannot process image") } return nil }
package job import ( "context" "os" "github.com/sherifabdlnaby/prism/pkg/payload" "github.com/sherifabdlnaby/prism/pkg/response" ) // Job represent a job containing a streamable payload (the message) and a response channel, // which is used to indicate whether the payload was successfully processed and propagated to the next destinations. type Job struct { // Payload is the message payload of this job. // is either a payload.Stream OR payload.Bytes. Payload payload.Payload // Data is the message data of this job. Data payload.Data // Context of the job Context context.Context // ResponseChan should receive a response at the end of a job, // The response itself indicates whether the payload was successfully processed and propagated // to the next destinations. ResponseChan chan<- response.Response } // Input represent a job containing a streamable payload, Data, PipelineTag, and a response channel, // response indicate whether the payload was successfully processed and propagated to the next destinations. // PipelineTag indicate to which pipeline should this job be forwarded to. type Input struct { Job PipelineTag string } // Async to be persisted in local DB type Async struct { ID, Filepath, NodeID string Data payload.Data Job Job `json:"-"` JobResponseChan <-chan response.Response `json:"-"` } func (a *Async) Load(Payload payload.Payload) error { var err error newPayload := Payload responseChan := make(chan response.Response, 1) if Payload == nil { // open tmp file newPayload, err = os.Open(a.Filepath) if err != nil { return err } } a.Job = Job{ Payload: newPayload, Data: a.Data, Context: context.Background(), ResponseChan: responseChan, } a.JobResponseChan = responseChan return nil }
package order type PaymentSessionUpdateReq struct { PaymentSessionId int64 AmountPaid float64 AmountLeft float64 Status string } type PaymentItemUpdateReq struct { PaymentItemId int64 `json:"paymentItemId"` PaymentSessionId int64 `json:"paymentSessionId"` Status string `json:"status"` }
package resolver import ( "github.com/taktakty/netlabi/testdata" "github.com/stretchr/testify/require" "strings" "testing" ) func TestIpSegmentQueries(t *testing.T) { testData := ipSegmentTestData t.Run("GetSingle", func(t *testing.T) { p := string(testData[0].ID) q := strings.Join([]string{`query {getIpSegment(input:{id:"`, p, `"})`, testdata.IpSegmentResp, "}"}, "") var resp struct { GetIpSegment testdata.IpSegmentRespStruct } c.MustPost(q, &resp) require.Equal(t, p, resp.GetIpSegment.ID) require.Equal(t, string(testData[0].IPSegment), resp.GetIpSegment.IPSegment) require.Equal(t, testData[0].Note, resp.GetIpSegment.Note) }) t.Run("GetMultiple", func(t *testing.T) { forSearchTestData := testData[5:8] q := strings.Join([]string{`query {getIpSegments(input:{ipSegment:"172.16.1"})`, testdata.IpSegmentResp, "}"}, "") var resp struct { GetIpSegments []testdata.IpSegmentRespStruct } c.MustPost(q, &resp) require.Len(t, resp.GetIpSegments, len(forSearchTestData)) for i, r := range resp.GetIpSegments { require.Equal(t, string(forSearchTestData[i].IPSegment), r.IPSegment) require.Equal(t, forSearchTestData[i].Note, r.Note) } }) }
package otf import "io" type SubtableReader struct { io.ReadSeeker } func (t *SubtableReader) Size() int64 { n, err := t.Seek(0, 2) if err != nil { return 0 } return n } func (t *SubtableReader) Bytes() []byte { bytes := make([]byte, t.Size()) t.Seek(0, 0) t.Read(bytes) return bytes }
/* Description Your rich uncle died recently, and the heritage needs to be divided among your relatives and the church (your uncle insisted in his will that the church must get something). There are N relatives (N <= 18) that were mentioned in the will. They are sorted in descending order according to their importance (the first one is the most important). Since you are the computer scientist in the family, your relatives asked you to help them. They need help, because there are some blanks in the will left to be filled. Here is how the will looks: Relative #1 will get 1 / ... of the whole heritage, Relative #2 will get 1 / ... of the whole heritage, ---------------------- ... Relative #n will get 1 / ... of the whole heritage. The logical desire of the relatives is to fill the blanks in such way that the uncle's will is preserved (i.e the fractions are non-ascending and the church gets something) and the amount of heritage left for the church is minimized. Input The only line of input contains the single integer N (1 <= N <= 18). Output Output the numbers that the blanks need to be filled (on separate lines), so that the heritage left for the church is minimized. Sample Input 2 Sample Output 2 3 Source ural 1108 */ package main import ( "fmt" "math/big" ) func main() { for i := 0; i < 2; i++ { fmt.Println(sylvester(i)) } } // https://oeis.org/A000058 func sylvester(n int) *big.Int { one := big.NewInt(1) r := big.NewInt(2) for i := 0; i < n; i++ { x := new(big.Int) y := new(big.Int) x.Mul(r, r) y.Neg(r) x.Add(x, y) x.Add(x, one) r.Set(x) } return r }
// ˅ package main import ( "github.com/lxn/walk" ) // ˄ type ColleagueButton struct { // ˅ // ˄ Colleague pushButton *walk.PushButton // ˅ // ˄ } func NewColleagueButton(pushButton *walk.PushButton) *ColleagueButton { // ˅ colleagueButton := &ColleagueButton{} colleagueButton.Colleague = *NewColleague() colleagueButton.pushButton = pushButton return colleagueButton // ˄ } // Set enable/disable from the Mediator func (self *ColleagueButton) SetActivation(isEnable bool) { // ˅ self.pushButton.SetEnabled(isEnable) // ˄ } func (self *ColleagueButton) OnClicked() { // ˅ self.mediator.ColleagueChanged() // ˄ } func (self *ColleagueButton) IsSelected() bool { // ˅ return self.pushButton.Focused() // ˄ } // ˅ // ˄
package scanner import ( "time" ) const ( // AnalysisStatusQueued denotes a request for analysis has been // accepted and queued AnalysisStatusQueued = "queued" // AnalysisStatusErrored denotes a request for analysis has errored during // the run, the message field will have more details AnalysisStatusErrored = "errored" // AnalysisStatusFinished denotes a request for analysis has been // completed, view the passed field from an Analysis and the scan details for // more information AnalysisStatusFinished = "finished" // AnalysisStatusPassed denotes a request for analysis has failed to // run, the message field will have more details AnalysisStatusPassed = "passed" // AnalysisStatusFailed denotes a request for analysis has been // accepted and has failed AnalysisStatusFailed = "failed" // AnalysisStatusAnalyzing denotes a request for analysis has been // accepted and has begun AnalysisStatusAnalyzing = "analyzing" ) const ( // ScannerAnalyzeProjectEndpoint is a string representation of the current endpoint for analyzing project ScannerAnalyzeProjectEndpoint = "v1/scanner/analyzeProject" // ScannerGetAnalysisStatusEndpoint is a string representation of the current endpoint for getting analysis status ScannerGetAnalysisStatusEndpoint = "v1/scanner/getAnalysisStatus" // ScannerGetLatestAnalysisStatusEndpoint is a string representation of the current endpoint for getting latest analysis status ScannerGetLatestAnalysisStatusEndpoint = "v1/scanner/getLatestAnalysisStatus" // ScannerGetLatestAnalysisStatusesEndpoint is a string representation of the current endpoint for getting latest analysis statuses ScannerGetLatestAnalysisStatusesEndpoint = "v1/scanner/getLatestAnalysisStatuses" ) // AnalysisStatus is a representation of an Ion Channel Analysis Status within the system type AnalysisStatus struct { ID string `json:"id"` TeamID string `json:"team_id"` ProjectID string `json:"project_id"` Message string `json:"message"` Branch string `json:"branch"` Status string `json:"status"` UnreachableError bool `json:"unreachable_error"` AnalysisEventSource string `json:"analysis_event_src"` CreatedAt time.Time `json:"created_at"` UpdatedAt time.Time `json:"updated_at"` ScanStatus []ScanStatus `json:"scan_status"` Deliveries map[string]Delivery `json:"deliveries"` } // Done indicates an analyse has stopped processing func (a *AnalysisStatus) Done() bool { return a.Status == AnalysisStatusErrored || a.Status == AnalysisStatusFailed || a.Status == AnalysisStatusFinished } // Navigation represents a navigational meta data reference to given analysis type Navigation struct { Analysis *AnalysisStatus `json:"analysis"` LatestAnalysis *AnalysisStatus `json:"latest_analysis"` }
package camt import ( "encoding/xml" "github.com/thought-machine/finance-messaging/iso20022" ) type Document02600101 struct { XMLName xml.Name `xml:"urn:iso:std:iso:20022:tech:xsd:camt.026.001.01 Document"` Message *UnableToApply `xml:"camt.026.001.01"` } func (d *Document02600101) AddMessage() *UnableToApply { d.Message = new(UnableToApply) return d.Message } // Scope // The Unable To Apply message is sent by a case creator or a case assigner to a case assignee. This message is used to initiate an investigation of a payment instruction that cannot be executed or reconciled. // Usage // The Unable To Apply case occurs in two situations: // - an agent cannot execute the payment instruction due to missing or incorrect information // - a creditor cannot reconcile the payment entry as it is received unexpectedly, or missing or incorrect information prevents reconciliation // The Unable To Apply message: // - always follows the reverse route of the original payment instruction // - must be forwarded to the preceding agents in the payment processing chain, where appropriate // - covers one and only one payment instruction (or payment entry) at a time; if several payment instructions cannot be executed or several payment entries cannot be reconciled, then multiple Unable To Apply messages must be sent. // Depending on what stage the payment is and what has been done to it, for example incorrect routing, errors/omissions when processing the instruction or even the absence of any error, the unable to apply case may lead to a: // - Additional Payment Information message, sent to the case creator/case assigner, if a truncation or omission in a payment instruction prevented reconciliation. // - Request To Cancel Payment message, sent to the subsequent agent in the payment processing chain, if the original payment instruction has been incorrectly routed through the chain of agents (this also entails a new corrected payment instruction being issued). Prior to sending the payment cancellation request, the agent should first send a resolution indicating that a cancellation will follow (CWFW). // - Request To Modify Payment message, sent to the subsequent agent in the payment processing chain, if a truncation or omission has occurred during the processing of the original payment instruction. Prior to sending the modify payment request, the agent should first send a resolution indicating that a modification will follow (MWFW). // - Debit Authorisation Request message, sent to the case creator/case assigner, if the payment instruction has reached an incorrect creditor. type UnableToApply struct { // Identifies the assignment. Assignment *iso20022.CaseAssignment `xml:"Assgnmt"` // Identifies the case. Case *iso20022.Case `xml:"Case"` // References the Payment Instruction that a Party is unable to execute or unable to reconcile. Underlying *iso20022.PaymentInstructionExtract `xml:"Undrlyg"` // Explains the reason why unable to apply. Justification *iso20022.UnableToApplyJustificationChoice `xml:"Justfn"` } func (u *UnableToApply) AddAssignment() *iso20022.CaseAssignment { u.Assignment = new(iso20022.CaseAssignment) return u.Assignment } func (u *UnableToApply) AddCase() *iso20022.Case { u.Case = new(iso20022.Case) return u.Case } func (u *UnableToApply) AddUnderlying() *iso20022.PaymentInstructionExtract { u.Underlying = new(iso20022.PaymentInstructionExtract) return u.Underlying } func (u *UnableToApply) AddJustification() *iso20022.UnableToApplyJustificationChoice { u.Justification = new(iso20022.UnableToApplyJustificationChoice) return u.Justification }
package types // OrderFill represents a filled trade of an order // And order can have multiple fill's before being completely // executed type OrderFill struct { // Price of the fill Price float64 // Quantity filled (in base asset) Quantity float64 // Commission payed Commission float64 // Asset in which the commission is payed CommissionAsset string } // NewOrderFill creates a new OrderFill instance func NewOrderFill(price float64, quantity float64, commission float64, commissionAsset string) (f OrderFill) { f.Price = price f.Quantity = quantity f.Commission = commission f.CommissionAsset = commissionAsset return }
package weight_validation type validation struct { } func NewValidation() *validation { return &validation{} } func (v *validation) GetMessage() map[string]string { return map[string]string { "Number.required": "請輸入體重資料", } } type GetUpdateRule struct { Number float32 `json:"number" form:"number" binding:"required"` } type GetStoreRule struct { Number float32 `json:"number" form:"number" binding:"required"` }
package aggregates import ( "github.com/tmtx/res-sys/app" "github.com/tmtx/res-sys/pkg/bus" "github.com/tmtx/res-sys/pkg/event" "github.com/tmtx/res-sys/pkg/validator" ) type User struct { Base Email string `bson:"email"` HashedPassword string `bson:"hashed_password"` } func (ag *User) GetTargetEvents() []bus.MessageKey { return []bus.MessageKey{ app.UserCreated, app.UserInfoUpdated, } } func (ag *User) HydrateFromParams(params bus.MessageParams) { if email, ok := params["email"].(string); ok { ag.Email = email } if pw, ok := params["hashed_password"].(string); ok { ag.HashedPassword = pw } } func (ag *User) ApplyEvent(e event.Event) { switch e.Key { case app.UserInfoUpdated: fallthrough case app.UserCreated: ag.HydrateFromParams(e.Params) if e.EntityId != nil { ag.Id = e.EntityId } } ag.AppliedEventCount += 1 } func (ag *User) Validate() (bool, *validator.Messages) { if ag.HashedPassword == "" { return false, &validator.Messages{ "hashed_password": []validator.Message{ "empty password", }, } } if ag.AppliedEventCount != uint(len(ag.GetEvents())) { return false, &validator.Messages{ "events": []validator.Message{ "not all events applied", }, } } return true, nil } func (ag *User) CanBeRestored() bool { if ag.Id == nil && ag.Email == "" { return false } return true } func (ag *User) Restore() error { if !ag.CanBeRestored() { return app.TypedError{Type: app.UnableToRestoreAggregate} } if ag.Id != nil { restoredAggregate, err := RestoreFromId(ag) if err != nil { return err } ag = restoredAggregate.(*User) } else if ag.Email != "" { restoredAggregate, err := RestoreFromEmail(ag, ag.Email) if err != nil { return err } ag = restoredAggregate.(*User) } return nil }
package main import ( "SoftwareGoDay2/routes" "SoftwareGoDay2/server" "fmt" ) func main() { s := server.NewServer() routes.ApplyRoutes(s.Router) err := s.Router.Run() // listen and serve on 0.0.0.0:8080 (for windows "localhost:8080") if err != nil { fmt.Println(err) } }
package polynomial import "math/big" var LInt = new(big.Int).SetBytes([]byte{0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x14, 0xde, 0xf9, 0xde, 0xa2, 0xf7, 0x9c, 0xd6, 0x58, 0x12, 0x63, 0x1a, 0x5c, 0xf5, 0xd3, 0xed})
package controllers import ( "context" "strings" "k8s.io/apimachinery/pkg/api/resource" "k8s.io/apimachinery/pkg/util/intstr" gitifold "hyperspike.io/eng/gitifold/api/v1beta1" appsv1 "k8s.io/api/apps/v1" corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/api/errors" "k8s.io/apimachinery/pkg/types" "sigs.k8s.io/controller-runtime/pkg/controller/controllerutil" ) func keydbLabelNames(component string, cr *gitifold.VCS) (string, map[string]string) { labels := map[string]string{ "app.kubernetes.io/name": "keydb", "app.kubernetes.io/component": component, "app.kubernetes.io/deployment": "gitifold", "app.kubernetes.io/instance": cr.Name, } name := strings.Join([]string{cr.Name, component, "gitifold", "keydb"}, "-") return name, labels } func createKeyDBService(component string, cr *gitifold.VCS, r *VCSReconciler) error { logger := r.Log.WithValues("Request.Namespace", cr.Namespace, "Request.Name", cr.Name) svc := newKeyDBServiceCr(component, cr) if err := controllerutil.SetControllerReference(cr, svc, r.Scheme); err != nil { return err } foundSvc := &corev1.Service{} err := r.Client.Get(context.TODO(), types.NamespacedName{Name: svc.Name, Namespace: svc.Namespace}, foundSvc) if err != nil && errors.IsNotFound(err) { logger.Info("Creating a new KeyDB Service") err = r.Client.Create(context.TODO(), svc) if err != nil { return err } } logger.Info("Skip reconcile: KeyDB service already exists") sts := newKeyDBDeploymentCr(component, cr) if err := controllerutil.SetControllerReference(cr, sts, r.Scheme); err != nil { return err } found := &appsv1.Deployment{} err = r.Client.Get(context.TODO(), types.NamespacedName{Name: sts.Name, Namespace: sts.Namespace}, found) if err != nil && errors.IsNotFound(err) { logger.Info("Creating a new Redis Deployment") err = r.Client.Create(context.TODO(), sts) if err != nil { return err } } logger.Info("Skip reconcile: KeyDB Deployment already exists") return nil } func newKeyDBServiceCr(component string, cr *gitifold.VCS) *corev1.Service { name, labels := keydbLabelNames(component, cr) return &corev1.Service{ TypeMeta: metav1.TypeMeta{ APIVersion: "v1", Kind: "Service", }, ObjectMeta: metav1.ObjectMeta{ Name: name, Namespace: cr.Namespace, Labels: labels, Annotations: make(map[string]string), }, Spec: corev1.ServiceSpec{ Selector: labels, Type: "ClusterIP", Ports: []corev1.ServicePort{ { Name: "redis", Protocol: "TCP", Port: 6379, TargetPort: intstr.FromString("redis"), }, }, }, } } func newKeyDBDeploymentCr(component string, cr *gitifold.VCS) *appsv1.Deployment { name, labels := keydbLabelNames(component, cr) limitCpu, _ := resource.ParseQuantity("250m") limitMemory, _ := resource.ParseQuantity("1024Mi") requestCpu, _ := resource.ParseQuantity("10m") requestMemory, _ := resource.ParseQuantity("15Mi") var rc int32 rc = 1 return &appsv1.Deployment{ TypeMeta: metav1.TypeMeta{ Kind: "Deployment", APIVersion: "apps/v1", }, ObjectMeta: metav1.ObjectMeta{ Name: name, Namespace: cr.Namespace, Labels: labels, }, Spec: appsv1.DeploymentSpec{ Replicas: &rc, Selector: &metav1.LabelSelector{ MatchLabels: labels, }, Template: corev1.PodTemplateSpec{ ObjectMeta: metav1.ObjectMeta{ Labels: labels, }, Spec: corev1.PodSpec{ Containers: []corev1.Container{ { Name: "keydb", Image: "eqalpha/keydb:latest", ImagePullPolicy: "Always", Ports: []corev1.ContainerPort{ { Name: "redis", ContainerPort: 6379, Protocol: "TCP", }, }, LivenessProbe: &corev1.Probe{ Handler: corev1.Handler{ Exec: &corev1.ExecAction{ Command: []string{ "sh", "-c", "keydb-cli -h $(hostname) ping", }, }, }, InitialDelaySeconds: int32(8), PeriodSeconds: int32(6), }, ReadinessProbe: &corev1.Probe{ Handler: corev1.Handler{ Exec: &corev1.ExecAction{ Command: []string{ "sh", "-c", "keydb-cli -h $(hostname) ping", }, }, }, InitialDelaySeconds: int32(5), PeriodSeconds: int32(6), }, Resources: corev1.ResourceRequirements{ Limits: corev1.ResourceList{ "cpu": limitCpu, "memory": limitMemory, }, Requests: corev1.ResourceList{ "cpu": requestCpu, "memory": requestMemory, }, }, }, }, }, }, }, } }
package engine import ( "golang.org/x/exp/shiny/driver" "golang.org/x/exp/shiny/screen" "golang.org/x/mobile/event/key" "golang.org/x/mobile/event/lifecycle" "io" "log" "sync" "time" "image" "image/color" "image/draw" _ "image/gif" _ "image/jpeg" _ "image/png" ) // State is the main struct of the engine. It keeps track of pretty // much everything, as well as running the actual game. type State struct { frame int closing chan struct{} rooms map[string]Room room Room s screen.Screen win screen.Window bnds image.Rectangle eventsDone chan struct{} fps *time.Ticker kqpool sync.Pool kqc chan *keyQuery } // NewState initializes a new state. func NewState() *State { kqc := make(chan *keyQuery) return &State{ closing: make(chan struct{}), rooms: make(map[string]Room), kqpool: sync.Pool{ New: func() interface{} { return &keyQuery{ c: kqc, r: make(chan bool), } }, }, kqc: kqc, } } // LoadAnim loads an animation from r with the given frame width. The // width of the image loaded must be evenly divisible by the frame // width. func (s State) LoadAnim(r io.Reader, frameW int) (*Anim, error) { img, _, err := image.Decode(r) if err != nil { return nil, err } buf, err := s.s.NewBuffer(img.Bounds().Size()) if err != nil { return nil, err } defer buf.Release() draw.Draw(buf.RGBA(), buf.Bounds(), img, img.Bounds().Min, draw.Src) tex, err := s.s.NewTexture(buf.Size()) if err != nil { return nil, err } tex.Upload(image.ZP, buf, buf.Bounds()) return newAnim(tex, frameW) } // Draw draws an image onto the screen at the specified point. func (s State) Draw(img Imager, dst image.Point) { image, clip := img.Image() // TODO: According to the race detector, this is causing a data // race. I'm not sure how that's possible, since everything being // dealt with here should only ever be accessed from one thread. // Maybe it's a Shiny bug? s.win.Copy(dst, image, clip, draw.Over, nil) } // Fill fills r with c on the screen. func (s State) Fill(r image.Rectangle, c color.Color) { s.win.Fill(r, c, draw.Over) } // Publish updates the screen. Changes to the screen are not // guarunteed to actually appear until Publish() has been called. func (s State) Publish() { s.win.Publish() } // Bounds returns the screen's bounds. func (s State) Bounds() image.Rectangle { return s.bnds } func (s *State) eventsStart() { // TODO: Rewrite this method to work with the new EventQueue better. // TODO: This causes a potential data race. s.eventsDone = make(chan struct{}) ev := make(chan interface{}) go func() { for { e := s.win.NextEvent() select { case ev <- e: case <-s.eventsDone: return } } }() keys := make(map[key.Code]bool) keysCheck := make(map[key.Code]bool) for { select { case ev := <-ev: switch ev := ev.(type) { case key.Event: keys[ev.Code] = ev.Direction != key.DirRelease case lifecycle.Event: if ev.To == lifecycle.StageDead { close(s.closing) } case error: log.Printf("Event error: %v", ev) } case kq := <-s.kqc: down := keys[kq.code] if !kq.press { kq.r <- keys[kq.code] continue } if down { kq.r <- !keysCheck[kq.code] keysCheck[kq.code] = true } else { kq.r <- false keysCheck[kq.code] = false } case <-s.eventsDone: return } } } func (s *State) eventsStop() { close(s.eventsDone) } // KeyDown returns whether or not a specific key is currently being // held down. func (s *State) KeyDown(code key.Code) bool { // Can you say 'overkill'? kq := s.kqpool.Get().(*keyQuery) defer s.kqpool.Put(kq) return kq.Q(code, false) } // KeyPress returns true the first time it is called after the key // represented by code is pressed, but returns false for that key // until the key is released and then pressed again. func (s *State) KeyPress(code key.Code) bool { kq := s.kqpool.Get().(*keyQuery) defer s.kqpool.Put(kq) return kq.Q(code, true) } // Run starts the game. It blocks until an unrecoverable error occurs // or until the game otherwise exits. // // Before the game enters the mainloop, init is called. If init // returns false, the game exits. init may be nil. func (s *State) Run(opts *StateOptions, init func() bool) (reterr error) { if opts == nil { opts = &DefaultStateOptions } driver.Main(func(scrn screen.Screen) { s.s = scrn win, err := scrn.NewWindow(&screen.NewWindowOptions{ Width: opts.Width, Height: opts.Height, }) if err != nil { reterr = err return } s.win = win s.bnds = image.Rect(0, 0, opts.Width, opts.Height) if (init != nil) && !init() { return } go s.eventsStart() defer s.eventsStop() s.fps = time.NewTicker(time.Second / time.Duration(opts.FPS)) defer s.fps.Stop() for { s.room.Update() s.frame++ select { case <-s.closing: return default: } <-s.fps.C } }) return } // Frame returns the current frame of the game, with 0 being the // initial frame. func (s State) Frame() int { return s.frame } // AddRoom adds a room to the game, or overwrites an existing room if // one named name already exists. func (s *State) AddRoom(name string, room Room) { s.rooms[name] = room } // EnterRoom switches to the room named name, calling its Enter() // method. func (s *State) EnterRoom(name string) { s.room = s.rooms[name] s.room.Enter() } // StateOptions are options for initializing a State. type StateOptions struct { // The width and height of the screen. Width int Height int // The target FPS of the game. // // TODO: Make it possible to remove the FPS cap. FPS int } // DefaultStateOptions are the options used if NewState is passed nil. var DefaultStateOptions = StateOptions{ Width: 640, Height: 480, FPS: 60, } // Room represents a room of the game. This can be almost anything, // from a menu, to a level, to credits. type Room interface { Enter() Update() } // Imager is a type that can represent itself as a piece of a texture. type Imager interface { // Image returns a texture and a clipping rectangle. Image() (screen.Texture, image.Rectangle) } type keyQuery struct { c chan *keyQuery r chan bool code key.Code press bool } func (kq *keyQuery) Q(code key.Code, press bool) bool { kq.code = code kq.press = press kq.c <- kq return <-kq.r }
package snet import ( "io" ) type rewriter struct { data []byte begin int } func (r *rewriter) Push(b []byte) { /* if len(b) >= len(r.data) { copy(r.data, b[len(b)-len(r.data):]) } else { copy(r.data, r.data[len(b):]) copy(r.data[len(r.data)-len(b):], b) } */ for c, n := b, 0; len(c) > 0; c = c[n:] { n = len(r.data) - r.begin if n > len(c) { n = len(c) } copy(r.data[r.begin:], c[:n]) r.begin = (r.begin + n) % len(r.data) } } func (r *rewriter) Rewrite(w io.Writer, writeCount, readCount uint64) bool { n := int(writeCount - readCount) switch { case n == 0: return true case n < 0 || n > len(r.data): return false case int(writeCount) <= len(r.data): _, err := w.Write(r.data[readCount:writeCount]) return err == nil } /* _, err := w.Write(r.data[len(r.data)-n:]) return err == nil */ var ( begin = (r.begin + (len(r.data) - n)) % len(r.data) end = begin + n ) if end > len(r.data) { end = len(r.data) } if _, err := w.Write(r.data[begin:end]); err != nil { return false } n -= end - begin if n == 0 { return true } _, err := w.Write(r.data[:n]) return err == nil }
package models import ( "time" mgo "gopkg.in/mgo.v2" "gopkg.in/mgo.v2/bson" "github.com/ne7ermore/gRBAC/common" "github.com/ne7ermore/gRBAC/plugin" ) type Permission struct { Id bson.ObjectId `bson:"_id,omitempty" json:"id"` Name string `bson:"name" json:"name"` Descrip string `bson:"descrip" json:"descrip"` Sep string `bson:"sep" json:"sep"` CreateTime time.Time `bson:"createTime" json:"createTime"` UpdateTime time.Time `bson:"updateTime,omitempty" json:"updateTime"` } func (p Permission) Getid() string { return p.Id.Hex() } func (p Permission) GetName() string { return p.Name } func (p Permission) GetDescrip() string { return p.Descrip } func (p Permission) GetSep() string { return p.Sep } func (p Permission) GetCreateTime() time.Time { return p.CreateTime } func (p Permission) GetUpdateTime() time.Time { return p.UpdateTime } type PermissionColl struct { *mgo.Collection } func (s *Store) GetPermissionPools() plugin.PermissionPools { coll := NewMongodbColl(s.auth, s.perm) return plugin.PermissionPools(&PermissionColl{coll}) } func (p *PermissionColl) Gather() ([]plugin.Permission, error) { ps := []*Permission{} if err := p.Find(nil).All(&ps); err != nil { return nil, err } pps := make([]plugin.Permission, 0, len(ps)) for _, p := range ps { pps = append(pps, plugin.Permission(p)) } return pps, nil } func (p *PermissionColl) New(name, des string) (string, error) { id := bson.NewObjectId() if err := p.Insert(Permission{ Id: id, Name: name, Descrip: des, Sep: common.FirstSep, CreateTime: time.Now(), UpdateTime: time.Now(), }); err != nil { return "", err } return id.Hex(), nil } func (p *PermissionColl) Get(id string) (plugin.Permission, error) { if !bson.IsObjectIdHex(id) { return nil, common.ErrInvalidMongoId } mp := new(Permission) if err := p.Find(bson.M{"_id": bson.ObjectIdHex(id)}).One(mp); err != nil { return nil, err } return plugin.Permission(mp), nil } func (p *PermissionColl) GetByDesc(descrip string) (plugin.Permission, error) { mp := new(Permission) if err := p.Find(bson.M{"descrip": descrip}).One(mp); err != nil { return nil, err } return plugin.Permission(mp), nil } func (p *PermissionColl) Update(id string, update map[string]string) error { if !bson.IsObjectIdHex(id) { return common.ErrInvalidMongoId } updateParams := bson.M{} for k, v := range update { updateParams[k] = v } updateParams["updateTime"] = time.Now() if err := p.UpdateId(bson.ObjectIdHex(id), bson.M{ "$set": updateParams, }); err != nil { return err } return nil } func (p *PermissionColl) Gets(skip, limit int, field string) ([]plugin.Permission, error) { ps := make([]*Permission, 0, limit) if err := p.Find(bson.M{}).Limit(limit).Skip(skip).Sort(field).All(&ps); err != nil { return nil, err } pps := make([]plugin.Permission, 0, limit) for _, p := range ps { pps = append(pps, plugin.Permission(p)) } return pps, nil } func (p *PermissionColl) Close() { p.Database.Session.Close() } func (p *PermissionColl) Counts() int { c, _ := p.Count() return c }
// Copyright 2015 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 codec import ( "testing" "github.com/pingcap/tidb/types" "github.com/stretchr/testify/require" ) func TestDecimalCodec(t *testing.T) { inputs := []struct { Input float64 }{ {float64(123400)}, {float64(1234)}, {float64(12.34)}, {float64(0.1234)}, {float64(0.01234)}, {float64(-0.1234)}, {float64(-0.01234)}, {float64(12.3400)}, {float64(-12.34)}, {float64(0.00000)}, {float64(0)}, {float64(-0.0)}, {float64(-0.000)}, } for _, input := range inputs { v := types.NewDecFromFloatForTest(input.Input) datum := types.NewDatum(v) b, err := EncodeDecimal([]byte{}, datum.GetMysqlDecimal(), datum.Length(), datum.Frac()) require.NoError(t, err) _, d, prec, frac, err := DecodeDecimal(b) if datum.Length() != 0 { require.Equal(t, datum.Length(), prec) require.Equal(t, datum.Frac(), frac) } else { prec1, frac1 := datum.GetMysqlDecimal().PrecisionAndFrac() require.Equal(t, prec1, prec) require.Equal(t, frac1, frac) } require.NoError(t, err) require.Equal(t, 0, v.Compare(d)) } } func TestFrac(t *testing.T) { inputs := []struct { Input *types.MyDecimal }{ {types.NewDecFromInt(3)}, {types.NewDecFromFloatForTest(0.03)}, } for _, v := range inputs { var datum types.Datum datum.SetMysqlDecimal(v.Input) b, err := EncodeDecimal([]byte{}, datum.GetMysqlDecimal(), datum.Length(), datum.Frac()) require.NoError(t, err) _, dec, _, _, err := DecodeDecimal(b) require.NoError(t, err) require.Equal(t, v.Input.String(), dec.String()) } }
package services import ( "interface-testing/api/domain/weather_domain" "interface-testing/api/providers/weather_provider" "net/http" "testing" "github.com/stretchr/testify/assert" ) var ( getWeatherProviderFunc func(request weather_domain.WeatherRequest) (*weather_domain.Weather, *weather_domain.WeatherError) ) type getProviderMock struct{} func (c *getProviderMock) GetWeather(request weather_domain.WeatherRequest) (*weather_domain.Weather, *weather_domain.WeatherError) { return getWeatherProviderFunc(request) } func TestWeatherServiceNoAuthKey(t *testing.T) { getWeatherProviderFunc = func(request weather_domain.WeatherRequest) (*weather_domain.Weather, *weather_domain.WeatherError) { return nil, &weather_domain.WeatherError{ Code: 403, ErrorMessage: "permission denied", } } weather_provider.WeatherProvider = &getProviderMock{} //without this line, the real api is fired request := weather_domain.WeatherRequest{ApiKey: "wrong_key", Latitude: 44.3601, Longitude: -71.0589} result, err := WeatherService.GetWeather(request) assert.Nil(t, result) assert.NotNil(t, err) assert.EqualValues(t, http.StatusForbidden, err.Status()) assert.EqualValues(t, "permission denied", err.Message()) } func TestWeatherServiceWrongLatitude(t *testing.T) { getWeatherProviderFunc = func(request weather_domain.WeatherRequest) (*weather_domain.Weather, *weather_domain.WeatherError) { return nil, &weather_domain.WeatherError{ Code: 400, ErrorMessage: "The given location is invalid", } } weather_provider.WeatherProvider = &getProviderMock{} //without this line, the real api is fired request := weather_domain.WeatherRequest{ApiKey: "api_key", Latitude: 123443, Longitude: -71.0589} result, err := WeatherService.GetWeather(request) assert.Nil(t, result) assert.NotNil(t, err) assert.EqualValues(t, http.StatusBadRequest, err.Status()) assert.EqualValues(t, "The given location is invalid", err.Message()) } func TestWeatherServiceWrongLongitude(t *testing.T) { getWeatherProviderFunc = func(request weather_domain.WeatherRequest) (*weather_domain.Weather, *weather_domain.WeatherError) { return nil, &weather_domain.WeatherError{ Code: 400, ErrorMessage: "The given location is invalid", } } weather_provider.WeatherProvider = &getProviderMock{} //without this line, the real api is fired request := weather_domain.WeatherRequest{ApiKey: "api_key", Latitude: 39.12, Longitude: 122332} result, err := WeatherService.GetWeather(request) assert.Nil(t, result) assert.NotNil(t, err) assert.EqualValues(t, http.StatusBadRequest, err.Status()) assert.EqualValues(t, "The given location is invalid", err.Message()) } func TestWeatherServiceSuccess(t *testing.T) { getWeatherProviderFunc = func(request weather_domain.WeatherRequest) (*weather_domain.Weather, *weather_domain.WeatherError) { return &weather_domain.Weather{ Latitude: 39.12, Longitude: 49.12, TimeZone: "America/New_York", Currently: weather_domain.CurrentlyInfo{ Temperature: 40.22, Summary: "Clear", DewPoint: 50.22, Pressure: 12.90, Humidity: 16.54, }, }, nil } weather_provider.WeatherProvider = &getProviderMock{} //without this line, the real api is fired request := weather_domain.WeatherRequest{ApiKey: "api_key", Latitude: 39.12, Longitude: 49.12} result, err := WeatherService.GetWeather(request) assert.NotNil(t, result) assert.Nil(t, err) assert.EqualValues(t, 39.12, result.Latitude) assert.EqualValues(t, 49.12, result.Longitude) assert.EqualValues(t, "America/New_York", result.TimeZone) assert.EqualValues(t, "Clear", result.Currently.Summary) assert.EqualValues(t, 40.22, result.Currently.Temperature) assert.EqualValues(t, 50.22, result.Currently.DewPoint) assert.EqualValues(t, 12.90, result.Currently.Pressure) assert.EqualValues(t, 16.54, result.Currently.Humidity) }
package x // GENERATED BY XO. DO NOT EDIT. import ( "errors" "strings" //"time" "ms/sun/shared/helper" "strconv" "github.com/jmoiron/sqlx" ) // (shortname .TableNameGo "err" "res" "sqlstr" "db" "XOLog") -}}//(schema .Schema .Table.TableName) -}}// .TableNameGo}}// SettingNotifications represents a row from 'sun.setting_notifications'. // Manualy copy this to project type SettingNotifications__ struct { UserId int `json:"UserId"` // UserId - SocialLedOn int `json:"SocialLedOn"` // SocialLedOn - SocialLedColor string `json:"SocialLedColor"` // SocialLedColor - ReqestToFollowYou int `json:"ReqestToFollowYou"` // ReqestToFollowYou - FollowedYou int `json:"FollowedYou"` // FollowedYou - AccptedYourFollowRequest int `json:"AccptedYourFollowRequest"` // AccptedYourFollowRequest - YourPostLiked int `json:"YourPostLiked"` // YourPostLiked - YourPostCommented int `json:"YourPostCommented"` // YourPostCommented - MenthenedYouInPost int `json:"MenthenedYouInPost"` // MenthenedYouInPost - MenthenedYouInComment int `json:"MenthenedYouInComment"` // MenthenedYouInComment - YourContactsJoined int `json:"YourContactsJoined"` // YourContactsJoined - DirectMessage int `json:"DirectMessage"` // DirectMessage - DirectAlert int `json:"DirectAlert"` // DirectAlert - DirectPerview int `json:"DirectPerview"` // DirectPerview - DirectLedOn int `json:"DirectLedOn"` // DirectLedOn - DirectLedColor int `json:"DirectLedColor"` // DirectLedColor - DirectVibrate int `json:"DirectVibrate"` // DirectVibrate - DirectPopup int `json:"DirectPopup"` // DirectPopup - DirectSound int `json:"DirectSound"` // DirectSound - DirectPriority int `json:"DirectPriority"` // DirectPriority - // xo fields _exists, _deleted bool } // Exists determines if the SettingNotifications exists in the database. func (sn *SettingNotifications) Exists() bool { return sn._exists } // Deleted provides information if the SettingNotifications has been deleted from the database. func (sn *SettingNotifications) Deleted() bool { return sn._deleted } // Insert inserts the SettingNotifications to the database. func (sn *SettingNotifications) Insert(db XODB) error { var err error // if already exist, bail if sn._exists { return errors.New("insert failed: already exists") } // sql insert query, primary key must be provided const sqlstr = `INSERT INTO sun.setting_notifications (` + `UserId, SocialLedOn, SocialLedColor, ReqestToFollowYou, FollowedYou, AccptedYourFollowRequest, YourPostLiked, YourPostCommented, MenthenedYouInPost, MenthenedYouInComment, YourContactsJoined, DirectMessage, DirectAlert, DirectPerview, DirectLedOn, DirectLedColor, DirectVibrate, DirectPopup, DirectSound, DirectPriority` + `) VALUES (` + `?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?` + `)` // run query if LogTableSqlReq.SettingNotifications { XOLog(sqlstr, sn.UserId, sn.SocialLedOn, sn.SocialLedColor, sn.ReqestToFollowYou, sn.FollowedYou, sn.AccptedYourFollowRequest, sn.YourPostLiked, sn.YourPostCommented, sn.MenthenedYouInPost, sn.MenthenedYouInComment, sn.YourContactsJoined, sn.DirectMessage, sn.DirectAlert, sn.DirectPerview, sn.DirectLedOn, sn.DirectLedColor, sn.DirectVibrate, sn.DirectPopup, sn.DirectSound, sn.DirectPriority) } _, err = db.Exec(sqlstr, sn.UserId, sn.SocialLedOn, sn.SocialLedColor, sn.ReqestToFollowYou, sn.FollowedYou, sn.AccptedYourFollowRequest, sn.YourPostLiked, sn.YourPostCommented, sn.MenthenedYouInPost, sn.MenthenedYouInComment, sn.YourContactsJoined, sn.DirectMessage, sn.DirectAlert, sn.DirectPerview, sn.DirectLedOn, sn.DirectLedColor, sn.DirectVibrate, sn.DirectPopup, sn.DirectSound, sn.DirectPriority) if err != nil { return err } // set existence sn._exists = true OnSettingNotifications_AfterInsert(sn) return nil } // Insert inserts the SettingNotifications to the database. func (sn *SettingNotifications) Replace(db XODB) error { var err error // sql query const sqlstr = `REPLACE INTO sun.setting_notifications (` + `UserId, SocialLedOn, SocialLedColor, ReqestToFollowYou, FollowedYou, AccptedYourFollowRequest, YourPostLiked, YourPostCommented, MenthenedYouInPost, MenthenedYouInComment, YourContactsJoined, DirectMessage, DirectAlert, DirectPerview, DirectLedOn, DirectLedColor, DirectVibrate, DirectPopup, DirectSound, DirectPriority` + `) VALUES (` + `?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?` + `)` // run query if LogTableSqlReq.SettingNotifications { XOLog(sqlstr, sn.UserId, sn.SocialLedOn, sn.SocialLedColor, sn.ReqestToFollowYou, sn.FollowedYou, sn.AccptedYourFollowRequest, sn.YourPostLiked, sn.YourPostCommented, sn.MenthenedYouInPost, sn.MenthenedYouInComment, sn.YourContactsJoined, sn.DirectMessage, sn.DirectAlert, sn.DirectPerview, sn.DirectLedOn, sn.DirectLedColor, sn.DirectVibrate, sn.DirectPopup, sn.DirectSound, sn.DirectPriority) } _, err = db.Exec(sqlstr, sn.UserId, sn.SocialLedOn, sn.SocialLedColor, sn.ReqestToFollowYou, sn.FollowedYou, sn.AccptedYourFollowRequest, sn.YourPostLiked, sn.YourPostCommented, sn.MenthenedYouInPost, sn.MenthenedYouInComment, sn.YourContactsJoined, sn.DirectMessage, sn.DirectAlert, sn.DirectPerview, sn.DirectLedOn, sn.DirectLedColor, sn.DirectVibrate, sn.DirectPopup, sn.DirectSound, sn.DirectPriority) if err != nil { if LogTableSqlReq.SettingNotifications { XOLogErr(err) } return err } sn._exists = true OnSettingNotifications_AfterInsert(sn) return nil } // Update updates the SettingNotifications in the database. func (sn *SettingNotifications) Update(db XODB) error { var err error // if doesn't exist, bail if !sn._exists { return errors.New("update failed: does not exist") } // if deleted, bail if sn._deleted { return errors.New("update failed: marked for deletion") } // sql query const sqlstr = `UPDATE sun.setting_notifications SET ` + `SocialLedOn = ?, SocialLedColor = ?, ReqestToFollowYou = ?, FollowedYou = ?, AccptedYourFollowRequest = ?, YourPostLiked = ?, YourPostCommented = ?, MenthenedYouInPost = ?, MenthenedYouInComment = ?, YourContactsJoined = ?, DirectMessage = ?, DirectAlert = ?, DirectPerview = ?, DirectLedOn = ?, DirectLedColor = ?, DirectVibrate = ?, DirectPopup = ?, DirectSound = ?, DirectPriority = ?` + ` WHERE UserId = ?` // run query if LogTableSqlReq.SettingNotifications { XOLog(sqlstr, sn.SocialLedOn, sn.SocialLedColor, sn.ReqestToFollowYou, sn.FollowedYou, sn.AccptedYourFollowRequest, sn.YourPostLiked, sn.YourPostCommented, sn.MenthenedYouInPost, sn.MenthenedYouInComment, sn.YourContactsJoined, sn.DirectMessage, sn.DirectAlert, sn.DirectPerview, sn.DirectLedOn, sn.DirectLedColor, sn.DirectVibrate, sn.DirectPopup, sn.DirectSound, sn.DirectPriority, sn.UserId) } _, err = db.Exec(sqlstr, sn.SocialLedOn, sn.SocialLedColor, sn.ReqestToFollowYou, sn.FollowedYou, sn.AccptedYourFollowRequest, sn.YourPostLiked, sn.YourPostCommented, sn.MenthenedYouInPost, sn.MenthenedYouInComment, sn.YourContactsJoined, sn.DirectMessage, sn.DirectAlert, sn.DirectPerview, sn.DirectLedOn, sn.DirectLedColor, sn.DirectVibrate, sn.DirectPopup, sn.DirectSound, sn.DirectPriority, sn.UserId) if LogTableSqlReq.SettingNotifications { XOLogErr(err) } OnSettingNotifications_AfterUpdate(sn) return err } // Save saves the SettingNotifications to the database. func (sn *SettingNotifications) Save(db XODB) error { if sn.Exists() { return sn.Update(db) } return sn.Replace(db) } // Delete deletes the SettingNotifications from the database. func (sn *SettingNotifications) Delete(db XODB) error { var err error // if doesn't exist, bail if !sn._exists { return nil } // if deleted, bail if sn._deleted { return nil } // sql query const sqlstr = `DELETE FROM sun.setting_notifications WHERE UserId = ?` // run query if LogTableSqlReq.SettingNotifications { XOLog(sqlstr, sn.UserId) } _, err = db.Exec(sqlstr, sn.UserId) if err != nil { if LogTableSqlReq.SettingNotifications { XOLogErr(err) } return err } // set deleted sn._deleted = true OnSettingNotifications_AfterDelete(sn) return nil } //////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////// Querify gen - ME ///////////////////////////////////////// //.TableNameGo= table name // _Deleter, _Updater // orma types type __SettingNotifications_Deleter struct { wheres []whereClause whereSep string dollarIndex int isMysql bool } type __SettingNotifications_Updater struct { wheres []whereClause // updates map[string]interface{} updates []updateCol whereSep string dollarIndex int isMysql bool } type __SettingNotifications_Selector struct { wheres []whereClause selectCol string whereSep string orderBy string //" order by id desc //for ints limit int offset int dollarIndex int isMysql bool } func NewSettingNotifications_Deleter() *__SettingNotifications_Deleter { d := __SettingNotifications_Deleter{whereSep: " AND ", isMysql: true} return &d } func NewSettingNotifications_Updater() *__SettingNotifications_Updater { u := __SettingNotifications_Updater{whereSep: " AND ", isMysql: true} //u.updates = make(map[string]interface{},10) return &u } func NewSettingNotifications_Selector() *__SettingNotifications_Selector { u := __SettingNotifications_Selector{whereSep: " AND ", selectCol: "*", isMysql: true} return &u } /*/// mysql or cockroach ? or $1 handlers func (m *__SettingNotifications_Selector)nextDollars(size int) string { r := DollarsForSqlIn(size,m.dollarIndex,m.isMysql) m.dollarIndex += size return r } func (m *__SettingNotifications_Selector)nextDollar() string { r := DollarsForSqlIn(1,m.dollarIndex,m.isMysql) m.dollarIndex += 1 return r } */ /////////////////////////////// Where for all ///////////////////////////// //// for ints all selector updater, deleter /// mysql or cockroach ? or $1 handlers func (m *__SettingNotifications_Deleter) nextDollars(size int) string { r := DollarsForSqlIn(size, m.dollarIndex, m.isMysql) m.dollarIndex += size return r } func (m *__SettingNotifications_Deleter) nextDollar() string { r := DollarsForSqlIn(1, m.dollarIndex, m.isMysql) m.dollarIndex += 1 return r } ////////ints func (u *__SettingNotifications_Deleter) Or() *__SettingNotifications_Deleter { u.whereSep = " OR " return u } func (u *__SettingNotifications_Deleter) UserId_In(ins []int) *__SettingNotifications_Deleter { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " UserId IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (u *__SettingNotifications_Deleter) UserId_Ins(ins ...int) *__SettingNotifications_Deleter { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " UserId IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (u *__SettingNotifications_Deleter) UserId_NotIn(ins []int) *__SettingNotifications_Deleter { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " UserId NOT IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (d *__SettingNotifications_Deleter) UserId_Eq(val int) *__SettingNotifications_Deleter { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " UserId = " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Deleter) UserId_NotEq(val int) *__SettingNotifications_Deleter { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " UserId != " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Deleter) UserId_LT(val int) *__SettingNotifications_Deleter { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " UserId < " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Deleter) UserId_LE(val int) *__SettingNotifications_Deleter { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " UserId <= " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Deleter) UserId_GT(val int) *__SettingNotifications_Deleter { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " UserId > " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Deleter) UserId_GE(val int) *__SettingNotifications_Deleter { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " UserId >= " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (u *__SettingNotifications_Deleter) SocialLedOn_In(ins []int) *__SettingNotifications_Deleter { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " SocialLedOn IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (u *__SettingNotifications_Deleter) SocialLedOn_Ins(ins ...int) *__SettingNotifications_Deleter { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " SocialLedOn IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (u *__SettingNotifications_Deleter) SocialLedOn_NotIn(ins []int) *__SettingNotifications_Deleter { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " SocialLedOn NOT IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (d *__SettingNotifications_Deleter) SocialLedOn_Eq(val int) *__SettingNotifications_Deleter { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " SocialLedOn = " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Deleter) SocialLedOn_NotEq(val int) *__SettingNotifications_Deleter { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " SocialLedOn != " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Deleter) SocialLedOn_LT(val int) *__SettingNotifications_Deleter { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " SocialLedOn < " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Deleter) SocialLedOn_LE(val int) *__SettingNotifications_Deleter { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " SocialLedOn <= " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Deleter) SocialLedOn_GT(val int) *__SettingNotifications_Deleter { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " SocialLedOn > " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Deleter) SocialLedOn_GE(val int) *__SettingNotifications_Deleter { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " SocialLedOn >= " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (u *__SettingNotifications_Deleter) ReqestToFollowYou_In(ins []int) *__SettingNotifications_Deleter { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " ReqestToFollowYou IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (u *__SettingNotifications_Deleter) ReqestToFollowYou_Ins(ins ...int) *__SettingNotifications_Deleter { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " ReqestToFollowYou IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (u *__SettingNotifications_Deleter) ReqestToFollowYou_NotIn(ins []int) *__SettingNotifications_Deleter { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " ReqestToFollowYou NOT IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (d *__SettingNotifications_Deleter) ReqestToFollowYou_Eq(val int) *__SettingNotifications_Deleter { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " ReqestToFollowYou = " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Deleter) ReqestToFollowYou_NotEq(val int) *__SettingNotifications_Deleter { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " ReqestToFollowYou != " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Deleter) ReqestToFollowYou_LT(val int) *__SettingNotifications_Deleter { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " ReqestToFollowYou < " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Deleter) ReqestToFollowYou_LE(val int) *__SettingNotifications_Deleter { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " ReqestToFollowYou <= " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Deleter) ReqestToFollowYou_GT(val int) *__SettingNotifications_Deleter { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " ReqestToFollowYou > " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Deleter) ReqestToFollowYou_GE(val int) *__SettingNotifications_Deleter { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " ReqestToFollowYou >= " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (u *__SettingNotifications_Deleter) FollowedYou_In(ins []int) *__SettingNotifications_Deleter { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " FollowedYou IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (u *__SettingNotifications_Deleter) FollowedYou_Ins(ins ...int) *__SettingNotifications_Deleter { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " FollowedYou IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (u *__SettingNotifications_Deleter) FollowedYou_NotIn(ins []int) *__SettingNotifications_Deleter { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " FollowedYou NOT IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (d *__SettingNotifications_Deleter) FollowedYou_Eq(val int) *__SettingNotifications_Deleter { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " FollowedYou = " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Deleter) FollowedYou_NotEq(val int) *__SettingNotifications_Deleter { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " FollowedYou != " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Deleter) FollowedYou_LT(val int) *__SettingNotifications_Deleter { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " FollowedYou < " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Deleter) FollowedYou_LE(val int) *__SettingNotifications_Deleter { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " FollowedYou <= " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Deleter) FollowedYou_GT(val int) *__SettingNotifications_Deleter { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " FollowedYou > " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Deleter) FollowedYou_GE(val int) *__SettingNotifications_Deleter { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " FollowedYou >= " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (u *__SettingNotifications_Deleter) AccptedYourFollowRequest_In(ins []int) *__SettingNotifications_Deleter { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " AccptedYourFollowRequest IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (u *__SettingNotifications_Deleter) AccptedYourFollowRequest_Ins(ins ...int) *__SettingNotifications_Deleter { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " AccptedYourFollowRequest IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (u *__SettingNotifications_Deleter) AccptedYourFollowRequest_NotIn(ins []int) *__SettingNotifications_Deleter { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " AccptedYourFollowRequest NOT IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (d *__SettingNotifications_Deleter) AccptedYourFollowRequest_Eq(val int) *__SettingNotifications_Deleter { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " AccptedYourFollowRequest = " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Deleter) AccptedYourFollowRequest_NotEq(val int) *__SettingNotifications_Deleter { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " AccptedYourFollowRequest != " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Deleter) AccptedYourFollowRequest_LT(val int) *__SettingNotifications_Deleter { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " AccptedYourFollowRequest < " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Deleter) AccptedYourFollowRequest_LE(val int) *__SettingNotifications_Deleter { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " AccptedYourFollowRequest <= " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Deleter) AccptedYourFollowRequest_GT(val int) *__SettingNotifications_Deleter { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " AccptedYourFollowRequest > " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Deleter) AccptedYourFollowRequest_GE(val int) *__SettingNotifications_Deleter { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " AccptedYourFollowRequest >= " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (u *__SettingNotifications_Deleter) YourPostLiked_In(ins []int) *__SettingNotifications_Deleter { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " YourPostLiked IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (u *__SettingNotifications_Deleter) YourPostLiked_Ins(ins ...int) *__SettingNotifications_Deleter { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " YourPostLiked IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (u *__SettingNotifications_Deleter) YourPostLiked_NotIn(ins []int) *__SettingNotifications_Deleter { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " YourPostLiked NOT IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (d *__SettingNotifications_Deleter) YourPostLiked_Eq(val int) *__SettingNotifications_Deleter { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " YourPostLiked = " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Deleter) YourPostLiked_NotEq(val int) *__SettingNotifications_Deleter { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " YourPostLiked != " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Deleter) YourPostLiked_LT(val int) *__SettingNotifications_Deleter { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " YourPostLiked < " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Deleter) YourPostLiked_LE(val int) *__SettingNotifications_Deleter { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " YourPostLiked <= " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Deleter) YourPostLiked_GT(val int) *__SettingNotifications_Deleter { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " YourPostLiked > " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Deleter) YourPostLiked_GE(val int) *__SettingNotifications_Deleter { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " YourPostLiked >= " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (u *__SettingNotifications_Deleter) YourPostCommented_In(ins []int) *__SettingNotifications_Deleter { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " YourPostCommented IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (u *__SettingNotifications_Deleter) YourPostCommented_Ins(ins ...int) *__SettingNotifications_Deleter { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " YourPostCommented IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (u *__SettingNotifications_Deleter) YourPostCommented_NotIn(ins []int) *__SettingNotifications_Deleter { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " YourPostCommented NOT IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (d *__SettingNotifications_Deleter) YourPostCommented_Eq(val int) *__SettingNotifications_Deleter { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " YourPostCommented = " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Deleter) YourPostCommented_NotEq(val int) *__SettingNotifications_Deleter { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " YourPostCommented != " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Deleter) YourPostCommented_LT(val int) *__SettingNotifications_Deleter { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " YourPostCommented < " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Deleter) YourPostCommented_LE(val int) *__SettingNotifications_Deleter { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " YourPostCommented <= " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Deleter) YourPostCommented_GT(val int) *__SettingNotifications_Deleter { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " YourPostCommented > " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Deleter) YourPostCommented_GE(val int) *__SettingNotifications_Deleter { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " YourPostCommented >= " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (u *__SettingNotifications_Deleter) MenthenedYouInPost_In(ins []int) *__SettingNotifications_Deleter { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " MenthenedYouInPost IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (u *__SettingNotifications_Deleter) MenthenedYouInPost_Ins(ins ...int) *__SettingNotifications_Deleter { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " MenthenedYouInPost IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (u *__SettingNotifications_Deleter) MenthenedYouInPost_NotIn(ins []int) *__SettingNotifications_Deleter { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " MenthenedYouInPost NOT IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (d *__SettingNotifications_Deleter) MenthenedYouInPost_Eq(val int) *__SettingNotifications_Deleter { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " MenthenedYouInPost = " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Deleter) MenthenedYouInPost_NotEq(val int) *__SettingNotifications_Deleter { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " MenthenedYouInPost != " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Deleter) MenthenedYouInPost_LT(val int) *__SettingNotifications_Deleter { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " MenthenedYouInPost < " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Deleter) MenthenedYouInPost_LE(val int) *__SettingNotifications_Deleter { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " MenthenedYouInPost <= " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Deleter) MenthenedYouInPost_GT(val int) *__SettingNotifications_Deleter { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " MenthenedYouInPost > " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Deleter) MenthenedYouInPost_GE(val int) *__SettingNotifications_Deleter { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " MenthenedYouInPost >= " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (u *__SettingNotifications_Deleter) MenthenedYouInComment_In(ins []int) *__SettingNotifications_Deleter { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " MenthenedYouInComment IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (u *__SettingNotifications_Deleter) MenthenedYouInComment_Ins(ins ...int) *__SettingNotifications_Deleter { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " MenthenedYouInComment IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (u *__SettingNotifications_Deleter) MenthenedYouInComment_NotIn(ins []int) *__SettingNotifications_Deleter { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " MenthenedYouInComment NOT IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (d *__SettingNotifications_Deleter) MenthenedYouInComment_Eq(val int) *__SettingNotifications_Deleter { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " MenthenedYouInComment = " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Deleter) MenthenedYouInComment_NotEq(val int) *__SettingNotifications_Deleter { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " MenthenedYouInComment != " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Deleter) MenthenedYouInComment_LT(val int) *__SettingNotifications_Deleter { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " MenthenedYouInComment < " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Deleter) MenthenedYouInComment_LE(val int) *__SettingNotifications_Deleter { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " MenthenedYouInComment <= " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Deleter) MenthenedYouInComment_GT(val int) *__SettingNotifications_Deleter { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " MenthenedYouInComment > " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Deleter) MenthenedYouInComment_GE(val int) *__SettingNotifications_Deleter { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " MenthenedYouInComment >= " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (u *__SettingNotifications_Deleter) YourContactsJoined_In(ins []int) *__SettingNotifications_Deleter { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " YourContactsJoined IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (u *__SettingNotifications_Deleter) YourContactsJoined_Ins(ins ...int) *__SettingNotifications_Deleter { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " YourContactsJoined IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (u *__SettingNotifications_Deleter) YourContactsJoined_NotIn(ins []int) *__SettingNotifications_Deleter { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " YourContactsJoined NOT IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (d *__SettingNotifications_Deleter) YourContactsJoined_Eq(val int) *__SettingNotifications_Deleter { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " YourContactsJoined = " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Deleter) YourContactsJoined_NotEq(val int) *__SettingNotifications_Deleter { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " YourContactsJoined != " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Deleter) YourContactsJoined_LT(val int) *__SettingNotifications_Deleter { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " YourContactsJoined < " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Deleter) YourContactsJoined_LE(val int) *__SettingNotifications_Deleter { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " YourContactsJoined <= " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Deleter) YourContactsJoined_GT(val int) *__SettingNotifications_Deleter { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " YourContactsJoined > " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Deleter) YourContactsJoined_GE(val int) *__SettingNotifications_Deleter { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " YourContactsJoined >= " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (u *__SettingNotifications_Deleter) DirectMessage_In(ins []int) *__SettingNotifications_Deleter { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " DirectMessage IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (u *__SettingNotifications_Deleter) DirectMessage_Ins(ins ...int) *__SettingNotifications_Deleter { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " DirectMessage IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (u *__SettingNotifications_Deleter) DirectMessage_NotIn(ins []int) *__SettingNotifications_Deleter { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " DirectMessage NOT IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (d *__SettingNotifications_Deleter) DirectMessage_Eq(val int) *__SettingNotifications_Deleter { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " DirectMessage = " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Deleter) DirectMessage_NotEq(val int) *__SettingNotifications_Deleter { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " DirectMessage != " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Deleter) DirectMessage_LT(val int) *__SettingNotifications_Deleter { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " DirectMessage < " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Deleter) DirectMessage_LE(val int) *__SettingNotifications_Deleter { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " DirectMessage <= " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Deleter) DirectMessage_GT(val int) *__SettingNotifications_Deleter { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " DirectMessage > " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Deleter) DirectMessage_GE(val int) *__SettingNotifications_Deleter { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " DirectMessage >= " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (u *__SettingNotifications_Deleter) DirectAlert_In(ins []int) *__SettingNotifications_Deleter { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " DirectAlert IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (u *__SettingNotifications_Deleter) DirectAlert_Ins(ins ...int) *__SettingNotifications_Deleter { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " DirectAlert IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (u *__SettingNotifications_Deleter) DirectAlert_NotIn(ins []int) *__SettingNotifications_Deleter { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " DirectAlert NOT IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (d *__SettingNotifications_Deleter) DirectAlert_Eq(val int) *__SettingNotifications_Deleter { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " DirectAlert = " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Deleter) DirectAlert_NotEq(val int) *__SettingNotifications_Deleter { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " DirectAlert != " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Deleter) DirectAlert_LT(val int) *__SettingNotifications_Deleter { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " DirectAlert < " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Deleter) DirectAlert_LE(val int) *__SettingNotifications_Deleter { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " DirectAlert <= " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Deleter) DirectAlert_GT(val int) *__SettingNotifications_Deleter { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " DirectAlert > " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Deleter) DirectAlert_GE(val int) *__SettingNotifications_Deleter { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " DirectAlert >= " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (u *__SettingNotifications_Deleter) DirectPerview_In(ins []int) *__SettingNotifications_Deleter { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " DirectPerview IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (u *__SettingNotifications_Deleter) DirectPerview_Ins(ins ...int) *__SettingNotifications_Deleter { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " DirectPerview IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (u *__SettingNotifications_Deleter) DirectPerview_NotIn(ins []int) *__SettingNotifications_Deleter { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " DirectPerview NOT IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (d *__SettingNotifications_Deleter) DirectPerview_Eq(val int) *__SettingNotifications_Deleter { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " DirectPerview = " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Deleter) DirectPerview_NotEq(val int) *__SettingNotifications_Deleter { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " DirectPerview != " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Deleter) DirectPerview_LT(val int) *__SettingNotifications_Deleter { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " DirectPerview < " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Deleter) DirectPerview_LE(val int) *__SettingNotifications_Deleter { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " DirectPerview <= " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Deleter) DirectPerview_GT(val int) *__SettingNotifications_Deleter { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " DirectPerview > " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Deleter) DirectPerview_GE(val int) *__SettingNotifications_Deleter { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " DirectPerview >= " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (u *__SettingNotifications_Deleter) DirectLedOn_In(ins []int) *__SettingNotifications_Deleter { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " DirectLedOn IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (u *__SettingNotifications_Deleter) DirectLedOn_Ins(ins ...int) *__SettingNotifications_Deleter { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " DirectLedOn IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (u *__SettingNotifications_Deleter) DirectLedOn_NotIn(ins []int) *__SettingNotifications_Deleter { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " DirectLedOn NOT IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (d *__SettingNotifications_Deleter) DirectLedOn_Eq(val int) *__SettingNotifications_Deleter { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " DirectLedOn = " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Deleter) DirectLedOn_NotEq(val int) *__SettingNotifications_Deleter { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " DirectLedOn != " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Deleter) DirectLedOn_LT(val int) *__SettingNotifications_Deleter { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " DirectLedOn < " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Deleter) DirectLedOn_LE(val int) *__SettingNotifications_Deleter { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " DirectLedOn <= " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Deleter) DirectLedOn_GT(val int) *__SettingNotifications_Deleter { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " DirectLedOn > " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Deleter) DirectLedOn_GE(val int) *__SettingNotifications_Deleter { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " DirectLedOn >= " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (u *__SettingNotifications_Deleter) DirectLedColor_In(ins []int) *__SettingNotifications_Deleter { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " DirectLedColor IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (u *__SettingNotifications_Deleter) DirectLedColor_Ins(ins ...int) *__SettingNotifications_Deleter { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " DirectLedColor IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (u *__SettingNotifications_Deleter) DirectLedColor_NotIn(ins []int) *__SettingNotifications_Deleter { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " DirectLedColor NOT IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (d *__SettingNotifications_Deleter) DirectLedColor_Eq(val int) *__SettingNotifications_Deleter { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " DirectLedColor = " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Deleter) DirectLedColor_NotEq(val int) *__SettingNotifications_Deleter { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " DirectLedColor != " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Deleter) DirectLedColor_LT(val int) *__SettingNotifications_Deleter { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " DirectLedColor < " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Deleter) DirectLedColor_LE(val int) *__SettingNotifications_Deleter { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " DirectLedColor <= " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Deleter) DirectLedColor_GT(val int) *__SettingNotifications_Deleter { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " DirectLedColor > " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Deleter) DirectLedColor_GE(val int) *__SettingNotifications_Deleter { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " DirectLedColor >= " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (u *__SettingNotifications_Deleter) DirectVibrate_In(ins []int) *__SettingNotifications_Deleter { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " DirectVibrate IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (u *__SettingNotifications_Deleter) DirectVibrate_Ins(ins ...int) *__SettingNotifications_Deleter { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " DirectVibrate IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (u *__SettingNotifications_Deleter) DirectVibrate_NotIn(ins []int) *__SettingNotifications_Deleter { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " DirectVibrate NOT IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (d *__SettingNotifications_Deleter) DirectVibrate_Eq(val int) *__SettingNotifications_Deleter { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " DirectVibrate = " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Deleter) DirectVibrate_NotEq(val int) *__SettingNotifications_Deleter { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " DirectVibrate != " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Deleter) DirectVibrate_LT(val int) *__SettingNotifications_Deleter { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " DirectVibrate < " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Deleter) DirectVibrate_LE(val int) *__SettingNotifications_Deleter { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " DirectVibrate <= " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Deleter) DirectVibrate_GT(val int) *__SettingNotifications_Deleter { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " DirectVibrate > " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Deleter) DirectVibrate_GE(val int) *__SettingNotifications_Deleter { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " DirectVibrate >= " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (u *__SettingNotifications_Deleter) DirectPopup_In(ins []int) *__SettingNotifications_Deleter { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " DirectPopup IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (u *__SettingNotifications_Deleter) DirectPopup_Ins(ins ...int) *__SettingNotifications_Deleter { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " DirectPopup IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (u *__SettingNotifications_Deleter) DirectPopup_NotIn(ins []int) *__SettingNotifications_Deleter { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " DirectPopup NOT IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (d *__SettingNotifications_Deleter) DirectPopup_Eq(val int) *__SettingNotifications_Deleter { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " DirectPopup = " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Deleter) DirectPopup_NotEq(val int) *__SettingNotifications_Deleter { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " DirectPopup != " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Deleter) DirectPopup_LT(val int) *__SettingNotifications_Deleter { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " DirectPopup < " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Deleter) DirectPopup_LE(val int) *__SettingNotifications_Deleter { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " DirectPopup <= " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Deleter) DirectPopup_GT(val int) *__SettingNotifications_Deleter { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " DirectPopup > " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Deleter) DirectPopup_GE(val int) *__SettingNotifications_Deleter { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " DirectPopup >= " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (u *__SettingNotifications_Deleter) DirectSound_In(ins []int) *__SettingNotifications_Deleter { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " DirectSound IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (u *__SettingNotifications_Deleter) DirectSound_Ins(ins ...int) *__SettingNotifications_Deleter { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " DirectSound IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (u *__SettingNotifications_Deleter) DirectSound_NotIn(ins []int) *__SettingNotifications_Deleter { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " DirectSound NOT IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (d *__SettingNotifications_Deleter) DirectSound_Eq(val int) *__SettingNotifications_Deleter { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " DirectSound = " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Deleter) DirectSound_NotEq(val int) *__SettingNotifications_Deleter { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " DirectSound != " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Deleter) DirectSound_LT(val int) *__SettingNotifications_Deleter { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " DirectSound < " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Deleter) DirectSound_LE(val int) *__SettingNotifications_Deleter { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " DirectSound <= " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Deleter) DirectSound_GT(val int) *__SettingNotifications_Deleter { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " DirectSound > " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Deleter) DirectSound_GE(val int) *__SettingNotifications_Deleter { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " DirectSound >= " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (u *__SettingNotifications_Deleter) DirectPriority_In(ins []int) *__SettingNotifications_Deleter { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " DirectPriority IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (u *__SettingNotifications_Deleter) DirectPriority_Ins(ins ...int) *__SettingNotifications_Deleter { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " DirectPriority IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (u *__SettingNotifications_Deleter) DirectPriority_NotIn(ins []int) *__SettingNotifications_Deleter { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " DirectPriority NOT IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (d *__SettingNotifications_Deleter) DirectPriority_Eq(val int) *__SettingNotifications_Deleter { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " DirectPriority = " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Deleter) DirectPriority_NotEq(val int) *__SettingNotifications_Deleter { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " DirectPriority != " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Deleter) DirectPriority_LT(val int) *__SettingNotifications_Deleter { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " DirectPriority < " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Deleter) DirectPriority_LE(val int) *__SettingNotifications_Deleter { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " DirectPriority <= " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Deleter) DirectPriority_GT(val int) *__SettingNotifications_Deleter { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " DirectPriority > " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Deleter) DirectPriority_GE(val int) *__SettingNotifications_Deleter { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " DirectPriority >= " + d.nextDollar() d.wheres = append(d.wheres, w) return d } /// mysql or cockroach ? or $1 handlers func (m *__SettingNotifications_Updater) nextDollars(size int) string { r := DollarsForSqlIn(size, m.dollarIndex, m.isMysql) m.dollarIndex += size return r } func (m *__SettingNotifications_Updater) nextDollar() string { r := DollarsForSqlIn(1, m.dollarIndex, m.isMysql) m.dollarIndex += 1 return r } ////////ints func (u *__SettingNotifications_Updater) Or() *__SettingNotifications_Updater { u.whereSep = " OR " return u } func (u *__SettingNotifications_Updater) UserId_In(ins []int) *__SettingNotifications_Updater { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " UserId IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (u *__SettingNotifications_Updater) UserId_Ins(ins ...int) *__SettingNotifications_Updater { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " UserId IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (u *__SettingNotifications_Updater) UserId_NotIn(ins []int) *__SettingNotifications_Updater { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " UserId NOT IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (d *__SettingNotifications_Updater) UserId_Eq(val int) *__SettingNotifications_Updater { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " UserId = " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Updater) UserId_NotEq(val int) *__SettingNotifications_Updater { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " UserId != " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Updater) UserId_LT(val int) *__SettingNotifications_Updater { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " UserId < " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Updater) UserId_LE(val int) *__SettingNotifications_Updater { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " UserId <= " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Updater) UserId_GT(val int) *__SettingNotifications_Updater { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " UserId > " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Updater) UserId_GE(val int) *__SettingNotifications_Updater { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " UserId >= " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (u *__SettingNotifications_Updater) SocialLedOn_In(ins []int) *__SettingNotifications_Updater { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " SocialLedOn IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (u *__SettingNotifications_Updater) SocialLedOn_Ins(ins ...int) *__SettingNotifications_Updater { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " SocialLedOn IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (u *__SettingNotifications_Updater) SocialLedOn_NotIn(ins []int) *__SettingNotifications_Updater { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " SocialLedOn NOT IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (d *__SettingNotifications_Updater) SocialLedOn_Eq(val int) *__SettingNotifications_Updater { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " SocialLedOn = " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Updater) SocialLedOn_NotEq(val int) *__SettingNotifications_Updater { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " SocialLedOn != " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Updater) SocialLedOn_LT(val int) *__SettingNotifications_Updater { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " SocialLedOn < " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Updater) SocialLedOn_LE(val int) *__SettingNotifications_Updater { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " SocialLedOn <= " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Updater) SocialLedOn_GT(val int) *__SettingNotifications_Updater { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " SocialLedOn > " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Updater) SocialLedOn_GE(val int) *__SettingNotifications_Updater { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " SocialLedOn >= " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (u *__SettingNotifications_Updater) ReqestToFollowYou_In(ins []int) *__SettingNotifications_Updater { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " ReqestToFollowYou IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (u *__SettingNotifications_Updater) ReqestToFollowYou_Ins(ins ...int) *__SettingNotifications_Updater { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " ReqestToFollowYou IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (u *__SettingNotifications_Updater) ReqestToFollowYou_NotIn(ins []int) *__SettingNotifications_Updater { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " ReqestToFollowYou NOT IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (d *__SettingNotifications_Updater) ReqestToFollowYou_Eq(val int) *__SettingNotifications_Updater { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " ReqestToFollowYou = " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Updater) ReqestToFollowYou_NotEq(val int) *__SettingNotifications_Updater { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " ReqestToFollowYou != " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Updater) ReqestToFollowYou_LT(val int) *__SettingNotifications_Updater { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " ReqestToFollowYou < " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Updater) ReqestToFollowYou_LE(val int) *__SettingNotifications_Updater { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " ReqestToFollowYou <= " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Updater) ReqestToFollowYou_GT(val int) *__SettingNotifications_Updater { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " ReqestToFollowYou > " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Updater) ReqestToFollowYou_GE(val int) *__SettingNotifications_Updater { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " ReqestToFollowYou >= " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (u *__SettingNotifications_Updater) FollowedYou_In(ins []int) *__SettingNotifications_Updater { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " FollowedYou IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (u *__SettingNotifications_Updater) FollowedYou_Ins(ins ...int) *__SettingNotifications_Updater { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " FollowedYou IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (u *__SettingNotifications_Updater) FollowedYou_NotIn(ins []int) *__SettingNotifications_Updater { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " FollowedYou NOT IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (d *__SettingNotifications_Updater) FollowedYou_Eq(val int) *__SettingNotifications_Updater { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " FollowedYou = " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Updater) FollowedYou_NotEq(val int) *__SettingNotifications_Updater { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " FollowedYou != " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Updater) FollowedYou_LT(val int) *__SettingNotifications_Updater { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " FollowedYou < " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Updater) FollowedYou_LE(val int) *__SettingNotifications_Updater { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " FollowedYou <= " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Updater) FollowedYou_GT(val int) *__SettingNotifications_Updater { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " FollowedYou > " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Updater) FollowedYou_GE(val int) *__SettingNotifications_Updater { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " FollowedYou >= " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (u *__SettingNotifications_Updater) AccptedYourFollowRequest_In(ins []int) *__SettingNotifications_Updater { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " AccptedYourFollowRequest IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (u *__SettingNotifications_Updater) AccptedYourFollowRequest_Ins(ins ...int) *__SettingNotifications_Updater { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " AccptedYourFollowRequest IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (u *__SettingNotifications_Updater) AccptedYourFollowRequest_NotIn(ins []int) *__SettingNotifications_Updater { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " AccptedYourFollowRequest NOT IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (d *__SettingNotifications_Updater) AccptedYourFollowRequest_Eq(val int) *__SettingNotifications_Updater { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " AccptedYourFollowRequest = " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Updater) AccptedYourFollowRequest_NotEq(val int) *__SettingNotifications_Updater { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " AccptedYourFollowRequest != " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Updater) AccptedYourFollowRequest_LT(val int) *__SettingNotifications_Updater { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " AccptedYourFollowRequest < " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Updater) AccptedYourFollowRequest_LE(val int) *__SettingNotifications_Updater { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " AccptedYourFollowRequest <= " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Updater) AccptedYourFollowRequest_GT(val int) *__SettingNotifications_Updater { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " AccptedYourFollowRequest > " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Updater) AccptedYourFollowRequest_GE(val int) *__SettingNotifications_Updater { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " AccptedYourFollowRequest >= " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (u *__SettingNotifications_Updater) YourPostLiked_In(ins []int) *__SettingNotifications_Updater { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " YourPostLiked IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (u *__SettingNotifications_Updater) YourPostLiked_Ins(ins ...int) *__SettingNotifications_Updater { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " YourPostLiked IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (u *__SettingNotifications_Updater) YourPostLiked_NotIn(ins []int) *__SettingNotifications_Updater { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " YourPostLiked NOT IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (d *__SettingNotifications_Updater) YourPostLiked_Eq(val int) *__SettingNotifications_Updater { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " YourPostLiked = " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Updater) YourPostLiked_NotEq(val int) *__SettingNotifications_Updater { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " YourPostLiked != " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Updater) YourPostLiked_LT(val int) *__SettingNotifications_Updater { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " YourPostLiked < " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Updater) YourPostLiked_LE(val int) *__SettingNotifications_Updater { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " YourPostLiked <= " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Updater) YourPostLiked_GT(val int) *__SettingNotifications_Updater { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " YourPostLiked > " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Updater) YourPostLiked_GE(val int) *__SettingNotifications_Updater { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " YourPostLiked >= " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (u *__SettingNotifications_Updater) YourPostCommented_In(ins []int) *__SettingNotifications_Updater { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " YourPostCommented IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (u *__SettingNotifications_Updater) YourPostCommented_Ins(ins ...int) *__SettingNotifications_Updater { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " YourPostCommented IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (u *__SettingNotifications_Updater) YourPostCommented_NotIn(ins []int) *__SettingNotifications_Updater { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " YourPostCommented NOT IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (d *__SettingNotifications_Updater) YourPostCommented_Eq(val int) *__SettingNotifications_Updater { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " YourPostCommented = " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Updater) YourPostCommented_NotEq(val int) *__SettingNotifications_Updater { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " YourPostCommented != " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Updater) YourPostCommented_LT(val int) *__SettingNotifications_Updater { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " YourPostCommented < " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Updater) YourPostCommented_LE(val int) *__SettingNotifications_Updater { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " YourPostCommented <= " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Updater) YourPostCommented_GT(val int) *__SettingNotifications_Updater { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " YourPostCommented > " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Updater) YourPostCommented_GE(val int) *__SettingNotifications_Updater { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " YourPostCommented >= " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (u *__SettingNotifications_Updater) MenthenedYouInPost_In(ins []int) *__SettingNotifications_Updater { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " MenthenedYouInPost IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (u *__SettingNotifications_Updater) MenthenedYouInPost_Ins(ins ...int) *__SettingNotifications_Updater { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " MenthenedYouInPost IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (u *__SettingNotifications_Updater) MenthenedYouInPost_NotIn(ins []int) *__SettingNotifications_Updater { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " MenthenedYouInPost NOT IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (d *__SettingNotifications_Updater) MenthenedYouInPost_Eq(val int) *__SettingNotifications_Updater { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " MenthenedYouInPost = " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Updater) MenthenedYouInPost_NotEq(val int) *__SettingNotifications_Updater { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " MenthenedYouInPost != " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Updater) MenthenedYouInPost_LT(val int) *__SettingNotifications_Updater { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " MenthenedYouInPost < " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Updater) MenthenedYouInPost_LE(val int) *__SettingNotifications_Updater { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " MenthenedYouInPost <= " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Updater) MenthenedYouInPost_GT(val int) *__SettingNotifications_Updater { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " MenthenedYouInPost > " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Updater) MenthenedYouInPost_GE(val int) *__SettingNotifications_Updater { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " MenthenedYouInPost >= " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (u *__SettingNotifications_Updater) MenthenedYouInComment_In(ins []int) *__SettingNotifications_Updater { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " MenthenedYouInComment IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (u *__SettingNotifications_Updater) MenthenedYouInComment_Ins(ins ...int) *__SettingNotifications_Updater { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " MenthenedYouInComment IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (u *__SettingNotifications_Updater) MenthenedYouInComment_NotIn(ins []int) *__SettingNotifications_Updater { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " MenthenedYouInComment NOT IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (d *__SettingNotifications_Updater) MenthenedYouInComment_Eq(val int) *__SettingNotifications_Updater { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " MenthenedYouInComment = " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Updater) MenthenedYouInComment_NotEq(val int) *__SettingNotifications_Updater { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " MenthenedYouInComment != " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Updater) MenthenedYouInComment_LT(val int) *__SettingNotifications_Updater { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " MenthenedYouInComment < " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Updater) MenthenedYouInComment_LE(val int) *__SettingNotifications_Updater { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " MenthenedYouInComment <= " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Updater) MenthenedYouInComment_GT(val int) *__SettingNotifications_Updater { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " MenthenedYouInComment > " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Updater) MenthenedYouInComment_GE(val int) *__SettingNotifications_Updater { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " MenthenedYouInComment >= " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (u *__SettingNotifications_Updater) YourContactsJoined_In(ins []int) *__SettingNotifications_Updater { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " YourContactsJoined IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (u *__SettingNotifications_Updater) YourContactsJoined_Ins(ins ...int) *__SettingNotifications_Updater { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " YourContactsJoined IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (u *__SettingNotifications_Updater) YourContactsJoined_NotIn(ins []int) *__SettingNotifications_Updater { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " YourContactsJoined NOT IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (d *__SettingNotifications_Updater) YourContactsJoined_Eq(val int) *__SettingNotifications_Updater { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " YourContactsJoined = " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Updater) YourContactsJoined_NotEq(val int) *__SettingNotifications_Updater { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " YourContactsJoined != " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Updater) YourContactsJoined_LT(val int) *__SettingNotifications_Updater { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " YourContactsJoined < " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Updater) YourContactsJoined_LE(val int) *__SettingNotifications_Updater { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " YourContactsJoined <= " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Updater) YourContactsJoined_GT(val int) *__SettingNotifications_Updater { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " YourContactsJoined > " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Updater) YourContactsJoined_GE(val int) *__SettingNotifications_Updater { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " YourContactsJoined >= " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (u *__SettingNotifications_Updater) DirectMessage_In(ins []int) *__SettingNotifications_Updater { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " DirectMessage IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (u *__SettingNotifications_Updater) DirectMessage_Ins(ins ...int) *__SettingNotifications_Updater { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " DirectMessage IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (u *__SettingNotifications_Updater) DirectMessage_NotIn(ins []int) *__SettingNotifications_Updater { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " DirectMessage NOT IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (d *__SettingNotifications_Updater) DirectMessage_Eq(val int) *__SettingNotifications_Updater { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " DirectMessage = " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Updater) DirectMessage_NotEq(val int) *__SettingNotifications_Updater { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " DirectMessage != " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Updater) DirectMessage_LT(val int) *__SettingNotifications_Updater { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " DirectMessage < " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Updater) DirectMessage_LE(val int) *__SettingNotifications_Updater { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " DirectMessage <= " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Updater) DirectMessage_GT(val int) *__SettingNotifications_Updater { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " DirectMessage > " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Updater) DirectMessage_GE(val int) *__SettingNotifications_Updater { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " DirectMessage >= " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (u *__SettingNotifications_Updater) DirectAlert_In(ins []int) *__SettingNotifications_Updater { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " DirectAlert IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (u *__SettingNotifications_Updater) DirectAlert_Ins(ins ...int) *__SettingNotifications_Updater { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " DirectAlert IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (u *__SettingNotifications_Updater) DirectAlert_NotIn(ins []int) *__SettingNotifications_Updater { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " DirectAlert NOT IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (d *__SettingNotifications_Updater) DirectAlert_Eq(val int) *__SettingNotifications_Updater { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " DirectAlert = " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Updater) DirectAlert_NotEq(val int) *__SettingNotifications_Updater { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " DirectAlert != " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Updater) DirectAlert_LT(val int) *__SettingNotifications_Updater { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " DirectAlert < " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Updater) DirectAlert_LE(val int) *__SettingNotifications_Updater { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " DirectAlert <= " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Updater) DirectAlert_GT(val int) *__SettingNotifications_Updater { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " DirectAlert > " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Updater) DirectAlert_GE(val int) *__SettingNotifications_Updater { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " DirectAlert >= " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (u *__SettingNotifications_Updater) DirectPerview_In(ins []int) *__SettingNotifications_Updater { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " DirectPerview IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (u *__SettingNotifications_Updater) DirectPerview_Ins(ins ...int) *__SettingNotifications_Updater { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " DirectPerview IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (u *__SettingNotifications_Updater) DirectPerview_NotIn(ins []int) *__SettingNotifications_Updater { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " DirectPerview NOT IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (d *__SettingNotifications_Updater) DirectPerview_Eq(val int) *__SettingNotifications_Updater { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " DirectPerview = " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Updater) DirectPerview_NotEq(val int) *__SettingNotifications_Updater { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " DirectPerview != " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Updater) DirectPerview_LT(val int) *__SettingNotifications_Updater { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " DirectPerview < " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Updater) DirectPerview_LE(val int) *__SettingNotifications_Updater { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " DirectPerview <= " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Updater) DirectPerview_GT(val int) *__SettingNotifications_Updater { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " DirectPerview > " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Updater) DirectPerview_GE(val int) *__SettingNotifications_Updater { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " DirectPerview >= " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (u *__SettingNotifications_Updater) DirectLedOn_In(ins []int) *__SettingNotifications_Updater { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " DirectLedOn IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (u *__SettingNotifications_Updater) DirectLedOn_Ins(ins ...int) *__SettingNotifications_Updater { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " DirectLedOn IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (u *__SettingNotifications_Updater) DirectLedOn_NotIn(ins []int) *__SettingNotifications_Updater { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " DirectLedOn NOT IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (d *__SettingNotifications_Updater) DirectLedOn_Eq(val int) *__SettingNotifications_Updater { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " DirectLedOn = " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Updater) DirectLedOn_NotEq(val int) *__SettingNotifications_Updater { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " DirectLedOn != " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Updater) DirectLedOn_LT(val int) *__SettingNotifications_Updater { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " DirectLedOn < " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Updater) DirectLedOn_LE(val int) *__SettingNotifications_Updater { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " DirectLedOn <= " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Updater) DirectLedOn_GT(val int) *__SettingNotifications_Updater { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " DirectLedOn > " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Updater) DirectLedOn_GE(val int) *__SettingNotifications_Updater { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " DirectLedOn >= " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (u *__SettingNotifications_Updater) DirectLedColor_In(ins []int) *__SettingNotifications_Updater { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " DirectLedColor IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (u *__SettingNotifications_Updater) DirectLedColor_Ins(ins ...int) *__SettingNotifications_Updater { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " DirectLedColor IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (u *__SettingNotifications_Updater) DirectLedColor_NotIn(ins []int) *__SettingNotifications_Updater { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " DirectLedColor NOT IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (d *__SettingNotifications_Updater) DirectLedColor_Eq(val int) *__SettingNotifications_Updater { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " DirectLedColor = " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Updater) DirectLedColor_NotEq(val int) *__SettingNotifications_Updater { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " DirectLedColor != " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Updater) DirectLedColor_LT(val int) *__SettingNotifications_Updater { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " DirectLedColor < " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Updater) DirectLedColor_LE(val int) *__SettingNotifications_Updater { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " DirectLedColor <= " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Updater) DirectLedColor_GT(val int) *__SettingNotifications_Updater { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " DirectLedColor > " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Updater) DirectLedColor_GE(val int) *__SettingNotifications_Updater { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " DirectLedColor >= " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (u *__SettingNotifications_Updater) DirectVibrate_In(ins []int) *__SettingNotifications_Updater { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " DirectVibrate IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (u *__SettingNotifications_Updater) DirectVibrate_Ins(ins ...int) *__SettingNotifications_Updater { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " DirectVibrate IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (u *__SettingNotifications_Updater) DirectVibrate_NotIn(ins []int) *__SettingNotifications_Updater { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " DirectVibrate NOT IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (d *__SettingNotifications_Updater) DirectVibrate_Eq(val int) *__SettingNotifications_Updater { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " DirectVibrate = " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Updater) DirectVibrate_NotEq(val int) *__SettingNotifications_Updater { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " DirectVibrate != " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Updater) DirectVibrate_LT(val int) *__SettingNotifications_Updater { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " DirectVibrate < " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Updater) DirectVibrate_LE(val int) *__SettingNotifications_Updater { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " DirectVibrate <= " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Updater) DirectVibrate_GT(val int) *__SettingNotifications_Updater { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " DirectVibrate > " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Updater) DirectVibrate_GE(val int) *__SettingNotifications_Updater { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " DirectVibrate >= " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (u *__SettingNotifications_Updater) DirectPopup_In(ins []int) *__SettingNotifications_Updater { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " DirectPopup IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (u *__SettingNotifications_Updater) DirectPopup_Ins(ins ...int) *__SettingNotifications_Updater { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " DirectPopup IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (u *__SettingNotifications_Updater) DirectPopup_NotIn(ins []int) *__SettingNotifications_Updater { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " DirectPopup NOT IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (d *__SettingNotifications_Updater) DirectPopup_Eq(val int) *__SettingNotifications_Updater { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " DirectPopup = " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Updater) DirectPopup_NotEq(val int) *__SettingNotifications_Updater { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " DirectPopup != " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Updater) DirectPopup_LT(val int) *__SettingNotifications_Updater { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " DirectPopup < " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Updater) DirectPopup_LE(val int) *__SettingNotifications_Updater { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " DirectPopup <= " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Updater) DirectPopup_GT(val int) *__SettingNotifications_Updater { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " DirectPopup > " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Updater) DirectPopup_GE(val int) *__SettingNotifications_Updater { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " DirectPopup >= " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (u *__SettingNotifications_Updater) DirectSound_In(ins []int) *__SettingNotifications_Updater { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " DirectSound IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (u *__SettingNotifications_Updater) DirectSound_Ins(ins ...int) *__SettingNotifications_Updater { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " DirectSound IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (u *__SettingNotifications_Updater) DirectSound_NotIn(ins []int) *__SettingNotifications_Updater { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " DirectSound NOT IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (d *__SettingNotifications_Updater) DirectSound_Eq(val int) *__SettingNotifications_Updater { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " DirectSound = " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Updater) DirectSound_NotEq(val int) *__SettingNotifications_Updater { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " DirectSound != " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Updater) DirectSound_LT(val int) *__SettingNotifications_Updater { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " DirectSound < " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Updater) DirectSound_LE(val int) *__SettingNotifications_Updater { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " DirectSound <= " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Updater) DirectSound_GT(val int) *__SettingNotifications_Updater { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " DirectSound > " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Updater) DirectSound_GE(val int) *__SettingNotifications_Updater { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " DirectSound >= " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (u *__SettingNotifications_Updater) DirectPriority_In(ins []int) *__SettingNotifications_Updater { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " DirectPriority IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (u *__SettingNotifications_Updater) DirectPriority_Ins(ins ...int) *__SettingNotifications_Updater { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " DirectPriority IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (u *__SettingNotifications_Updater) DirectPriority_NotIn(ins []int) *__SettingNotifications_Updater { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " DirectPriority NOT IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (d *__SettingNotifications_Updater) DirectPriority_Eq(val int) *__SettingNotifications_Updater { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " DirectPriority = " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Updater) DirectPriority_NotEq(val int) *__SettingNotifications_Updater { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " DirectPriority != " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Updater) DirectPriority_LT(val int) *__SettingNotifications_Updater { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " DirectPriority < " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Updater) DirectPriority_LE(val int) *__SettingNotifications_Updater { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " DirectPriority <= " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Updater) DirectPriority_GT(val int) *__SettingNotifications_Updater { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " DirectPriority > " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Updater) DirectPriority_GE(val int) *__SettingNotifications_Updater { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " DirectPriority >= " + d.nextDollar() d.wheres = append(d.wheres, w) return d } /// mysql or cockroach ? or $1 handlers func (m *__SettingNotifications_Selector) nextDollars(size int) string { r := DollarsForSqlIn(size, m.dollarIndex, m.isMysql) m.dollarIndex += size return r } func (m *__SettingNotifications_Selector) nextDollar() string { r := DollarsForSqlIn(1, m.dollarIndex, m.isMysql) m.dollarIndex += 1 return r } ////////ints func (u *__SettingNotifications_Selector) Or() *__SettingNotifications_Selector { u.whereSep = " OR " return u } func (u *__SettingNotifications_Selector) UserId_In(ins []int) *__SettingNotifications_Selector { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " UserId IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (u *__SettingNotifications_Selector) UserId_Ins(ins ...int) *__SettingNotifications_Selector { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " UserId IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (u *__SettingNotifications_Selector) UserId_NotIn(ins []int) *__SettingNotifications_Selector { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " UserId NOT IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (d *__SettingNotifications_Selector) UserId_Eq(val int) *__SettingNotifications_Selector { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " UserId = " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Selector) UserId_NotEq(val int) *__SettingNotifications_Selector { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " UserId != " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Selector) UserId_LT(val int) *__SettingNotifications_Selector { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " UserId < " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Selector) UserId_LE(val int) *__SettingNotifications_Selector { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " UserId <= " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Selector) UserId_GT(val int) *__SettingNotifications_Selector { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " UserId > " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Selector) UserId_GE(val int) *__SettingNotifications_Selector { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " UserId >= " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (u *__SettingNotifications_Selector) SocialLedOn_In(ins []int) *__SettingNotifications_Selector { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " SocialLedOn IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (u *__SettingNotifications_Selector) SocialLedOn_Ins(ins ...int) *__SettingNotifications_Selector { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " SocialLedOn IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (u *__SettingNotifications_Selector) SocialLedOn_NotIn(ins []int) *__SettingNotifications_Selector { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " SocialLedOn NOT IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (d *__SettingNotifications_Selector) SocialLedOn_Eq(val int) *__SettingNotifications_Selector { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " SocialLedOn = " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Selector) SocialLedOn_NotEq(val int) *__SettingNotifications_Selector { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " SocialLedOn != " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Selector) SocialLedOn_LT(val int) *__SettingNotifications_Selector { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " SocialLedOn < " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Selector) SocialLedOn_LE(val int) *__SettingNotifications_Selector { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " SocialLedOn <= " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Selector) SocialLedOn_GT(val int) *__SettingNotifications_Selector { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " SocialLedOn > " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Selector) SocialLedOn_GE(val int) *__SettingNotifications_Selector { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " SocialLedOn >= " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (u *__SettingNotifications_Selector) ReqestToFollowYou_In(ins []int) *__SettingNotifications_Selector { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " ReqestToFollowYou IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (u *__SettingNotifications_Selector) ReqestToFollowYou_Ins(ins ...int) *__SettingNotifications_Selector { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " ReqestToFollowYou IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (u *__SettingNotifications_Selector) ReqestToFollowYou_NotIn(ins []int) *__SettingNotifications_Selector { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " ReqestToFollowYou NOT IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (d *__SettingNotifications_Selector) ReqestToFollowYou_Eq(val int) *__SettingNotifications_Selector { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " ReqestToFollowYou = " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Selector) ReqestToFollowYou_NotEq(val int) *__SettingNotifications_Selector { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " ReqestToFollowYou != " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Selector) ReqestToFollowYou_LT(val int) *__SettingNotifications_Selector { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " ReqestToFollowYou < " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Selector) ReqestToFollowYou_LE(val int) *__SettingNotifications_Selector { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " ReqestToFollowYou <= " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Selector) ReqestToFollowYou_GT(val int) *__SettingNotifications_Selector { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " ReqestToFollowYou > " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Selector) ReqestToFollowYou_GE(val int) *__SettingNotifications_Selector { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " ReqestToFollowYou >= " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (u *__SettingNotifications_Selector) FollowedYou_In(ins []int) *__SettingNotifications_Selector { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " FollowedYou IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (u *__SettingNotifications_Selector) FollowedYou_Ins(ins ...int) *__SettingNotifications_Selector { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " FollowedYou IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (u *__SettingNotifications_Selector) FollowedYou_NotIn(ins []int) *__SettingNotifications_Selector { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " FollowedYou NOT IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (d *__SettingNotifications_Selector) FollowedYou_Eq(val int) *__SettingNotifications_Selector { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " FollowedYou = " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Selector) FollowedYou_NotEq(val int) *__SettingNotifications_Selector { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " FollowedYou != " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Selector) FollowedYou_LT(val int) *__SettingNotifications_Selector { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " FollowedYou < " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Selector) FollowedYou_LE(val int) *__SettingNotifications_Selector { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " FollowedYou <= " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Selector) FollowedYou_GT(val int) *__SettingNotifications_Selector { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " FollowedYou > " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Selector) FollowedYou_GE(val int) *__SettingNotifications_Selector { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " FollowedYou >= " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (u *__SettingNotifications_Selector) AccptedYourFollowRequest_In(ins []int) *__SettingNotifications_Selector { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " AccptedYourFollowRequest IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (u *__SettingNotifications_Selector) AccptedYourFollowRequest_Ins(ins ...int) *__SettingNotifications_Selector { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " AccptedYourFollowRequest IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (u *__SettingNotifications_Selector) AccptedYourFollowRequest_NotIn(ins []int) *__SettingNotifications_Selector { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " AccptedYourFollowRequest NOT IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (d *__SettingNotifications_Selector) AccptedYourFollowRequest_Eq(val int) *__SettingNotifications_Selector { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " AccptedYourFollowRequest = " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Selector) AccptedYourFollowRequest_NotEq(val int) *__SettingNotifications_Selector { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " AccptedYourFollowRequest != " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Selector) AccptedYourFollowRequest_LT(val int) *__SettingNotifications_Selector { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " AccptedYourFollowRequest < " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Selector) AccptedYourFollowRequest_LE(val int) *__SettingNotifications_Selector { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " AccptedYourFollowRequest <= " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Selector) AccptedYourFollowRequest_GT(val int) *__SettingNotifications_Selector { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " AccptedYourFollowRequest > " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Selector) AccptedYourFollowRequest_GE(val int) *__SettingNotifications_Selector { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " AccptedYourFollowRequest >= " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (u *__SettingNotifications_Selector) YourPostLiked_In(ins []int) *__SettingNotifications_Selector { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " YourPostLiked IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (u *__SettingNotifications_Selector) YourPostLiked_Ins(ins ...int) *__SettingNotifications_Selector { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " YourPostLiked IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (u *__SettingNotifications_Selector) YourPostLiked_NotIn(ins []int) *__SettingNotifications_Selector { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " YourPostLiked NOT IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (d *__SettingNotifications_Selector) YourPostLiked_Eq(val int) *__SettingNotifications_Selector { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " YourPostLiked = " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Selector) YourPostLiked_NotEq(val int) *__SettingNotifications_Selector { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " YourPostLiked != " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Selector) YourPostLiked_LT(val int) *__SettingNotifications_Selector { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " YourPostLiked < " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Selector) YourPostLiked_LE(val int) *__SettingNotifications_Selector { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " YourPostLiked <= " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Selector) YourPostLiked_GT(val int) *__SettingNotifications_Selector { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " YourPostLiked > " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Selector) YourPostLiked_GE(val int) *__SettingNotifications_Selector { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " YourPostLiked >= " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (u *__SettingNotifications_Selector) YourPostCommented_In(ins []int) *__SettingNotifications_Selector { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " YourPostCommented IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (u *__SettingNotifications_Selector) YourPostCommented_Ins(ins ...int) *__SettingNotifications_Selector { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " YourPostCommented IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (u *__SettingNotifications_Selector) YourPostCommented_NotIn(ins []int) *__SettingNotifications_Selector { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " YourPostCommented NOT IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (d *__SettingNotifications_Selector) YourPostCommented_Eq(val int) *__SettingNotifications_Selector { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " YourPostCommented = " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Selector) YourPostCommented_NotEq(val int) *__SettingNotifications_Selector { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " YourPostCommented != " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Selector) YourPostCommented_LT(val int) *__SettingNotifications_Selector { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " YourPostCommented < " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Selector) YourPostCommented_LE(val int) *__SettingNotifications_Selector { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " YourPostCommented <= " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Selector) YourPostCommented_GT(val int) *__SettingNotifications_Selector { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " YourPostCommented > " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Selector) YourPostCommented_GE(val int) *__SettingNotifications_Selector { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " YourPostCommented >= " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (u *__SettingNotifications_Selector) MenthenedYouInPost_In(ins []int) *__SettingNotifications_Selector { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " MenthenedYouInPost IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (u *__SettingNotifications_Selector) MenthenedYouInPost_Ins(ins ...int) *__SettingNotifications_Selector { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " MenthenedYouInPost IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (u *__SettingNotifications_Selector) MenthenedYouInPost_NotIn(ins []int) *__SettingNotifications_Selector { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " MenthenedYouInPost NOT IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (d *__SettingNotifications_Selector) MenthenedYouInPost_Eq(val int) *__SettingNotifications_Selector { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " MenthenedYouInPost = " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Selector) MenthenedYouInPost_NotEq(val int) *__SettingNotifications_Selector { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " MenthenedYouInPost != " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Selector) MenthenedYouInPost_LT(val int) *__SettingNotifications_Selector { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " MenthenedYouInPost < " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Selector) MenthenedYouInPost_LE(val int) *__SettingNotifications_Selector { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " MenthenedYouInPost <= " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Selector) MenthenedYouInPost_GT(val int) *__SettingNotifications_Selector { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " MenthenedYouInPost > " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Selector) MenthenedYouInPost_GE(val int) *__SettingNotifications_Selector { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " MenthenedYouInPost >= " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (u *__SettingNotifications_Selector) MenthenedYouInComment_In(ins []int) *__SettingNotifications_Selector { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " MenthenedYouInComment IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (u *__SettingNotifications_Selector) MenthenedYouInComment_Ins(ins ...int) *__SettingNotifications_Selector { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " MenthenedYouInComment IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (u *__SettingNotifications_Selector) MenthenedYouInComment_NotIn(ins []int) *__SettingNotifications_Selector { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " MenthenedYouInComment NOT IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (d *__SettingNotifications_Selector) MenthenedYouInComment_Eq(val int) *__SettingNotifications_Selector { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " MenthenedYouInComment = " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Selector) MenthenedYouInComment_NotEq(val int) *__SettingNotifications_Selector { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " MenthenedYouInComment != " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Selector) MenthenedYouInComment_LT(val int) *__SettingNotifications_Selector { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " MenthenedYouInComment < " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Selector) MenthenedYouInComment_LE(val int) *__SettingNotifications_Selector { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " MenthenedYouInComment <= " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Selector) MenthenedYouInComment_GT(val int) *__SettingNotifications_Selector { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " MenthenedYouInComment > " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Selector) MenthenedYouInComment_GE(val int) *__SettingNotifications_Selector { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " MenthenedYouInComment >= " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (u *__SettingNotifications_Selector) YourContactsJoined_In(ins []int) *__SettingNotifications_Selector { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " YourContactsJoined IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (u *__SettingNotifications_Selector) YourContactsJoined_Ins(ins ...int) *__SettingNotifications_Selector { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " YourContactsJoined IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (u *__SettingNotifications_Selector) YourContactsJoined_NotIn(ins []int) *__SettingNotifications_Selector { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " YourContactsJoined NOT IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (d *__SettingNotifications_Selector) YourContactsJoined_Eq(val int) *__SettingNotifications_Selector { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " YourContactsJoined = " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Selector) YourContactsJoined_NotEq(val int) *__SettingNotifications_Selector { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " YourContactsJoined != " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Selector) YourContactsJoined_LT(val int) *__SettingNotifications_Selector { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " YourContactsJoined < " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Selector) YourContactsJoined_LE(val int) *__SettingNotifications_Selector { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " YourContactsJoined <= " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Selector) YourContactsJoined_GT(val int) *__SettingNotifications_Selector { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " YourContactsJoined > " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Selector) YourContactsJoined_GE(val int) *__SettingNotifications_Selector { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " YourContactsJoined >= " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (u *__SettingNotifications_Selector) DirectMessage_In(ins []int) *__SettingNotifications_Selector { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " DirectMessage IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (u *__SettingNotifications_Selector) DirectMessage_Ins(ins ...int) *__SettingNotifications_Selector { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " DirectMessage IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (u *__SettingNotifications_Selector) DirectMessage_NotIn(ins []int) *__SettingNotifications_Selector { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " DirectMessage NOT IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (d *__SettingNotifications_Selector) DirectMessage_Eq(val int) *__SettingNotifications_Selector { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " DirectMessage = " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Selector) DirectMessage_NotEq(val int) *__SettingNotifications_Selector { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " DirectMessage != " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Selector) DirectMessage_LT(val int) *__SettingNotifications_Selector { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " DirectMessage < " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Selector) DirectMessage_LE(val int) *__SettingNotifications_Selector { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " DirectMessage <= " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Selector) DirectMessage_GT(val int) *__SettingNotifications_Selector { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " DirectMessage > " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Selector) DirectMessage_GE(val int) *__SettingNotifications_Selector { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " DirectMessage >= " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (u *__SettingNotifications_Selector) DirectAlert_In(ins []int) *__SettingNotifications_Selector { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " DirectAlert IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (u *__SettingNotifications_Selector) DirectAlert_Ins(ins ...int) *__SettingNotifications_Selector { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " DirectAlert IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (u *__SettingNotifications_Selector) DirectAlert_NotIn(ins []int) *__SettingNotifications_Selector { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " DirectAlert NOT IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (d *__SettingNotifications_Selector) DirectAlert_Eq(val int) *__SettingNotifications_Selector { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " DirectAlert = " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Selector) DirectAlert_NotEq(val int) *__SettingNotifications_Selector { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " DirectAlert != " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Selector) DirectAlert_LT(val int) *__SettingNotifications_Selector { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " DirectAlert < " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Selector) DirectAlert_LE(val int) *__SettingNotifications_Selector { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " DirectAlert <= " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Selector) DirectAlert_GT(val int) *__SettingNotifications_Selector { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " DirectAlert > " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Selector) DirectAlert_GE(val int) *__SettingNotifications_Selector { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " DirectAlert >= " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (u *__SettingNotifications_Selector) DirectPerview_In(ins []int) *__SettingNotifications_Selector { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " DirectPerview IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (u *__SettingNotifications_Selector) DirectPerview_Ins(ins ...int) *__SettingNotifications_Selector { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " DirectPerview IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (u *__SettingNotifications_Selector) DirectPerview_NotIn(ins []int) *__SettingNotifications_Selector { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " DirectPerview NOT IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (d *__SettingNotifications_Selector) DirectPerview_Eq(val int) *__SettingNotifications_Selector { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " DirectPerview = " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Selector) DirectPerview_NotEq(val int) *__SettingNotifications_Selector { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " DirectPerview != " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Selector) DirectPerview_LT(val int) *__SettingNotifications_Selector { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " DirectPerview < " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Selector) DirectPerview_LE(val int) *__SettingNotifications_Selector { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " DirectPerview <= " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Selector) DirectPerview_GT(val int) *__SettingNotifications_Selector { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " DirectPerview > " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Selector) DirectPerview_GE(val int) *__SettingNotifications_Selector { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " DirectPerview >= " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (u *__SettingNotifications_Selector) DirectLedOn_In(ins []int) *__SettingNotifications_Selector { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " DirectLedOn IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (u *__SettingNotifications_Selector) DirectLedOn_Ins(ins ...int) *__SettingNotifications_Selector { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " DirectLedOn IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (u *__SettingNotifications_Selector) DirectLedOn_NotIn(ins []int) *__SettingNotifications_Selector { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " DirectLedOn NOT IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (d *__SettingNotifications_Selector) DirectLedOn_Eq(val int) *__SettingNotifications_Selector { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " DirectLedOn = " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Selector) DirectLedOn_NotEq(val int) *__SettingNotifications_Selector { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " DirectLedOn != " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Selector) DirectLedOn_LT(val int) *__SettingNotifications_Selector { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " DirectLedOn < " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Selector) DirectLedOn_LE(val int) *__SettingNotifications_Selector { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " DirectLedOn <= " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Selector) DirectLedOn_GT(val int) *__SettingNotifications_Selector { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " DirectLedOn > " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Selector) DirectLedOn_GE(val int) *__SettingNotifications_Selector { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " DirectLedOn >= " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (u *__SettingNotifications_Selector) DirectLedColor_In(ins []int) *__SettingNotifications_Selector { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " DirectLedColor IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (u *__SettingNotifications_Selector) DirectLedColor_Ins(ins ...int) *__SettingNotifications_Selector { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " DirectLedColor IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (u *__SettingNotifications_Selector) DirectLedColor_NotIn(ins []int) *__SettingNotifications_Selector { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " DirectLedColor NOT IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (d *__SettingNotifications_Selector) DirectLedColor_Eq(val int) *__SettingNotifications_Selector { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " DirectLedColor = " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Selector) DirectLedColor_NotEq(val int) *__SettingNotifications_Selector { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " DirectLedColor != " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Selector) DirectLedColor_LT(val int) *__SettingNotifications_Selector { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " DirectLedColor < " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Selector) DirectLedColor_LE(val int) *__SettingNotifications_Selector { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " DirectLedColor <= " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Selector) DirectLedColor_GT(val int) *__SettingNotifications_Selector { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " DirectLedColor > " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Selector) DirectLedColor_GE(val int) *__SettingNotifications_Selector { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " DirectLedColor >= " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (u *__SettingNotifications_Selector) DirectVibrate_In(ins []int) *__SettingNotifications_Selector { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " DirectVibrate IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (u *__SettingNotifications_Selector) DirectVibrate_Ins(ins ...int) *__SettingNotifications_Selector { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " DirectVibrate IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (u *__SettingNotifications_Selector) DirectVibrate_NotIn(ins []int) *__SettingNotifications_Selector { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " DirectVibrate NOT IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (d *__SettingNotifications_Selector) DirectVibrate_Eq(val int) *__SettingNotifications_Selector { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " DirectVibrate = " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Selector) DirectVibrate_NotEq(val int) *__SettingNotifications_Selector { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " DirectVibrate != " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Selector) DirectVibrate_LT(val int) *__SettingNotifications_Selector { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " DirectVibrate < " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Selector) DirectVibrate_LE(val int) *__SettingNotifications_Selector { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " DirectVibrate <= " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Selector) DirectVibrate_GT(val int) *__SettingNotifications_Selector { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " DirectVibrate > " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Selector) DirectVibrate_GE(val int) *__SettingNotifications_Selector { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " DirectVibrate >= " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (u *__SettingNotifications_Selector) DirectPopup_In(ins []int) *__SettingNotifications_Selector { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " DirectPopup IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (u *__SettingNotifications_Selector) DirectPopup_Ins(ins ...int) *__SettingNotifications_Selector { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " DirectPopup IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (u *__SettingNotifications_Selector) DirectPopup_NotIn(ins []int) *__SettingNotifications_Selector { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " DirectPopup NOT IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (d *__SettingNotifications_Selector) DirectPopup_Eq(val int) *__SettingNotifications_Selector { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " DirectPopup = " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Selector) DirectPopup_NotEq(val int) *__SettingNotifications_Selector { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " DirectPopup != " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Selector) DirectPopup_LT(val int) *__SettingNotifications_Selector { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " DirectPopup < " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Selector) DirectPopup_LE(val int) *__SettingNotifications_Selector { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " DirectPopup <= " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Selector) DirectPopup_GT(val int) *__SettingNotifications_Selector { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " DirectPopup > " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Selector) DirectPopup_GE(val int) *__SettingNotifications_Selector { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " DirectPopup >= " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (u *__SettingNotifications_Selector) DirectSound_In(ins []int) *__SettingNotifications_Selector { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " DirectSound IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (u *__SettingNotifications_Selector) DirectSound_Ins(ins ...int) *__SettingNotifications_Selector { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " DirectSound IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (u *__SettingNotifications_Selector) DirectSound_NotIn(ins []int) *__SettingNotifications_Selector { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " DirectSound NOT IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (d *__SettingNotifications_Selector) DirectSound_Eq(val int) *__SettingNotifications_Selector { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " DirectSound = " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Selector) DirectSound_NotEq(val int) *__SettingNotifications_Selector { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " DirectSound != " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Selector) DirectSound_LT(val int) *__SettingNotifications_Selector { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " DirectSound < " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Selector) DirectSound_LE(val int) *__SettingNotifications_Selector { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " DirectSound <= " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Selector) DirectSound_GT(val int) *__SettingNotifications_Selector { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " DirectSound > " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Selector) DirectSound_GE(val int) *__SettingNotifications_Selector { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " DirectSound >= " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (u *__SettingNotifications_Selector) DirectPriority_In(ins []int) *__SettingNotifications_Selector { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " DirectPriority IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (u *__SettingNotifications_Selector) DirectPriority_Ins(ins ...int) *__SettingNotifications_Selector { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " DirectPriority IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (u *__SettingNotifications_Selector) DirectPriority_NotIn(ins []int) *__SettingNotifications_Selector { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " DirectPriority NOT IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (d *__SettingNotifications_Selector) DirectPriority_Eq(val int) *__SettingNotifications_Selector { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " DirectPriority = " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Selector) DirectPriority_NotEq(val int) *__SettingNotifications_Selector { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " DirectPriority != " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Selector) DirectPriority_LT(val int) *__SettingNotifications_Selector { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " DirectPriority < " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Selector) DirectPriority_LE(val int) *__SettingNotifications_Selector { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " DirectPriority <= " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Selector) DirectPriority_GT(val int) *__SettingNotifications_Selector { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " DirectPriority > " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Selector) DirectPriority_GE(val int) *__SettingNotifications_Selector { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " DirectPriority >= " + d.nextDollar() d.wheres = append(d.wheres, w) return d } ///// for strings //copy of above with type int -> string + rm if eq + $ms_str_cond ////////ints func (u *__SettingNotifications_Deleter) SocialLedColor_In(ins []string) *__SettingNotifications_Deleter { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " SocialLedColor IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (u *__SettingNotifications_Deleter) SocialLedColor_NotIn(ins []string) *__SettingNotifications_Deleter { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " SocialLedColor NOT IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } //must be used like: UserName_like("hamid%") func (u *__SettingNotifications_Deleter) SocialLedColor_Like(val string) *__SettingNotifications_Deleter { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " SocialLedColor LIKE " + u.nextDollar() u.wheres = append(u.wheres, w) return u } func (d *__SettingNotifications_Deleter) SocialLedColor_Eq(val string) *__SettingNotifications_Deleter { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " SocialLedColor = " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Deleter) SocialLedColor_NotEq(val string) *__SettingNotifications_Deleter { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " SocialLedColor != " + d.nextDollar() d.wheres = append(d.wheres, w) return d } ////////ints func (u *__SettingNotifications_Updater) SocialLedColor_In(ins []string) *__SettingNotifications_Updater { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " SocialLedColor IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (u *__SettingNotifications_Updater) SocialLedColor_NotIn(ins []string) *__SettingNotifications_Updater { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " SocialLedColor NOT IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } //must be used like: UserName_like("hamid%") func (u *__SettingNotifications_Updater) SocialLedColor_Like(val string) *__SettingNotifications_Updater { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " SocialLedColor LIKE " + u.nextDollar() u.wheres = append(u.wheres, w) return u } func (d *__SettingNotifications_Updater) SocialLedColor_Eq(val string) *__SettingNotifications_Updater { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " SocialLedColor = " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Updater) SocialLedColor_NotEq(val string) *__SettingNotifications_Updater { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " SocialLedColor != " + d.nextDollar() d.wheres = append(d.wheres, w) return d } ////////ints func (u *__SettingNotifications_Selector) SocialLedColor_In(ins []string) *__SettingNotifications_Selector { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " SocialLedColor IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } func (u *__SettingNotifications_Selector) SocialLedColor_NotIn(ins []string) *__SettingNotifications_Selector { w := whereClause{} var insWhere []interface{} for _, i := range ins { insWhere = append(insWhere, i) } w.args = insWhere w.condition = " SocialLedColor NOT IN(" + u.nextDollars(len(ins)) + ") " u.wheres = append(u.wheres, w) return u } //must be used like: UserName_like("hamid%") func (u *__SettingNotifications_Selector) SocialLedColor_Like(val string) *__SettingNotifications_Selector { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " SocialLedColor LIKE " + u.nextDollar() u.wheres = append(u.wheres, w) return u } func (d *__SettingNotifications_Selector) SocialLedColor_Eq(val string) *__SettingNotifications_Selector { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " SocialLedColor = " + d.nextDollar() d.wheres = append(d.wheres, w) return d } func (d *__SettingNotifications_Selector) SocialLedColor_NotEq(val string) *__SettingNotifications_Selector { w := whereClause{} var insWhere []interface{} insWhere = append(insWhere, val) w.args = insWhere w.condition = " SocialLedColor != " + d.nextDollar() d.wheres = append(d.wheres, w) return d } /// End of wheres for selectors , updators, deletor /////////////////////////////// Updater ///////////////////////////// //ints func (u *__SettingNotifications_Updater) UserId(newVal int) *__SettingNotifications_Updater { up := updateCol{" UserId = " + u.nextDollar(), newVal} u.updates = append(u.updates, up) // u.updates[" UserId = " + u.nextDollar()] = newVal return u } func (u *__SettingNotifications_Updater) UserId_Increment(count int) *__SettingNotifications_Updater { if count > 0 { up := updateCol{" UserId = UserId+ " + u.nextDollar(), count} u.updates = append(u.updates, up) //u.updates[" UserId = UserId+ " + u.nextDollar()] = count } if count < 0 { up := updateCol{" UserId = UserId- " + u.nextDollar(), count} u.updates = append(u.updates, up) // u.updates[" UserId = UserId- " + u.nextDollar() ] = -(count) //make it positive } return u } //string //ints func (u *__SettingNotifications_Updater) SocialLedOn(newVal int) *__SettingNotifications_Updater { up := updateCol{" SocialLedOn = " + u.nextDollar(), newVal} u.updates = append(u.updates, up) // u.updates[" SocialLedOn = " + u.nextDollar()] = newVal return u } func (u *__SettingNotifications_Updater) SocialLedOn_Increment(count int) *__SettingNotifications_Updater { if count > 0 { up := updateCol{" SocialLedOn = SocialLedOn+ " + u.nextDollar(), count} u.updates = append(u.updates, up) //u.updates[" SocialLedOn = SocialLedOn+ " + u.nextDollar()] = count } if count < 0 { up := updateCol{" SocialLedOn = SocialLedOn- " + u.nextDollar(), count} u.updates = append(u.updates, up) // u.updates[" SocialLedOn = SocialLedOn- " + u.nextDollar() ] = -(count) //make it positive } return u } //string //ints //string func (u *__SettingNotifications_Updater) SocialLedColor(newVal string) *__SettingNotifications_Updater { up := updateCol{"SocialLedColor = " + u.nextDollar(), newVal} u.updates = append(u.updates, up) // u.updates[" SocialLedColor = "+ u.nextDollar()] = newVal return u } //ints func (u *__SettingNotifications_Updater) ReqestToFollowYou(newVal int) *__SettingNotifications_Updater { up := updateCol{" ReqestToFollowYou = " + u.nextDollar(), newVal} u.updates = append(u.updates, up) // u.updates[" ReqestToFollowYou = " + u.nextDollar()] = newVal return u } func (u *__SettingNotifications_Updater) ReqestToFollowYou_Increment(count int) *__SettingNotifications_Updater { if count > 0 { up := updateCol{" ReqestToFollowYou = ReqestToFollowYou+ " + u.nextDollar(), count} u.updates = append(u.updates, up) //u.updates[" ReqestToFollowYou = ReqestToFollowYou+ " + u.nextDollar()] = count } if count < 0 { up := updateCol{" ReqestToFollowYou = ReqestToFollowYou- " + u.nextDollar(), count} u.updates = append(u.updates, up) // u.updates[" ReqestToFollowYou = ReqestToFollowYou- " + u.nextDollar() ] = -(count) //make it positive } return u } //string //ints func (u *__SettingNotifications_Updater) FollowedYou(newVal int) *__SettingNotifications_Updater { up := updateCol{" FollowedYou = " + u.nextDollar(), newVal} u.updates = append(u.updates, up) // u.updates[" FollowedYou = " + u.nextDollar()] = newVal return u } func (u *__SettingNotifications_Updater) FollowedYou_Increment(count int) *__SettingNotifications_Updater { if count > 0 { up := updateCol{" FollowedYou = FollowedYou+ " + u.nextDollar(), count} u.updates = append(u.updates, up) //u.updates[" FollowedYou = FollowedYou+ " + u.nextDollar()] = count } if count < 0 { up := updateCol{" FollowedYou = FollowedYou- " + u.nextDollar(), count} u.updates = append(u.updates, up) // u.updates[" FollowedYou = FollowedYou- " + u.nextDollar() ] = -(count) //make it positive } return u } //string //ints func (u *__SettingNotifications_Updater) AccptedYourFollowRequest(newVal int) *__SettingNotifications_Updater { up := updateCol{" AccptedYourFollowRequest = " + u.nextDollar(), newVal} u.updates = append(u.updates, up) // u.updates[" AccptedYourFollowRequest = " + u.nextDollar()] = newVal return u } func (u *__SettingNotifications_Updater) AccptedYourFollowRequest_Increment(count int) *__SettingNotifications_Updater { if count > 0 { up := updateCol{" AccptedYourFollowRequest = AccptedYourFollowRequest+ " + u.nextDollar(), count} u.updates = append(u.updates, up) //u.updates[" AccptedYourFollowRequest = AccptedYourFollowRequest+ " + u.nextDollar()] = count } if count < 0 { up := updateCol{" AccptedYourFollowRequest = AccptedYourFollowRequest- " + u.nextDollar(), count} u.updates = append(u.updates, up) // u.updates[" AccptedYourFollowRequest = AccptedYourFollowRequest- " + u.nextDollar() ] = -(count) //make it positive } return u } //string //ints func (u *__SettingNotifications_Updater) YourPostLiked(newVal int) *__SettingNotifications_Updater { up := updateCol{" YourPostLiked = " + u.nextDollar(), newVal} u.updates = append(u.updates, up) // u.updates[" YourPostLiked = " + u.nextDollar()] = newVal return u } func (u *__SettingNotifications_Updater) YourPostLiked_Increment(count int) *__SettingNotifications_Updater { if count > 0 { up := updateCol{" YourPostLiked = YourPostLiked+ " + u.nextDollar(), count} u.updates = append(u.updates, up) //u.updates[" YourPostLiked = YourPostLiked+ " + u.nextDollar()] = count } if count < 0 { up := updateCol{" YourPostLiked = YourPostLiked- " + u.nextDollar(), count} u.updates = append(u.updates, up) // u.updates[" YourPostLiked = YourPostLiked- " + u.nextDollar() ] = -(count) //make it positive } return u } //string //ints func (u *__SettingNotifications_Updater) YourPostCommented(newVal int) *__SettingNotifications_Updater { up := updateCol{" YourPostCommented = " + u.nextDollar(), newVal} u.updates = append(u.updates, up) // u.updates[" YourPostCommented = " + u.nextDollar()] = newVal return u } func (u *__SettingNotifications_Updater) YourPostCommented_Increment(count int) *__SettingNotifications_Updater { if count > 0 { up := updateCol{" YourPostCommented = YourPostCommented+ " + u.nextDollar(), count} u.updates = append(u.updates, up) //u.updates[" YourPostCommented = YourPostCommented+ " + u.nextDollar()] = count } if count < 0 { up := updateCol{" YourPostCommented = YourPostCommented- " + u.nextDollar(), count} u.updates = append(u.updates, up) // u.updates[" YourPostCommented = YourPostCommented- " + u.nextDollar() ] = -(count) //make it positive } return u } //string //ints func (u *__SettingNotifications_Updater) MenthenedYouInPost(newVal int) *__SettingNotifications_Updater { up := updateCol{" MenthenedYouInPost = " + u.nextDollar(), newVal} u.updates = append(u.updates, up) // u.updates[" MenthenedYouInPost = " + u.nextDollar()] = newVal return u } func (u *__SettingNotifications_Updater) MenthenedYouInPost_Increment(count int) *__SettingNotifications_Updater { if count > 0 { up := updateCol{" MenthenedYouInPost = MenthenedYouInPost+ " + u.nextDollar(), count} u.updates = append(u.updates, up) //u.updates[" MenthenedYouInPost = MenthenedYouInPost+ " + u.nextDollar()] = count } if count < 0 { up := updateCol{" MenthenedYouInPost = MenthenedYouInPost- " + u.nextDollar(), count} u.updates = append(u.updates, up) // u.updates[" MenthenedYouInPost = MenthenedYouInPost- " + u.nextDollar() ] = -(count) //make it positive } return u } //string //ints func (u *__SettingNotifications_Updater) MenthenedYouInComment(newVal int) *__SettingNotifications_Updater { up := updateCol{" MenthenedYouInComment = " + u.nextDollar(), newVal} u.updates = append(u.updates, up) // u.updates[" MenthenedYouInComment = " + u.nextDollar()] = newVal return u } func (u *__SettingNotifications_Updater) MenthenedYouInComment_Increment(count int) *__SettingNotifications_Updater { if count > 0 { up := updateCol{" MenthenedYouInComment = MenthenedYouInComment+ " + u.nextDollar(), count} u.updates = append(u.updates, up) //u.updates[" MenthenedYouInComment = MenthenedYouInComment+ " + u.nextDollar()] = count } if count < 0 { up := updateCol{" MenthenedYouInComment = MenthenedYouInComment- " + u.nextDollar(), count} u.updates = append(u.updates, up) // u.updates[" MenthenedYouInComment = MenthenedYouInComment- " + u.nextDollar() ] = -(count) //make it positive } return u } //string //ints func (u *__SettingNotifications_Updater) YourContactsJoined(newVal int) *__SettingNotifications_Updater { up := updateCol{" YourContactsJoined = " + u.nextDollar(), newVal} u.updates = append(u.updates, up) // u.updates[" YourContactsJoined = " + u.nextDollar()] = newVal return u } func (u *__SettingNotifications_Updater) YourContactsJoined_Increment(count int) *__SettingNotifications_Updater { if count > 0 { up := updateCol{" YourContactsJoined = YourContactsJoined+ " + u.nextDollar(), count} u.updates = append(u.updates, up) //u.updates[" YourContactsJoined = YourContactsJoined+ " + u.nextDollar()] = count } if count < 0 { up := updateCol{" YourContactsJoined = YourContactsJoined- " + u.nextDollar(), count} u.updates = append(u.updates, up) // u.updates[" YourContactsJoined = YourContactsJoined- " + u.nextDollar() ] = -(count) //make it positive } return u } //string //ints func (u *__SettingNotifications_Updater) DirectMessage(newVal int) *__SettingNotifications_Updater { up := updateCol{" DirectMessage = " + u.nextDollar(), newVal} u.updates = append(u.updates, up) // u.updates[" DirectMessage = " + u.nextDollar()] = newVal return u } func (u *__SettingNotifications_Updater) DirectMessage_Increment(count int) *__SettingNotifications_Updater { if count > 0 { up := updateCol{" DirectMessage = DirectMessage+ " + u.nextDollar(), count} u.updates = append(u.updates, up) //u.updates[" DirectMessage = DirectMessage+ " + u.nextDollar()] = count } if count < 0 { up := updateCol{" DirectMessage = DirectMessage- " + u.nextDollar(), count} u.updates = append(u.updates, up) // u.updates[" DirectMessage = DirectMessage- " + u.nextDollar() ] = -(count) //make it positive } return u } //string //ints func (u *__SettingNotifications_Updater) DirectAlert(newVal int) *__SettingNotifications_Updater { up := updateCol{" DirectAlert = " + u.nextDollar(), newVal} u.updates = append(u.updates, up) // u.updates[" DirectAlert = " + u.nextDollar()] = newVal return u } func (u *__SettingNotifications_Updater) DirectAlert_Increment(count int) *__SettingNotifications_Updater { if count > 0 { up := updateCol{" DirectAlert = DirectAlert+ " + u.nextDollar(), count} u.updates = append(u.updates, up) //u.updates[" DirectAlert = DirectAlert+ " + u.nextDollar()] = count } if count < 0 { up := updateCol{" DirectAlert = DirectAlert- " + u.nextDollar(), count} u.updates = append(u.updates, up) // u.updates[" DirectAlert = DirectAlert- " + u.nextDollar() ] = -(count) //make it positive } return u } //string //ints func (u *__SettingNotifications_Updater) DirectPerview(newVal int) *__SettingNotifications_Updater { up := updateCol{" DirectPerview = " + u.nextDollar(), newVal} u.updates = append(u.updates, up) // u.updates[" DirectPerview = " + u.nextDollar()] = newVal return u } func (u *__SettingNotifications_Updater) DirectPerview_Increment(count int) *__SettingNotifications_Updater { if count > 0 { up := updateCol{" DirectPerview = DirectPerview+ " + u.nextDollar(), count} u.updates = append(u.updates, up) //u.updates[" DirectPerview = DirectPerview+ " + u.nextDollar()] = count } if count < 0 { up := updateCol{" DirectPerview = DirectPerview- " + u.nextDollar(), count} u.updates = append(u.updates, up) // u.updates[" DirectPerview = DirectPerview- " + u.nextDollar() ] = -(count) //make it positive } return u } //string //ints func (u *__SettingNotifications_Updater) DirectLedOn(newVal int) *__SettingNotifications_Updater { up := updateCol{" DirectLedOn = " + u.nextDollar(), newVal} u.updates = append(u.updates, up) // u.updates[" DirectLedOn = " + u.nextDollar()] = newVal return u } func (u *__SettingNotifications_Updater) DirectLedOn_Increment(count int) *__SettingNotifications_Updater { if count > 0 { up := updateCol{" DirectLedOn = DirectLedOn+ " + u.nextDollar(), count} u.updates = append(u.updates, up) //u.updates[" DirectLedOn = DirectLedOn+ " + u.nextDollar()] = count } if count < 0 { up := updateCol{" DirectLedOn = DirectLedOn- " + u.nextDollar(), count} u.updates = append(u.updates, up) // u.updates[" DirectLedOn = DirectLedOn- " + u.nextDollar() ] = -(count) //make it positive } return u } //string //ints func (u *__SettingNotifications_Updater) DirectLedColor(newVal int) *__SettingNotifications_Updater { up := updateCol{" DirectLedColor = " + u.nextDollar(), newVal} u.updates = append(u.updates, up) // u.updates[" DirectLedColor = " + u.nextDollar()] = newVal return u } func (u *__SettingNotifications_Updater) DirectLedColor_Increment(count int) *__SettingNotifications_Updater { if count > 0 { up := updateCol{" DirectLedColor = DirectLedColor+ " + u.nextDollar(), count} u.updates = append(u.updates, up) //u.updates[" DirectLedColor = DirectLedColor+ " + u.nextDollar()] = count } if count < 0 { up := updateCol{" DirectLedColor = DirectLedColor- " + u.nextDollar(), count} u.updates = append(u.updates, up) // u.updates[" DirectLedColor = DirectLedColor- " + u.nextDollar() ] = -(count) //make it positive } return u } //string //ints func (u *__SettingNotifications_Updater) DirectVibrate(newVal int) *__SettingNotifications_Updater { up := updateCol{" DirectVibrate = " + u.nextDollar(), newVal} u.updates = append(u.updates, up) // u.updates[" DirectVibrate = " + u.nextDollar()] = newVal return u } func (u *__SettingNotifications_Updater) DirectVibrate_Increment(count int) *__SettingNotifications_Updater { if count > 0 { up := updateCol{" DirectVibrate = DirectVibrate+ " + u.nextDollar(), count} u.updates = append(u.updates, up) //u.updates[" DirectVibrate = DirectVibrate+ " + u.nextDollar()] = count } if count < 0 { up := updateCol{" DirectVibrate = DirectVibrate- " + u.nextDollar(), count} u.updates = append(u.updates, up) // u.updates[" DirectVibrate = DirectVibrate- " + u.nextDollar() ] = -(count) //make it positive } return u } //string //ints func (u *__SettingNotifications_Updater) DirectPopup(newVal int) *__SettingNotifications_Updater { up := updateCol{" DirectPopup = " + u.nextDollar(), newVal} u.updates = append(u.updates, up) // u.updates[" DirectPopup = " + u.nextDollar()] = newVal return u } func (u *__SettingNotifications_Updater) DirectPopup_Increment(count int) *__SettingNotifications_Updater { if count > 0 { up := updateCol{" DirectPopup = DirectPopup+ " + u.nextDollar(), count} u.updates = append(u.updates, up) //u.updates[" DirectPopup = DirectPopup+ " + u.nextDollar()] = count } if count < 0 { up := updateCol{" DirectPopup = DirectPopup- " + u.nextDollar(), count} u.updates = append(u.updates, up) // u.updates[" DirectPopup = DirectPopup- " + u.nextDollar() ] = -(count) //make it positive } return u } //string //ints func (u *__SettingNotifications_Updater) DirectSound(newVal int) *__SettingNotifications_Updater { up := updateCol{" DirectSound = " + u.nextDollar(), newVal} u.updates = append(u.updates, up) // u.updates[" DirectSound = " + u.nextDollar()] = newVal return u } func (u *__SettingNotifications_Updater) DirectSound_Increment(count int) *__SettingNotifications_Updater { if count > 0 { up := updateCol{" DirectSound = DirectSound+ " + u.nextDollar(), count} u.updates = append(u.updates, up) //u.updates[" DirectSound = DirectSound+ " + u.nextDollar()] = count } if count < 0 { up := updateCol{" DirectSound = DirectSound- " + u.nextDollar(), count} u.updates = append(u.updates, up) // u.updates[" DirectSound = DirectSound- " + u.nextDollar() ] = -(count) //make it positive } return u } //string //ints func (u *__SettingNotifications_Updater) DirectPriority(newVal int) *__SettingNotifications_Updater { up := updateCol{" DirectPriority = " + u.nextDollar(), newVal} u.updates = append(u.updates, up) // u.updates[" DirectPriority = " + u.nextDollar()] = newVal return u } func (u *__SettingNotifications_Updater) DirectPriority_Increment(count int) *__SettingNotifications_Updater { if count > 0 { up := updateCol{" DirectPriority = DirectPriority+ " + u.nextDollar(), count} u.updates = append(u.updates, up) //u.updates[" DirectPriority = DirectPriority+ " + u.nextDollar()] = count } if count < 0 { up := updateCol{" DirectPriority = DirectPriority- " + u.nextDollar(), count} u.updates = append(u.updates, up) // u.updates[" DirectPriority = DirectPriority- " + u.nextDollar() ] = -(count) //make it positive } return u } //string ///////////////////////////////////////////////////////////////////// /////////////////////// Selector /////////////////////////////////// //Select_* can just be used with: .GetString() , .GetStringSlice(), .GetInt() ..GetIntSlice() func (u *__SettingNotifications_Selector) OrderBy_UserId_Desc() *__SettingNotifications_Selector { u.orderBy = " ORDER BY UserId DESC " return u } func (u *__SettingNotifications_Selector) OrderBy_UserId_Asc() *__SettingNotifications_Selector { u.orderBy = " ORDER BY UserId ASC " return u } func (u *__SettingNotifications_Selector) Select_UserId() *__SettingNotifications_Selector { u.selectCol = "UserId" return u } func (u *__SettingNotifications_Selector) OrderBy_SocialLedOn_Desc() *__SettingNotifications_Selector { u.orderBy = " ORDER BY SocialLedOn DESC " return u } func (u *__SettingNotifications_Selector) OrderBy_SocialLedOn_Asc() *__SettingNotifications_Selector { u.orderBy = " ORDER BY SocialLedOn ASC " return u } func (u *__SettingNotifications_Selector) Select_SocialLedOn() *__SettingNotifications_Selector { u.selectCol = "SocialLedOn" return u } func (u *__SettingNotifications_Selector) OrderBy_SocialLedColor_Desc() *__SettingNotifications_Selector { u.orderBy = " ORDER BY SocialLedColor DESC " return u } func (u *__SettingNotifications_Selector) OrderBy_SocialLedColor_Asc() *__SettingNotifications_Selector { u.orderBy = " ORDER BY SocialLedColor ASC " return u } func (u *__SettingNotifications_Selector) Select_SocialLedColor() *__SettingNotifications_Selector { u.selectCol = "SocialLedColor" return u } func (u *__SettingNotifications_Selector) OrderBy_ReqestToFollowYou_Desc() *__SettingNotifications_Selector { u.orderBy = " ORDER BY ReqestToFollowYou DESC " return u } func (u *__SettingNotifications_Selector) OrderBy_ReqestToFollowYou_Asc() *__SettingNotifications_Selector { u.orderBy = " ORDER BY ReqestToFollowYou ASC " return u } func (u *__SettingNotifications_Selector) Select_ReqestToFollowYou() *__SettingNotifications_Selector { u.selectCol = "ReqestToFollowYou" return u } func (u *__SettingNotifications_Selector) OrderBy_FollowedYou_Desc() *__SettingNotifications_Selector { u.orderBy = " ORDER BY FollowedYou DESC " return u } func (u *__SettingNotifications_Selector) OrderBy_FollowedYou_Asc() *__SettingNotifications_Selector { u.orderBy = " ORDER BY FollowedYou ASC " return u } func (u *__SettingNotifications_Selector) Select_FollowedYou() *__SettingNotifications_Selector { u.selectCol = "FollowedYou" return u } func (u *__SettingNotifications_Selector) OrderBy_AccptedYourFollowRequest_Desc() *__SettingNotifications_Selector { u.orderBy = " ORDER BY AccptedYourFollowRequest DESC " return u } func (u *__SettingNotifications_Selector) OrderBy_AccptedYourFollowRequest_Asc() *__SettingNotifications_Selector { u.orderBy = " ORDER BY AccptedYourFollowRequest ASC " return u } func (u *__SettingNotifications_Selector) Select_AccptedYourFollowRequest() *__SettingNotifications_Selector { u.selectCol = "AccptedYourFollowRequest" return u } func (u *__SettingNotifications_Selector) OrderBy_YourPostLiked_Desc() *__SettingNotifications_Selector { u.orderBy = " ORDER BY YourPostLiked DESC " return u } func (u *__SettingNotifications_Selector) OrderBy_YourPostLiked_Asc() *__SettingNotifications_Selector { u.orderBy = " ORDER BY YourPostLiked ASC " return u } func (u *__SettingNotifications_Selector) Select_YourPostLiked() *__SettingNotifications_Selector { u.selectCol = "YourPostLiked" return u } func (u *__SettingNotifications_Selector) OrderBy_YourPostCommented_Desc() *__SettingNotifications_Selector { u.orderBy = " ORDER BY YourPostCommented DESC " return u } func (u *__SettingNotifications_Selector) OrderBy_YourPostCommented_Asc() *__SettingNotifications_Selector { u.orderBy = " ORDER BY YourPostCommented ASC " return u } func (u *__SettingNotifications_Selector) Select_YourPostCommented() *__SettingNotifications_Selector { u.selectCol = "YourPostCommented" return u } func (u *__SettingNotifications_Selector) OrderBy_MenthenedYouInPost_Desc() *__SettingNotifications_Selector { u.orderBy = " ORDER BY MenthenedYouInPost DESC " return u } func (u *__SettingNotifications_Selector) OrderBy_MenthenedYouInPost_Asc() *__SettingNotifications_Selector { u.orderBy = " ORDER BY MenthenedYouInPost ASC " return u } func (u *__SettingNotifications_Selector) Select_MenthenedYouInPost() *__SettingNotifications_Selector { u.selectCol = "MenthenedYouInPost" return u } func (u *__SettingNotifications_Selector) OrderBy_MenthenedYouInComment_Desc() *__SettingNotifications_Selector { u.orderBy = " ORDER BY MenthenedYouInComment DESC " return u } func (u *__SettingNotifications_Selector) OrderBy_MenthenedYouInComment_Asc() *__SettingNotifications_Selector { u.orderBy = " ORDER BY MenthenedYouInComment ASC " return u } func (u *__SettingNotifications_Selector) Select_MenthenedYouInComment() *__SettingNotifications_Selector { u.selectCol = "MenthenedYouInComment" return u } func (u *__SettingNotifications_Selector) OrderBy_YourContactsJoined_Desc() *__SettingNotifications_Selector { u.orderBy = " ORDER BY YourContactsJoined DESC " return u } func (u *__SettingNotifications_Selector) OrderBy_YourContactsJoined_Asc() *__SettingNotifications_Selector { u.orderBy = " ORDER BY YourContactsJoined ASC " return u } func (u *__SettingNotifications_Selector) Select_YourContactsJoined() *__SettingNotifications_Selector { u.selectCol = "YourContactsJoined" return u } func (u *__SettingNotifications_Selector) OrderBy_DirectMessage_Desc() *__SettingNotifications_Selector { u.orderBy = " ORDER BY DirectMessage DESC " return u } func (u *__SettingNotifications_Selector) OrderBy_DirectMessage_Asc() *__SettingNotifications_Selector { u.orderBy = " ORDER BY DirectMessage ASC " return u } func (u *__SettingNotifications_Selector) Select_DirectMessage() *__SettingNotifications_Selector { u.selectCol = "DirectMessage" return u } func (u *__SettingNotifications_Selector) OrderBy_DirectAlert_Desc() *__SettingNotifications_Selector { u.orderBy = " ORDER BY DirectAlert DESC " return u } func (u *__SettingNotifications_Selector) OrderBy_DirectAlert_Asc() *__SettingNotifications_Selector { u.orderBy = " ORDER BY DirectAlert ASC " return u } func (u *__SettingNotifications_Selector) Select_DirectAlert() *__SettingNotifications_Selector { u.selectCol = "DirectAlert" return u } func (u *__SettingNotifications_Selector) OrderBy_DirectPerview_Desc() *__SettingNotifications_Selector { u.orderBy = " ORDER BY DirectPerview DESC " return u } func (u *__SettingNotifications_Selector) OrderBy_DirectPerview_Asc() *__SettingNotifications_Selector { u.orderBy = " ORDER BY DirectPerview ASC " return u } func (u *__SettingNotifications_Selector) Select_DirectPerview() *__SettingNotifications_Selector { u.selectCol = "DirectPerview" return u } func (u *__SettingNotifications_Selector) OrderBy_DirectLedOn_Desc() *__SettingNotifications_Selector { u.orderBy = " ORDER BY DirectLedOn DESC " return u } func (u *__SettingNotifications_Selector) OrderBy_DirectLedOn_Asc() *__SettingNotifications_Selector { u.orderBy = " ORDER BY DirectLedOn ASC " return u } func (u *__SettingNotifications_Selector) Select_DirectLedOn() *__SettingNotifications_Selector { u.selectCol = "DirectLedOn" return u } func (u *__SettingNotifications_Selector) OrderBy_DirectLedColor_Desc() *__SettingNotifications_Selector { u.orderBy = " ORDER BY DirectLedColor DESC " return u } func (u *__SettingNotifications_Selector) OrderBy_DirectLedColor_Asc() *__SettingNotifications_Selector { u.orderBy = " ORDER BY DirectLedColor ASC " return u } func (u *__SettingNotifications_Selector) Select_DirectLedColor() *__SettingNotifications_Selector { u.selectCol = "DirectLedColor" return u } func (u *__SettingNotifications_Selector) OrderBy_DirectVibrate_Desc() *__SettingNotifications_Selector { u.orderBy = " ORDER BY DirectVibrate DESC " return u } func (u *__SettingNotifications_Selector) OrderBy_DirectVibrate_Asc() *__SettingNotifications_Selector { u.orderBy = " ORDER BY DirectVibrate ASC " return u } func (u *__SettingNotifications_Selector) Select_DirectVibrate() *__SettingNotifications_Selector { u.selectCol = "DirectVibrate" return u } func (u *__SettingNotifications_Selector) OrderBy_DirectPopup_Desc() *__SettingNotifications_Selector { u.orderBy = " ORDER BY DirectPopup DESC " return u } func (u *__SettingNotifications_Selector) OrderBy_DirectPopup_Asc() *__SettingNotifications_Selector { u.orderBy = " ORDER BY DirectPopup ASC " return u } func (u *__SettingNotifications_Selector) Select_DirectPopup() *__SettingNotifications_Selector { u.selectCol = "DirectPopup" return u } func (u *__SettingNotifications_Selector) OrderBy_DirectSound_Desc() *__SettingNotifications_Selector { u.orderBy = " ORDER BY DirectSound DESC " return u } func (u *__SettingNotifications_Selector) OrderBy_DirectSound_Asc() *__SettingNotifications_Selector { u.orderBy = " ORDER BY DirectSound ASC " return u } func (u *__SettingNotifications_Selector) Select_DirectSound() *__SettingNotifications_Selector { u.selectCol = "DirectSound" return u } func (u *__SettingNotifications_Selector) OrderBy_DirectPriority_Desc() *__SettingNotifications_Selector { u.orderBy = " ORDER BY DirectPriority DESC " return u } func (u *__SettingNotifications_Selector) OrderBy_DirectPriority_Asc() *__SettingNotifications_Selector { u.orderBy = " ORDER BY DirectPriority ASC " return u } func (u *__SettingNotifications_Selector) Select_DirectPriority() *__SettingNotifications_Selector { u.selectCol = "DirectPriority" return u } func (u *__SettingNotifications_Selector) Limit(num int) *__SettingNotifications_Selector { u.limit = num return u } func (u *__SettingNotifications_Selector) Offset(num int) *__SettingNotifications_Selector { u.offset = num return u } func (u *__SettingNotifications_Selector) Order_Rand() *__SettingNotifications_Selector { u.orderBy = " ORDER BY RAND() " return u } ///////////////////////// Queryer Selector ////////////////////////////////// func (u *__SettingNotifications_Selector) _stoSql() (string, []interface{}) { sqlWherrs, whereArgs := whereClusesToSql(u.wheres, u.whereSep) sqlstr := "SELECT " + u.selectCol + " FROM sun.setting_notifications" if len(strings.Trim(sqlWherrs, " ")) > 0 { //2 for safty sqlstr += " WHERE " + sqlWherrs } if u.orderBy != "" { sqlstr += u.orderBy } if u.limit != 0 { sqlstr += " LIMIT " + strconv.Itoa(u.limit) } if u.offset != 0 { sqlstr += " OFFSET " + strconv.Itoa(u.offset) } return sqlstr, whereArgs } func (u *__SettingNotifications_Selector) GetRow(db *sqlx.DB) (*SettingNotifications, error) { var err error sqlstr, whereArgs := u._stoSql() if LogTableSqlReq.SettingNotifications { XOLog(sqlstr, whereArgs) } row := &SettingNotifications{} //by Sqlx err = db.Get(row, sqlstr, whereArgs...) if err != nil { if LogTableSqlReq.SettingNotifications { XOLogErr(err) } return nil, err } row._exists = true OnSettingNotifications_LoadOne(row) return row, nil } func (u *__SettingNotifications_Selector) GetRows(db *sqlx.DB) ([]*SettingNotifications, error) { var err error sqlstr, whereArgs := u._stoSql() if LogTableSqlReq.SettingNotifications { XOLog(sqlstr, whereArgs) } var rows []*SettingNotifications //by Sqlx err = db.Unsafe().Select(&rows, sqlstr, whereArgs...) if err != nil { if LogTableSqlReq.SettingNotifications { XOLogErr(err) } return nil, err } /*for i:=0;i< len(rows);i++ { rows[i]._exists = true }*/ for i := 0; i < len(rows); i++ { rows[i]._exists = true } OnSettingNotifications_LoadMany(rows) return rows, nil } //dep use GetRows() func (u *__SettingNotifications_Selector) GetRows2(db *sqlx.DB) ([]SettingNotifications, error) { var err error sqlstr, whereArgs := u._stoSql() if LogTableSqlReq.SettingNotifications { XOLog(sqlstr, whereArgs) } var rows []*SettingNotifications //by Sqlx err = db.Unsafe().Select(&rows, sqlstr, whereArgs...) if err != nil { if LogTableSqlReq.SettingNotifications { XOLogErr(err) } return nil, err } /*for i:=0;i< len(rows);i++ { rows[i]._exists = true }*/ for i := 0; i < len(rows); i++ { rows[i]._exists = true } OnSettingNotifications_LoadMany(rows) rows2 := make([]SettingNotifications, len(rows)) for i := 0; i < len(rows); i++ { cp := *rows[i] rows2[i] = cp } return rows2, nil } func (u *__SettingNotifications_Selector) GetString(db *sqlx.DB) (string, error) { var err error sqlstr, whereArgs := u._stoSql() if LogTableSqlReq.SettingNotifications { XOLog(sqlstr, whereArgs) } var res string //by Sqlx err = db.Get(&res, sqlstr, whereArgs...) if err != nil { if LogTableSqlReq.SettingNotifications { XOLogErr(err) } return "", err } return res, nil } func (u *__SettingNotifications_Selector) GetStringSlice(db *sqlx.DB) ([]string, error) { var err error sqlstr, whereArgs := u._stoSql() if LogTableSqlReq.SettingNotifications { XOLog(sqlstr, whereArgs) } var rows []string //by Sqlx err = db.Select(&rows, sqlstr, whereArgs...) if err != nil { if LogTableSqlReq.SettingNotifications { XOLogErr(err) } return nil, err } return rows, nil } func (u *__SettingNotifications_Selector) GetIntSlice(db *sqlx.DB) ([]int, error) { var err error sqlstr, whereArgs := u._stoSql() if LogTableSqlReq.SettingNotifications { XOLog(sqlstr, whereArgs) } var rows []int //by Sqlx err = db.Select(&rows, sqlstr, whereArgs...) if err != nil { if LogTableSqlReq.SettingNotifications { XOLogErr(err) } return nil, err } return rows, nil } func (u *__SettingNotifications_Selector) GetInt(db *sqlx.DB) (int, error) { var err error sqlstr, whereArgs := u._stoSql() if LogTableSqlReq.SettingNotifications { XOLog(sqlstr, whereArgs) } var res int //by Sqlx err = db.Get(&res, sqlstr, whereArgs...) if err != nil { if LogTableSqlReq.SettingNotifications { XOLogErr(err) } return 0, err } return res, nil } ///////////////////////// Queryer Update Delete ////////////////////////////////// func (u *__SettingNotifications_Updater) Update(db XODB) (int, error) { var err error var updateArgs []interface{} var sqlUpdateArr []string /*for up, newVal := range u.updates { sqlUpdateArr = append(sqlUpdateArr, up) updateArgs = append(updateArgs, newVal) }*/ for _, up := range u.updates { sqlUpdateArr = append(sqlUpdateArr, up.col) updateArgs = append(updateArgs, up.val) } sqlUpdate := strings.Join(sqlUpdateArr, ",") sqlWherrs, whereArgs := whereClusesToSql(u.wheres, u.whereSep) var allArgs []interface{} allArgs = append(allArgs, updateArgs...) allArgs = append(allArgs, whereArgs...) sqlstr := `UPDATE sun.setting_notifications SET ` + sqlUpdate if len(strings.Trim(sqlWherrs, " ")) > 0 { //2 for safty sqlstr += " WHERE " + sqlWherrs } if LogTableSqlReq.SettingNotifications { XOLog(sqlstr, allArgs) } res, err := db.Exec(sqlstr, allArgs...) if err != nil { if LogTableSqlReq.SettingNotifications { XOLogErr(err) } return 0, err } num, err := res.RowsAffected() if err != nil { if LogTableSqlReq.SettingNotifications { XOLogErr(err) } return 0, err } return int(num), nil } func (d *__SettingNotifications_Deleter) Delete(db XODB) (int, error) { var err error var wheresArr []string for _, w := range d.wheres { wheresArr = append(wheresArr, w.condition) } wheresStr := strings.Join(wheresArr, d.whereSep) var args []interface{} for _, w := range d.wheres { args = append(args, w.args...) } sqlstr := "DELETE FROM sun.setting_notifications WHERE " + wheresStr // run query if LogTableSqlReq.SettingNotifications { XOLog(sqlstr, args) } res, err := db.Exec(sqlstr, args...) if err != nil { if LogTableSqlReq.SettingNotifications { XOLogErr(err) } return 0, err } // retrieve id num, err := res.RowsAffected() if err != nil { if LogTableSqlReq.SettingNotifications { XOLogErr(err) } return 0, err } return int(num), nil } ///////////////////////// Mass insert - replace for SettingNotifications //////////////// func MassInsert_SettingNotifications(rows []SettingNotifications, db XODB) error { if len(rows) == 0 { return errors.New("rows slice should not be empty - inserted nothing") } var err error ln := len(rows) // insVals_:= strings.Repeat(s, ln) // insVals := insVals_[0:len(insVals_)-1] insVals := helper.SqlManyDollars(20, ln, true) // sql query sqlstr := "INSERT INTO sun.setting_notifications (" + "UserId, SocialLedOn, SocialLedColor, ReqestToFollowYou, FollowedYou, AccptedYourFollowRequest, YourPostLiked, YourPostCommented, MenthenedYouInPost, MenthenedYouInComment, YourContactsJoined, DirectMessage, DirectAlert, DirectPerview, DirectLedOn, DirectLedColor, DirectVibrate, DirectPopup, DirectSound, DirectPriority" + ") VALUES " + insVals // run query vals := make([]interface{}, 0, ln*5) //5 fields for _, row := range rows { // vals = append(vals,row.UserId) vals = append(vals, row.UserId) vals = append(vals, row.SocialLedOn) vals = append(vals, row.SocialLedColor) vals = append(vals, row.ReqestToFollowYou) vals = append(vals, row.FollowedYou) vals = append(vals, row.AccptedYourFollowRequest) vals = append(vals, row.YourPostLiked) vals = append(vals, row.YourPostCommented) vals = append(vals, row.MenthenedYouInPost) vals = append(vals, row.MenthenedYouInComment) vals = append(vals, row.YourContactsJoined) vals = append(vals, row.DirectMessage) vals = append(vals, row.DirectAlert) vals = append(vals, row.DirectPerview) vals = append(vals, row.DirectLedOn) vals = append(vals, row.DirectLedColor) vals = append(vals, row.DirectVibrate) vals = append(vals, row.DirectPopup) vals = append(vals, row.DirectSound) vals = append(vals, row.DirectPriority) } if LogTableSqlReq.SettingNotifications { XOLog(sqlstr, " MassInsert len = ", ln, vals) } _, err = db.Exec(sqlstr, vals...) if err != nil { if LogTableSqlReq.SettingNotifications { XOLogErr(err) } return err } return nil } func MassReplace_SettingNotifications(rows []SettingNotifications, db XODB) error { if len(rows) == 0 { return errors.New("rows slice should not be empty - inserted nothing") } var err error ln := len(rows) // insVals_:= strings.Repeat(s, ln) // insVals := insVals_[0:len(insVals_)-1] insVals := helper.SqlManyDollars(20, ln, true) // sql query sqlstr := "REPLACE INTO sun.setting_notifications (" + "UserId, SocialLedOn, SocialLedColor, ReqestToFollowYou, FollowedYou, AccptedYourFollowRequest, YourPostLiked, YourPostCommented, MenthenedYouInPost, MenthenedYouInComment, YourContactsJoined, DirectMessage, DirectAlert, DirectPerview, DirectLedOn, DirectLedColor, DirectVibrate, DirectPopup, DirectSound, DirectPriority" + ") VALUES " + insVals // run query vals := make([]interface{}, 0, ln*5) //5 fields for _, row := range rows { // vals = append(vals,row.UserId) vals = append(vals, row.UserId) vals = append(vals, row.SocialLedOn) vals = append(vals, row.SocialLedColor) vals = append(vals, row.ReqestToFollowYou) vals = append(vals, row.FollowedYou) vals = append(vals, row.AccptedYourFollowRequest) vals = append(vals, row.YourPostLiked) vals = append(vals, row.YourPostCommented) vals = append(vals, row.MenthenedYouInPost) vals = append(vals, row.MenthenedYouInComment) vals = append(vals, row.YourContactsJoined) vals = append(vals, row.DirectMessage) vals = append(vals, row.DirectAlert) vals = append(vals, row.DirectPerview) vals = append(vals, row.DirectLedOn) vals = append(vals, row.DirectLedColor) vals = append(vals, row.DirectVibrate) vals = append(vals, row.DirectPopup) vals = append(vals, row.DirectSound) vals = append(vals, row.DirectPriority) } if LogTableSqlReq.SettingNotifications { XOLog(sqlstr, " MassReplace len = ", ln, vals) } _, err = db.Exec(sqlstr, vals...) if err != nil { if LogTableSqlReq.SettingNotifications { XOLogErr(err) } return err } return nil } //////////////////// Play /////////////////////////////// // // // // // // // // // // // // // // // // // // // //
package live import ( "backend/api" "backend/internal/fixture" simulator "backend/internal/simulation" "database/sql" "encoding/json" "github.com/gin-gonic/gin" "github.com/gorilla/websocket" "log" "time" ) var upgrader = websocket.Upgrader{} const timeScale float64 = 5.0/60.0 var simulations []*simulator.Simulator var currentGames []*api.Game func SimulateGames(games []*api.Game) { currentGames = make([]*api.Game, 0, len(games)) for _, v := range games { sim := simulator.SimulateGame(v, timeScale) simulations = append(simulations, sim) currentGames = append(currentGames, v) } } func Route(router gin.IRouter, db *sql.DB) { router.GET("/live", func(context *gin.Context) { fixturesDb := fixture.NewRepository(db) fix, err := fixturesDb.GetFullFixture() if err != nil { panic(err) } c, err := upgrader.Upgrade(context.Writer, context.Request, nil) if err != nil { log.Print("upgrade:", err) return } defer c.Close() if len(currentGames) == 0 { SimulateGames(fix.Games) } for { time.Sleep(time.Second) var gameState = make([]api.GameState, 0, len(simulations)) for _, v := range simulations { gameState = append(gameState, api.GameState{ Time: v.GetTime(), Game: v.GetGame(), }) } message, err := json.Marshal(gameState) if err != nil { log.Print(err.Error()) break } err = c.WriteMessage(websocket.TextMessage, message) } }) }
package rest import ( "github.com/HNB-ECO/HNB-Blockchain/HNB/appMgr" appComm "github.com/HNB-ECO/HNB-Blockchain/HNB/appMgr/common" "github.com/HNB-ECO/HNB-Blockchain/HNB/common" "github.com/HNB-ECO/HNB-Blockchain/HNB/config" "github.com/HNB-ECO/HNB-Blockchain/HNB/contract/hgs" "github.com/HNB-ECO/HNB-Blockchain/HNB/contract/hnb" "github.com/HNB-ECO/HNB-Blockchain/HNB/msp" "github.com/HNB-ECO/HNB-Blockchain/HNB/rlp" "github.com/HNB-ECO/HNB-Blockchain/HNB/txpool" "github.com/HNB-ECO/HNB-Blockchain/HNB/util" "bytes" "encoding/json" "errors" "strconv" "sync" ) func QueryBalanceMsg(params json.RawMessage) (interface{}, error) { dec := json.NewDecoder(bytes.NewReader(params)) if tok, _ := dec.Token(); tok != json.Delim('[') { return nil, errors.New("no [") } if !dec.More() { return nil, errors.New("data not complete") } var chainID, addr string err := dec.Decode(&chainID) if err != nil { return nil, err } if !dec.More() { return nil, errors.New("data not complete") } err = dec.Decode(&addr) if err != nil { return nil, err } if chainID == appComm.HGS { qh := &hgs.QryHgsTx{} qh.TxType = hnb.BALANCE qh.PayLoad = util.HexToByte(addr) qhm, _ := json.Marshal(qh) msg, err := appMgr.Query(chainID, qhm) if err != nil { return nil, err } else { var bal int64 if msg == nil { bal = 0 } else { bal, _ = strconv.ParseInt(string(msg), 10, 64) } return bal, nil } } else if chainID == appComm.HNB { qh := &hnb.QryHnbTx{} qh.TxType = hnb.BALANCE qh.PayLoad = util.HexToByte(addr) qhm, _ := json.Marshal(qh) msg, err := appMgr.Query(chainID, qhm) if err != nil { return nil, err } else { var bal int64 if msg == nil { bal = 0 } else { bal, _ = strconv.ParseInt(string(msg), 10, 64) } return bal, nil } } else { return nil, errors.New("chainID not exist") } return nil, nil } type AccountLock struct { rw sync.RWMutex accLock map[common.Address]*sync.RWMutex } var AccLockMgr AccountLock func (alm *AccountLock) Lock(address common.Address) { alm.rw.Lock() defer alm.rw.Unlock() if alm.accLock == nil { alm.accLock = make(map[common.Address]*sync.RWMutex) } lock, ok := alm.accLock[address] if !ok { lock = &sync.RWMutex{} alm.accLock[address] = lock } lock.Lock() } func (alm *AccountLock) UnLock(address common.Address) { alm.rw.RLock() defer alm.rw.RUnlock() lock, _ := alm.accLock[address] lock.Unlock() } func SendTxMsg(params json.RawMessage) (interface{}, error) { //from //value1 //contractName //to //value2 //contractName //nonceValue // V/R/S dec := json.NewDecoder(bytes.NewReader(params)) if tok, _ := dec.Token(); tok != json.Delim('[') { return nil, errors.New("no [") } if !dec.More() { return nil, errors.New("data not complete") } var rawTransaction string err := dec.Decode(&rawTransaction) if err != nil { return nil, err } msgTx := &common.Transaction{} err = rlp.DecodeBytes(util.FromHex(rawTransaction), msgTx) if err != nil { return nil, err } msgTx.Txid = common.Hash{} //测试使用 if config.Config.RunMode != "dev" { address := msp.AccountPubkeyToAddress() if msgTx.NonceValue == 0 { AccLockMgr.Lock(address) defer AccLockMgr.UnLock(address) nonce := txpool.GetPendingNonce(address) msgTx.NonceValue = nonce } } //msgTx.From = address //signer := msp.GetSigner() //msgTx.Txid = signer.Hash(&msgTx) //msgTxWithSign, err := msp.SignTx(&msgTx, signer) //if err != nil { // msg := fmt.Sprintf("sign err:%v", err.Error()) // retMsg := FormatQueryResResult("0001", msg, nil) // encoder.Encode(retMsg) // return //} signer := msp.GetSigner() msgTx.Txid = signer.Hash(msgTx) mar, _ := json.Marshal(msgTx) err = txpool.RecvTx(mar) if err != nil { return nil, err } return util.ByteToHex(msgTx.Txid.GetBytes()), nil }
package cmd import ( "github.com/alewgbl/fdwctl/internal/config" "github.com/alewgbl/fdwctl/internal/database" "github.com/alewgbl/fdwctl/internal/logger" "github.com/alewgbl/fdwctl/internal/model" "github.com/alewgbl/fdwctl/internal/util" "github.com/spf13/cobra" "strings" ) const ( dropServerCmdMinArgCount = 2 ) var ( dropCmd = &cobra.Command{ Use: "drop", Short: "Drop (delete) objects", PersistentPreRunE: preDoDrop, PersistentPostRun: postDoDrop, } dropExtensionCmd = &cobra.Command{ Use: "extension <extension name>", Short: "Drop a PG extension (usually postgres_fdw)", Run: dropExtension, Args: cobra.MinimumNArgs(1), } dropServerCmd = &cobra.Command{ Use: "server <server name>", Short: "Drop a foreign server", Run: dropServer, Args: cobra.MinimumNArgs(1), } dropUsermapCmd = &cobra.Command{ Use: "usermap <server name> <local user>", Short: "Drop a user mapping for a foreign server", Run: dropUsermap, Args: cobra.MinimumNArgs(dropServerCmdMinArgCount), } dropSchemaCmd = &cobra.Command{ Use: "schema <schema name>", Short: "Drop a schema", Run: dropSchema, Args: cobra.MinimumNArgs(1), } cascadeDrop bool dropLocalUser bool ) func init() { dropUsermapCmd.Flags().BoolVar(&dropLocalUser, "droplocal", false, "also drop the local USER object") dropCmd.PersistentFlags().BoolVar(&cascadeDrop, "cascade", false, "drop objects with CASCADE option") dropCmd.AddCommand(dropExtensionCmd) dropCmd.AddCommand(dropServerCmd) dropCmd.AddCommand(dropUsermapCmd) dropCmd.AddCommand(dropSchemaCmd) } func preDoDrop(cmd *cobra.Command, _ []string) error { var err error log := logger.Log(cmd.Context()). WithField("function", "preDoDrop") dbConnection, err = database.GetConnection(cmd.Context(), config.Instance().GetDatabaseConnectionString()) if err != nil { return logger.ErrorfAsError(log, "error getting database connection: %s", err) } return nil } func postDoDrop(cmd *cobra.Command, _ []string) { database.CloseConnection(cmd.Context(), dbConnection) } func dropExtension(cmd *cobra.Command, args []string) { log := logger.Log(cmd.Context()). WithField("function", "dropExtension") dropExtName := strings.TrimSpace(args[0]) err := util.DropExtension(cmd.Context(), dbConnection, model.Extension{ Name: dropExtName, }) if err != nil { log.Errorf("error dropping extension %s: %s", dropExtName, err) return } log.Infof("extension %s dropped", dropExtName) } func dropServer(cmd *cobra.Command, args []string) { log := logger.Log(cmd.Context()). WithField("function", "dropServer") dsServerName := strings.TrimSpace(args[0]) err := util.DropServer(cmd.Context(), dbConnection, dsServerName, cascadeDrop) if err != nil { log.Errorf("error dropping server: %s", err) return } log.Infof("server %s dropped", dsServerName) } func dropUsermap(cmd *cobra.Command, args []string) { log := logger.Log(cmd.Context()). WithField("function", "dropUsermap") duServerName := strings.TrimSpace(args[0]) if duServerName == "" { log.Errorf("server name is required") return } duLocalUser := strings.TrimSpace(args[1]) if duLocalUser == "" { log.Errorf("local user name is required") return } err := util.DropUserMap(cmd.Context(), dbConnection, model.UserMap{ ServerName: duServerName, LocalUser: duLocalUser, }, dropLocalUser) if err != nil { log.Errorf("error dropping user mapping: %s", err) return } log.Infof("user mapping for %s dropped", duLocalUser) } func dropSchema(cmd *cobra.Command, args []string) { log := logger.Log(cmd.Context()). WithField("function", "dropSchema") dsSchemaName := strings.TrimSpace(args[0]) if dsSchemaName == "" { log.Errorf("schema name is required") return } err := util.DropSchema(cmd.Context(), dbConnection, model.Schema{ LocalSchema: dsSchemaName, }, cascadeDrop) if err != nil { log.Errorf("error dropping schema: %s", err) return } log.Infof("schema %s dropped", dsSchemaName) }
package main import (. "fmt" "runtime" "time" ."net" ) func checkError(err error) { if err != nil { Println("Feil %v", err) return } } func main() { runtime.GOMAXPROCS(runtime.NumCPU()) // limits num of threads to num of cores buffer := make([]byte, 1024) // make an array with size 1024*bytes udp_addr, err := ResolveUDPAddr("udp", ":30000") // store adress of port 30000 into udpAddr, udpAddr hvor vi skal lese fra checkError(err) conn, err := ListenUDP("udp", udp_addr) // open connection for recieving udp messages // conn is a socket (connection), port checkError(err) for { time.Sleep(1000*time.Millisecond) n,err := conn.Read(buffer) // read data from conn into variable buffer checkError(err) Printf("Rcv %d bytes: %s\n",n, buffer) } }
package main import ( "fmt" "math" "github.com/skorobogatov/input" ) type V struct { w int dist int x, y int } type PriorityQueue struct { heap []*V cnt int } func Less(pq *PriorityQueue, i, j int) bool { h := pq.heap return h[i].dist < h[j].dist } func Swap(pq *PriorityQueue, i, j int) { pq.heap[i], pq.heap[j] = pq.heap[j], pq.heap[i] } func Up(pq *PriorityQueue, i int) { for ; i != 0 && Less(pq, i, (i-1)/2); i = (i - 1) / 2 { Swap(pq, i, (i-1)/2) } } func Down(pq *PriorityQueue, i int) { for i < pq.cnt/2 { mi := i*2 + 1 if i*2+2 < pq.cnt && Less(pq, i*2+2, i*2+1) { mi = i*2 + 2 } if Less(pq, i, mi) { return } Swap(pq, i, mi) i = mi } } func Push(pq *PriorityQueue, elem *V) { pq.heap = append(pq.heap, elem) pq.cnt++ Up(pq, pq.cnt-1) } func Pop(pq *PriorityQueue) *V { res := pq.heap[0] pq.cnt-- pq.heap = pq.heap[1:] return res } var graph [][](*V) func main() { var n int var w int input.Scanf("%d", &n) graph = make([][](*V), n) for i := 0; i < n; i++ { graph[i] = make([](*V), n) } for i := 0; i < n; i++ { for j := 0; j < n; j++ { input.Scanf("%d", &w) graph[i][j] = &V{w, math.MaxInt16, i, j} } } dist := dijkstra(n) fmt.Printf("%d", dist) } func dijkstra(n int) int { var next, current *V pq := &PriorityQueue{make([](*V), 0, n), 0} graph[0][0].dist = 0 Push(pq, graph[0][0]) dx := [4]int{0, 0, -1, 1} dy := [4]int{-1, 1, 0, 0} for pq.cnt != 0 { current = Pop(pq) x := current.x y := current.y for i := 0; i < 4; i++ { if x+dx[i] < n && x+dx[i] >= 0 && y+dy[i] < n && y+dy[i] >= 0 { nextX := x + dx[i] nextY := y + dy[i] next = graph[nextX][nextY] w := graph[nextX][nextY].w if w+current.dist < next.dist { next.dist = w + current.dist Push(pq, next) } } } } return graph[n-1][n-1].dist + graph[0][0].w }
package leetcode import "testing" func TestDetectCycle(t *testing.T) { l := &ListNode{} h := l for i := 1; i < 6; i++ { l.Val, l.Next = i, &ListNode{} l = l.Next } l.Next = h.Next s := detectCycle(h) if s == nil { t.Log("nil") } else { t.Log(s.Val) } }
package license import ( "encoding/base64" "encoding/json" "time" ) // Data is the data we expect in the license type Data struct { CustomerEmail string `json:"customer_email"` CreateTime time.Time `json:"create_time"` } // SetTime will load the current time into "data". Duration as -1 to remove // the monotonic clock that time.Now() adds by default func (d *Data) SetTime() { d.CreateTime = time.Now().Truncate(time.Duration(-1)) } // Encode the data into base64 by first converting into json func (d Data) Encode() (string, error) { jData, err := json.Marshal(d) if err != nil { return "", err } return base64.StdEncoding.EncodeToString(jData), nil } // Decode takes a base64 string, decodes it, and the loads the json into Data func Decode(str string) (d Data, err error) { jData, err := base64.StdEncoding.DecodeString(str) if err != nil { return } err = json.Unmarshal(jData, &d) return }
// Copyright 2020 Clivern. All rights reserved. // Use of this source code is governed by the MIT // license that can be found in the LICENSE file. package model import ( "fmt" "strings" "time" "github.com/clivern/walrus/core/driver" "github.com/clivern/walrus/core/util" log "github.com/sirupsen/logrus" "github.com/spf13/viper" ) // Host type type Host struct { db driver.Database } // HostData type type HostData struct { ID string `json:"id"` Hostname string `json:"hostname"` CreatedAt int64 `json:"createdAt"` UpdatedAt int64 `json:"updatedAt"` } // NewHostStore creates a new instance func NewHostStore(db driver.Database) *Host { result := new(Host) result.db = db return result } // CreateHost creates a host func (h *Host) CreateHost(hostData HostData) error { hostData.ID = util.GenerateUUID4() hostData.CreatedAt = time.Now().Unix() hostData.UpdatedAt = time.Now().Unix() result, err := util.ConvertToJSON(hostData) if err != nil { return err } log.WithFields(log.Fields{ "host_id": hostData.ID, "hostname": hostData.Hostname, }).Debug("Create an agent") // store agent data err = h.db.Put(fmt.Sprintf( "%s/host/%s/h-data", viper.GetString(fmt.Sprintf("%s.database.etcd.databaseName", viper.GetString("role"))), hostData.Hostname, ), result) if err != nil { return err } return nil } // UpdateHost updates a host func (h *Host) UpdateHost(hostData HostData) error { hostData.UpdatedAt = time.Now().Unix() result, err := util.ConvertToJSON(hostData) if err != nil { return err } log.WithFields(log.Fields{ "host_id": hostData.ID, "hostname": hostData.Hostname, }).Debug("Update host") // store agent status err = h.db.Put(fmt.Sprintf( "%s/host/%s/h-data", viper.GetString(fmt.Sprintf("%s.database.etcd.databaseName", viper.GetString("role"))), hostData.Hostname, ), result) if err != nil { return err } return nil } // GetHost gets a host func (h *Host) GetHost(hostname string) (*HostData, error) { hostData := &HostData{} log.WithFields(log.Fields{ "hostname": hostname, }).Debug("Get a host") data, err := h.db.Get(fmt.Sprintf( "%s/host/%s/h-data", viper.GetString(fmt.Sprintf("%s.database.etcd.databaseName", viper.GetString("role"))), hostname, )) if err != nil { return hostData, err } for k, v := range data { // Check if it is the data key if strings.Contains(k, "/h-data") { err = util.LoadFromJSON(hostData, []byte(v)) if err != nil { return hostData, err } return hostData, nil } } return hostData, fmt.Errorf( "Unable to find host with name: %s", hostname, ) } // GetHosts get hosts func (h *Host) GetHosts() ([]*HostData, error) { log.Debug("Get hosts") records := make([]*HostData, 0) data, err := h.db.Get(fmt.Sprintf( "%s/host", viper.GetString(fmt.Sprintf("%s.database.etcd.databaseName", viper.GetString("role"))), )) if err != nil { return records, err } for k, v := range data { // Check if it is the data key if strings.Contains(k, "/h-data") { recordData := &HostData{} err = util.LoadFromJSON(recordData, []byte(v)) if err != nil { return records, err } records = append(records, recordData) } } return records, nil } // DeleteHost deletes a host func (h *Host) DeleteHost(hostname string) (bool, error) { log.WithFields(log.Fields{ "hostname": hostname, }).Debug("Delete a host") count, err := h.db.Delete(fmt.Sprintf( "%s/host/%s", viper.GetString(fmt.Sprintf("%s.database.etcd.databaseName", viper.GetString("role"))), hostname, )) if err != nil { return false, err } return count > 0, nil }
package dbstorage import ( "context" "fmt" "strconv" "strings" "time" // init sql driver _ "github.com/jackc/pgx/stdlib" "github.com/jmoiron/sqlx" "github.com/jmoiron/sqlx/reflectx" "github.com/pkg/errors" "github.com/andywow/golang-lessons/lesson-calendar/internal/calendar/config" "github.com/andywow/golang-lessons/lesson-calendar/internal/calendar/repository" "github.com/andywow/golang-lessons/lesson-calendar/pkg/eventapi" ) // EventDatabase event database type EventDatabase struct { Database *sqlx.DB } // NewDatabaseStorage constructor func NewDatabaseStorage(ctx context.Context, cfg config.DBConfig) (repository.EventRepository, error) { db, err := sqlx.Connect("pgx", fmt.Sprintf("postgres://%s:%s@%s:%d/%s?sslmode=disable", cfg.User, cfg.Password, cfg.Host, cfg.Port, cfg.Database)) if err != nil { return nil, errors.Wrap(err, "could not initialize db") } _, err = db.Query("SELECT 1") if err != nil { return nil, errors.Wrap(err, "could not execute test query") } db.SetMaxIdleConns(1) db.SetMaxOpenConns(10) // map json fields from protobuf annotations db.Mapper = reflectx.NewMapperFunc("json", func(str string) string { return str }) eventDatabase := EventDatabase{ Database: db, } go func() { <-ctx.Done() db.Close() }() return &eventDatabase, nil } // CheckIfTimeIsBusy check if event time is busy func (s *EventDatabase) CheckIfTimeIsBusy(ctx context.Context, event *eventapi.Event) error { if err := s.verifyConnection(ctx); err != nil { return err } var err error intUUID := 0 if event.Uuid != "" { intUUID, err = strconv.Atoi(event.Uuid) if err != nil { return errors.Wrap(repository.ErrInvalidData, "invalid uuid data") } } rs, err := s.Database.NamedQueryContext(ctx, `select count(*) as count from calendar.event where uuid!=:uuid and username=:username and deleted=false and ( (:start_time>=start_time and :start_time<start_time + duration * interval '1 minute') or (:end_time>start_time and :end_time<=start_time + duration * interval '1 minute') )`, map[string]interface{}{ "uuid": intUUID, "username": event.Username, "start_time": event.StartTime, "end_time": event.StartTime.Add(time.Duration(event.Duration) * time.Minute), }) if err != nil { return errors.Wrap(err, "could not execute check time statement") } if rs.Next() { var count int64 err := rs.Scan(&count) if err != nil { return errors.Wrap(err, "could not parse select result") } if count != 0 { return repository.ErrDateBusy } return nil } return errors.New("could not get select result") } // Close connection func (s *EventDatabase) Close() error { if err := s.Database.Close(); err != nil { return errors.Wrap(err, "fail to close connection") } return nil } // CreateEvent create event func (s *EventDatabase) CreateEvent(ctx context.Context, event *eventapi.Event) error { if err := s.verifyConnection(ctx); err != nil { return err } rs, err := s.Database.NamedQueryContext(ctx, `insert into calendar.event (start_time, duration, header, description, username, notification_period) values(:start_time, :duration, :header, :description, :username, :notification_period) returning uuid`, event) if err != nil { return errors.Wrap(err, "could not create new event") } if rs.Next() { err := rs.Scan(&event.Uuid) if err != nil { return errors.Wrap(err, "could not get id for new event") } return nil } return repository.ErrGetQueryResult } // GetEventsForDate get events for 1 day func (s *EventDatabase) GetEventsForDate(ctx context.Context, date time.Time) ([]*eventapi.Event, error) { startTime := date.Truncate(24 * time.Hour) endTime := date.Truncate(24 * time.Hour).Add(24 * time.Hour) return s.getEvents(ctx, startTime, endTime) } // GetEventsForWeek get events for week func (s *EventDatabase) GetEventsForWeek(ctx context.Context, date time.Time) ([]*eventapi.Event, error) { startTime := date.Truncate(24 * time.Hour) endTime := date.Truncate(24 * time.Hour).Add(24 * 7 * time.Hour) return s.getEvents(ctx, startTime, endTime) } // GetEventsForMonth get events for month func (s *EventDatabase) GetEventsForMonth(ctx context.Context, date time.Time) ([]*eventapi.Event, error) { startTime := date.Truncate(24 * time.Hour) endTime := date.Truncate(24*time.Hour).AddDate(0, 1, 0) return s.getEvents(ctx, startTime, endTime) } // GetEventsForNotification get events for send notifications func (s *EventDatabase) GetEventsForNotification(ctx context.Context, date time.Time) ([]*eventapi.Event, error) { if err := s.verifyConnection(ctx); err != nil { return nil, err } rs, err := s.Database.NamedQueryContext(ctx, `select uuid, start_time, duration, header, description, username, notification_period from calendar.event where deleted=false and notification_period!=0 and start_time - :current_time = notification_period * interval '1 minute'`, map[string]interface{}{ "current_time": date, }) if err != nil { return nil, errors.Wrap(err, "could not execute get event for notification statement") } events := []*eventapi.Event{} for rs.Next() { var event eventapi.Event if err := rs.StructScan(&event); err != nil { return nil, errors.Wrap(err, "could not parse select result") } events = append(events, &event) } return events, nil } // DeleteEvent delete event func (s *EventDatabase) DeleteEvent(ctx context.Context, uuid string) error { if err := s.verifyConnection(ctx); err != nil { return err } rs, err := s.Database.ExecContext(ctx, `update calendar.event set deleted=true where uuid=$1`, uuid) if err != nil { return errors.Wrap(err, "could not execute delete query") } rowCount, err := rs.RowsAffected() if err != nil { return errors.Wrap(err, "could not get deleted rows") } if rowCount == 0 { return repository.ErrEventNotFound } return nil } // UpdateEvent update event func (s *EventDatabase) UpdateEvent(ctx context.Context, event *eventapi.Event) error { if err := s.verifyConnection(ctx); err != nil { return err } query := "update calendar.event set " fields := []string{} if event.StartTime != nil { fields = append(fields, "start_time=:start_time") } if event.Duration != 0 { fields = append(fields, "duration=:duration") } if event.Header != "" { fields = append(fields, "header=:header") } if event.Description != "" { fields = append(fields, "description=:description") } if event.NotificationPeriod != 0 { fields = append(fields, "notification_period=:notification_period") } if len(fields) == 0 { return errors.Wrap(repository.ErrInvalidData, "no fields to update") } query = query + strings.Join(fields, ",") query = query + " where uuid=:uuid returning uuid" rs, err := s.Database.NamedQueryContext(ctx, query, event) if err != nil { return errors.Wrap(err, "could not execute update query") } if rs.Next() { if err := rs.Scan(&event.Uuid); err != nil { return errors.Wrap(err, "could not get id for updated event") } return nil } return repository.ErrEventNotFound } // check connection func (s *EventDatabase) verifyConnection(ctx context.Context) error { if err := s.Database.PingContext(ctx); err != nil { return errors.Wrap(repository.ErrStorageUnavailable, err.Error()) } return nil } func (s *EventDatabase) getEvents(ctx context.Context, startDate, endDate time.Time) ([]*eventapi.Event, error) { if err := s.verifyConnection(ctx); err != nil { return nil, err } rs, err := s.Database.NamedQueryContext(ctx, `select uuid, start_time, duration, header, description, username, notification_period from calendar.event where deleted=false and start_time>=:start_time and start_time<=:end_time`, map[string]interface{}{ "start_time": startDate, "end_time": endDate, }) if err != nil { return nil, errors.Wrap(err, "could not execute get event statement") } events := []*eventapi.Event{} for rs.Next() { var event eventapi.Event if err := rs.StructScan(&event); err != nil { return nil, errors.Wrap(err, "could not parse select result") } events = append(events, &event) } return events, nil }
// *** *** *** *** *** *** *** *** // signFind is a small backend utility/API to // serve media for SignFind Android/iOS App. // *** *** *** *** *** *** *** *** // Milla Says AS (C) 2017 // By Roy Dybing // github.com: rDybing // slack.com: rdybing // https://github.com/rDybing/SignFindBackEnd // *** *** *** *** *** *** *** *** package main import ( "fmt" "math/rand" "time" "github.com/rDybing/SignFindBackEnd/chores" "github.com/rDybing/SignFindBackEnd/httpIO" ) func main() { var input string var quit bool rand.Seed(time.Now().UnixNano()) //postgres.Initialize() go API.Initialize() time.Sleep(1 * time.Second) help() for quit == false { fmt.Scanf("%s\n", &input) switch input { case "help": help() case "words": API.ReloadWordsList() case "networds": API.ReloadNetWordsList() case "welcome": API.ReloadWelcome() case "files": testFileNames() case "test": test() case "quit": quit = true } } chores.CloseApp("Bahbah") } func help() { ver := API.GetVer() fmt.Println("---------------------") fmt.Printf("-- signFind %s --\n", ver) fmt.Println("---------------------") fmt.Println("Available Commands:") fmt.Println(" - help | list of commands") fmt.Println(" - words | reloads the words-list") fmt.Println(" - networds | reloads test-network words list") fmt.Println(" - welcome | reloads welcome message") fmt.Println(" - files | runs a test to see files match wordslist") fmt.Println(" - test | runs a test if any available") fmt.Println(" - quit | exit this application") } func testFileNames() { // do stuff fmt.Println("Coming soon... (tm)") } func test() { // do tests }
package connection import ( "bytes" "compress/zlib" "context" "crypto/sha256" "crypto/tls" "crypto/x509" "database/sql/driver" "encoding/hex" "encoding/json" "fmt" "io" "net/url" "strings" "github.com/exasol/exasol-driver-go/internal/utils" "github.com/exasol/exasol-driver-go/pkg/errors" "github.com/exasol/exasol-driver-go/pkg/logger" "github.com/exasol/exasol-driver-go/pkg/types" "github.com/gorilla/websocket" ) func (c *Connection) getURIScheme() string { if c.Config.Encryption { return "wss" } else { return "ws" } } func (c *Connection) Connect() error { hosts, err := utils.ResolveHosts(c.Config.Host) if err != nil { return err } utils.ShuffleHosts(hosts) for _, host := range hosts { url := url.URL{ Scheme: c.getURIScheme(), Host: fmt.Sprintf("%s:%d", host, c.Config.Port), } skipVerify := !c.Config.ValidateServerCertificate || c.Config.CertificateFingerprint != "" dialer := *websocket.DefaultDialer dialer.TLSClientConfig = &tls.Config{ InsecureSkipVerify: skipVerify, //nolint:gosec CipherSuites: []uint16{ tls.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384, // Workaround, set db suit in first place to fix handshake issue tls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, tls.TLS_RSA_WITH_3DES_EDE_CBC_SHA, tls.TLS_RSA_WITH_AES_128_CBC_SHA, tls.TLS_RSA_WITH_AES_256_CBC_SHA, tls.TLS_RSA_WITH_AES_128_GCM_SHA256, tls.TLS_RSA_WITH_AES_256_GCM_SHA384, tls.TLS_AES_128_GCM_SHA256, tls.TLS_AES_256_GCM_SHA384, tls.TLS_CHACHA20_POLY1305_SHA256, tls.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, tls.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA, tls.TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA, tls.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA, tls.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA, tls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, tls.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384, tls.TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256, tls.TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256, }, VerifyPeerCertificate: c.verifyPeerCertificate, } var ws *websocket.Conn ws, _, err = dialer.DialContext(c.Ctx, url.String(), nil) if err == nil { c.websocket = ws c.websocket.EnableWriteCompression(false) break } else { logger.ErrorLogger.Print(errors.NewConnectionFailedError(url, err)) } } return err } func (c *Connection) verifyPeerCertificate(rawCerts [][]byte, verifiedChains [][]*x509.Certificate) error { expectedFingerprint := c.Config.CertificateFingerprint if len(expectedFingerprint) == 0 { return nil } if len(rawCerts) == 0 { return errors.ErrMissingServerCertificate } actualFingerprint := sha256Hex(rawCerts[0]) if !strings.EqualFold(expectedFingerprint, actualFingerprint) { return errors.NewErrCertificateFingerprintMismatch(actualFingerprint, expectedFingerprint) } return nil } func sha256Hex(data []byte) string { sha256Sum := sha256.Sum256(data) return bytesToHexString(sha256Sum[:]) } func bytesToHexString(data []byte) string { return hex.EncodeToString(data) } func (c *Connection) Send(ctx context.Context, request, response interface{}) error { receiver, err := c.asyncSend(request) if err != nil { return err } channel := make(chan error, 1) go func() { channel <- receiver(response) }() select { case <-ctx.Done(): _, err := c.asyncSend(&types.Command{Command: "abortQuery"}) if err != nil { return errors.NewErrCouldNotAbort(ctx.Err()) } return ctx.Err() case err := <-channel: return err } } func (c *Connection) asyncSend(request interface{}) (func(interface{}) error, error) { message, err := json.Marshal(request) if err != nil { logger.ErrorLogger.Print(errors.NewMarshallingError(request, err)) return nil, driver.ErrBadConn } messageType := websocket.TextMessage if c.Config.Compression { var b bytes.Buffer w := zlib.NewWriter(&b) _, err = w.Write(message) if err != nil { return nil, err } w.Close() message = b.Bytes() messageType = websocket.BinaryMessage } err = c.websocket.WriteMessage(messageType, message) if err != nil { logger.ErrorLogger.Print(errors.NewRequestSendingError(err)) return nil, driver.ErrBadConn } return c.callback(), nil } func (c *Connection) callback() func(response interface{}) error { return func(response interface{}) error { _, message, err := c.websocket.ReadMessage() if err != nil { logger.ErrorLogger.Print(errors.NewReceivingError(err)) return driver.ErrBadConn } result := &types.BaseResponse{} var reader io.Reader reader = bytes.NewReader(message) if c.Config.Compression { reader, err = zlib.NewReader(bytes.NewReader(message)) if err != nil { logger.ErrorLogger.Print(errors.NewUncompressingError(err)) return driver.ErrBadConn } } err = json.NewDecoder(reader).Decode(result) if err != nil { logger.ErrorLogger.Print(errors.NewJsonDecodingError(err)) return driver.ErrBadConn } if result.Status != "ok" { return errors.NewSqlErr(result.Exception.SQLCode, result.Exception.Text) } if response == nil { return nil } return json.Unmarshal(result.ResponseData, response) } }
// Copyright 2023 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 external import ( "context" "io" "testing" "time" "github.com/pingcap/errors" "github.com/stretchr/testify/require" "golang.org/x/exp/rand" ) // mockExtStore is only used for test. type mockExtStore struct { src []byte idx uint64 } func (s *mockExtStore) Read(p []byte) (n int, err error) { // Read from src to p. if s.idx >= uint64(len(s.src)) { return 0, io.EOF } n = copy(p, s.src[s.idx:]) s.idx += uint64(n) return n, nil } func (s *mockExtStore) Seek(_ int64, _ int) (int64, error) { return 0, errors.Errorf("unsupported operation") } func (s *mockExtStore) Close() error { return nil } func TestByteReader(t *testing.T) { // Test basic next() usage. br, err := newByteReader(context.Background(), &mockExtStore{src: []byte("abcde")}, 3) require.NoError(t, err) x := br.next(1) require.Equal(t, 1, len(x)) require.Equal(t, byte('a'), x[0]) x = br.next(2) require.Equal(t, 2, len(x)) require.Equal(t, byte('b'), x[0]) require.Equal(t, byte('c'), x[1]) require.NoError(t, br.Close()) // Test basic readNBytes() usage. br, err = newByteReader(context.Background(), &mockExtStore{src: []byte("abcde")}, 3) require.NoError(t, err) y, err := br.readNBytes(2) require.NoError(t, err) x = *y require.Equal(t, 2, len(x)) require.Equal(t, byte('a'), x[0]) require.Equal(t, byte('b'), x[1]) require.NoError(t, br.Close()) br, err = newByteReader(context.Background(), &mockExtStore{src: []byte("abcde")}, 3) require.NoError(t, err) y, err = br.readNBytes(5) // Read all the data. require.NoError(t, err) x = *y require.Equal(t, 5, len(x)) require.Equal(t, byte('e'), x[4]) require.NoError(t, br.Close()) br, err = newByteReader(context.Background(), &mockExtStore{src: []byte("abcde")}, 3) require.NoError(t, err) _, err = br.readNBytes(7) // EOF require.Error(t, err) ms := &mockExtStore{src: []byte("abcdef")} br, err = newByteReader(context.Background(), ms, 2) require.NoError(t, err) y, err = br.readNBytes(3) require.NoError(t, err) // Pollute mockExtStore to verify if the slice is not affected. copy(ms.src, []byte("xyz")) x = *y require.Equal(t, 3, len(x)) require.Equal(t, byte('c'), x[2]) require.NoError(t, br.Close()) ms = &mockExtStore{src: []byte("abcdef")} br, err = newByteReader(context.Background(), ms, 2) require.NoError(t, err) y, err = br.readNBytes(2) require.NoError(t, err) // Pollute mockExtStore to verify if the slice is not affected. copy(ms.src, []byte("xyz")) x = *y require.Equal(t, 2, len(x)) require.Equal(t, byte('b'), x[1]) br.reset() require.NoError(t, br.Close()) } func TestByteReaderClone(t *testing.T) { ms := &mockExtStore{src: []byte("0123456789")} br, err := newByteReader(context.Background(), ms, 4) require.NoError(t, err) y1, err := br.readNBytes(2) require.NoError(t, err) y2, err := br.readNBytes(1) require.NoError(t, err) x1, x2 := *y1, *y2 require.Len(t, x1, 2) require.Len(t, x2, 1) require.Equal(t, byte('0'), x1[0]) require.Equal(t, byte('2'), x2[0]) require.NoError(t, br.reload()) // Perform a reload to overwrite buffer. x1, x2 = *y1, *y2 require.Len(t, x1, 2) require.Len(t, x2, 1) require.Equal(t, byte('4'), x1[0]) // Verify if the buffer is overwritten. require.Equal(t, byte('6'), x2[0]) require.NoError(t, br.Close()) ms = &mockExtStore{src: []byte("0123456789")} br, err = newByteReader(context.Background(), ms, 4) require.NoError(t, err) y1, err = br.readNBytes(2) require.NoError(t, err) y2, err = br.readNBytes(1) require.NoError(t, err) x1, x2 = *y1, *y2 require.Len(t, x1, 2) require.Len(t, x2, 1) require.Equal(t, byte('0'), x1[0]) require.Equal(t, byte('2'), x2[0]) br.cloneSlices() require.NoError(t, br.reload()) // Perform a reload to overwrite buffer. x1, x2 = *y1, *y2 require.Len(t, x1, 2) require.Len(t, x2, 1) require.Equal(t, byte('0'), x1[0]) // Verify if the buffer is NOT overwritten. require.Equal(t, byte('2'), x2[0]) require.NoError(t, br.Close()) } func TestByteReaderAuxBuf(t *testing.T) { ms := &mockExtStore{src: []byte("0123456789")} br, err := newByteReader(context.Background(), ms, 1) require.NoError(t, err) y1, err := br.readNBytes(1) require.NoError(t, err) y2, err := br.readNBytes(2) require.NoError(t, err) require.Equal(t, []byte("0"), *y1) require.Equal(t, []byte("12"), *y2) y3, err := br.readNBytes(1) require.NoError(t, err) y4, err := br.readNBytes(2) require.NoError(t, err) require.Equal(t, []byte("3"), *y3) require.Equal(t, []byte("45"), *y4) require.Equal(t, []byte("0"), *y1) require.Equal(t, []byte("12"), *y2) } func TestReset(t *testing.T) { seed := time.Now().Unix() rand.Seed(uint64(seed)) t.Logf("seed: %d", seed) src := make([]byte, 256) for i := range src { src[i] = byte(i) } ms := &mockExtStore{src: src} bufSize := rand.Intn(256) br, err := newByteReader(context.Background(), ms, bufSize) require.NoError(t, err) end := 0 toCheck := make([]*[]byte, 0, 10) for end < len(src) { n := rand.Intn(len(src) - end) if n == 0 { n = 1 } y, err := br.readNBytes(n) require.NoError(t, err) toCheck = append(toCheck, y) end += n l := end r := end for i := len(toCheck) - 1; i >= 0; i-- { l -= len(*toCheck[i]) require.Equal(t, src[l:r], *toCheck[i]) r = l } if rand.Intn(2) == 0 { br.reset() toCheck = toCheck[:0] } } _, err = br.readNBytes(1) require.Equal(t, io.EOF, err) } func TestUnexpectedEOF(t *testing.T) { ms := &mockExtStore{src: []byte("0123456789")} br, err := newByteReader(context.Background(), ms, 3) require.NoError(t, err) _, err = br.readNBytes(100) require.ErrorIs(t, err, io.ErrUnexpectedEOF) } func TestEmptyContent(t *testing.T) { ms := &mockExtStore{src: []byte{}} _, err := newByteReader(context.Background(), ms, 100) require.Equal(t, io.EOF, err) }
package lyft import ( "encoding/json" "fmt" "time" "golang.org/x/net/context" ) type PassengerDetail struct { FirstName string `json:"first_name"` LastName string `json:"last_name"` } type DriverDetail struct { FirstName string `json:"first_name"` PhoneNumber string `json:"phone_number"` Rating string `json:"rating"` ImageURL string `json:"image_url"` } type VehicleDetail struct { Make string `json:"make"` Model string `json:"model"` Year int64 `json:"year"` LicensePlate string `json:"license_plate"` LicensePlateState string `json:"license_plate_state"` Color string `json:"color"` ImageURL string `json:"image_url"` } type Location struct { Lat float64 `json:"lat"` Lng float64 `json:"lng"` Address string `json:"address,omitempty"` } type PickupDropoffLocation struct { Location Time *time.Time `json:"time,omitempty"` } type Price struct { Amount int64 `json:"amount"` Currency string `json:"currency"` Description string `json:"description"` } type LineItem struct { Type string `json:"type"` Amount int64 `json:"amount"` Currency string `json:"currency"` } type Charge struct { Amount int64 `json:"amount"` Currency string `json:"currency"` PaymentMethod string `json:"payment_method"` } type CancellationCost struct { Amount int64 `json:"amount"` Currency string `json:"currency"` Description string `json:"description"` Token string `json:"token,omitempty"` TokenDuration *int64 `json:"token_duration,omitempty"` } type RideDetail struct { RideID string `json:"ride_id,omitempty"` Status string `json:"status,omitempty"` RideType string `json:"ride_type,omitempty"` Passenger *PassengerDetail `json:"passenger,omitempty"` Driver *DriverDetail `json:"driver,omitempty"` Vehicle *VehicleDetail `json:"vehicle,omitempty"` Origin *Location `json:"origin,omitempty"` Destination *Location `json:"destination,omitempty"` Pickup *PickupDropoffLocation `json:"pickup,omitempty"` Dropoff *PickupDropoffLocation `json:"dropoff,omitempty"` Location *Location `json:"location,omitempty"` PrimetimePercentage string `json:"primetime_percentage,omitempty"` Price *Price `json:"price,omitempty"` LineItems []LineItem `json:"line_items,omitempty"` CanCancel []string `json:"can_cancel,omitempty"` CanceledBy string `json:"canceled_by,omitempty"` CancellationPrice *CancellationCost `json:"cancellation_price,omitempty"` Rating *int64 `json:"rating,omitempty"` Feedback string `json:"feedback,omitempty"` RouteURL string `json:"route_url,omitempty"` RequestedAt *time.Time `json:"requested_at,omitempty"` *ServerResponse } type ProfileCall struct { *getCall } func (s *Service) Profile() *ProfileCall { return &ProfileCall{newGetCall(s.c, baseURL+"/v1/profile")} } type Profile struct { ID string `json:"id"` *ServerResponse } func (r *ProfileCall) Do(ctx context.Context) (*Profile, error) { resp, err := r.do(ctx) if err != nil { return nil, err } profile := &Profile{ServerResponse: new(ServerResponse)} if err := decode(resp, profile); err != nil { return nil, err } return profile, nil } type rideParams struct { RideType string `json:"ride_type"` Origin Location `json:"origin"` Destination Location `json:"destination,omitempty"` PrimetimeConfirmationToken string `json:"primetime_confirmation_token,omitempty"` } type RidesCall struct { *postCall data *rideParams } func (s *Service) RequestRide(ridetype string, orig Location) *RidesCall { data := &rideParams{Origin: orig, RideType: ridetype} return &RidesCall{&postCall{s.c, baseURL + "/v1/rides"}, data} } func (r *RidesCall) Destination(dest Location) *RidesCall { r.data.Destination = dest return r } func (r *RidesCall) Primetime(s string) *RidesCall { r.data.PrimetimeConfirmationToken = s return r } type RideToken struct { *Err PrimetimePercentage string `json:"primetime_percentage"` PrimetimeConfirmationToken string `json:"primetime_confirmation_token"` TokenDuration int64 `json:"token_duration"` } type RideRequest struct { RideID string `json:"ride_id,omitempty"` Status string `json:"status,omitempty"` Origin *Location `json:"origin,omitempty"` Destination *Location `json:"destination,omitempty"` Passenger *PassengerDetail `json:"passenger,omitempty"` *ServerResponse } func (r *RidesCall) Do(ctx context.Context) (*RideRequest, error) { resp, err := r.do(ctx, r.data) if err != nil { return nil, err } defer resp.Body.Close() if !success(resp) { e := newError(resp) if e.Err == "primetime_confirmation_required" { rt := &RideToken{Err: e} json.Unmarshal([]byte(e.Body), rt) return nil, rt } return nil, e } ride := &RideRequest{ServerResponse: &ServerResponse{resp.StatusCode, resp.Header}} if err = json.NewDecoder(resp.Body).Decode(ride); err != nil { return nil, err } return ride, nil } func PrimetimeConfirmationNeeded(err error) *RideToken { rt, _ := err.(*RideToken) return rt } type RideDetailsCall struct { *getCall } func (s *Service) RideDetails(rideID string) *RideDetailsCall { urlStr := fmt.Sprintf("https://api.lyft.com/v1/rides/%s", rideID) return &RideDetailsCall{newGetCall(s.c, urlStr)} } func (r *RideDetailsCall) Do(ctx context.Context) (*RideDetail, error) { resp, err := r.do(ctx) if err != nil { return nil, err } details := &RideDetail{ServerResponse: new(ServerResponse)} if err := decode(resp, details); err != nil { return nil, err } return details, nil } type cancelParams struct { CancelConfirmationToken string `json:"cancel_confirmation_token,omitempty"` } type CancelCall struct { *postCall data *cancelParams } func (s *Service) Cancel(rideID string) *CancelCall { urlStr := fmt.Sprintf("https://api.lyft.com/v1/rides/%s/cancel", rideID) return &CancelCall{&postCall{s.c, urlStr}, new(cancelParams)} } func (c *CancelCall) Token(s string) *CancelCall { c.data.CancelConfirmationToken = s return c } type CancelToken struct { *Err Amount int64 `json:"amount"` Currency string `json:"currency"` Token string `json:"token"` TokenDuration int64 `json:"token_duration"` } type Cancel struct { *ServerResponse } func (c *CancelCall) Do(ctx context.Context) (*Cancel, error) { resp, err := c.do(ctx, c.data) if err != nil { return nil, err } defer resp.Body.Close() if !success(resp) { e := newError(resp) if e.Err == "cancel_confirmation_required" { ct := &CancelToken{Err: e} json.Unmarshal([]byte(e.Body), ct) return nil, ct } return nil, e } cancel := &Cancel{ServerResponse: &ServerResponse{resp.StatusCode, resp.Header}} if err = json.NewDecoder(resp.Body).Decode(cancel); err != nil { return nil, err } return cancel, nil } func CancelConfirmationNeeded(err error) *CancelToken { ct, _ := err.(*CancelToken) return ct } type ratingParams struct { Rating int64 `json:"rating"` Feedback string `json:"feedback,omitempty"` Amount *int64 `json:"amount,omitempty"` Currency string `json:"currency,omitempty"` } type RatingCall struct { *putCall data *ratingParams } func (s *Service) Rate(rideID string, rating int64) *RatingCall { urlStr := fmt.Sprintf("https://api.lyft.com/v1/rides/%s/rating", rideID) data := &ratingParams{Rating: rating} return &RatingCall{&putCall{s.c, urlStr}, data} } func (r *RatingCall) Feedback(s string) *RatingCall { r.data.Feedback = s return r } func (r *RatingCall) Amount(amount int64) *RatingCall { r.data.Amount = &amount return r } func (r *RatingCall) Currency(currency string) *RatingCall { r.data.Currency = currency return r } type Rating struct { *ServerResponse } func (r *RatingCall) Do(ctx context.Context) (*Rating, error) { resp, err := r.do(ctx, r.data) if err != nil { return nil, err } rating := &Rating{ServerResponse: new(ServerResponse)} if err := decode(resp, rating); err != nil { return nil, err } return rating, nil } type ReceiptCall struct { *getCall } func (s *Service) Receipt(rideID string) *ReceiptCall { urlStr := fmt.Sprintf("https://api.lyft.com/v1/rides/%s/receipts", rideID) return &ReceiptCall{newGetCall(s.c, urlStr)} } type RideReceipt struct { RideID string `json:"ride_id,omitempty"` Price *Price `json:"price,omitempty"` LineItems []LineItem `json:"line_items,omitempty"` Charges []Charge `json:"charges,omitempty"` RequestedAt *time.Time `json:"requested_at,omitempty"` *ServerResponse } func (r *ReceiptCall) Do(ctx context.Context) (*RideReceipt, error) { resp, err := r.do(ctx) if err != nil { return nil, err } receipt := &RideReceipt{ServerResponse: new(ServerResponse)} if err := decode(resp, receipt); err != nil { return nil, err } return receipt, nil } type HistoryCall struct { *getCall } func (s *Service) History(start time.Time) *HistoryCall { h := &HistoryCall{newGetCall(s.c, baseURL+"/v1/rides")} h.params.Set("start_time", start.Format(time.RFC3339)) return h } func (h *HistoryCall) EndTime(end time.Time) *HistoryCall { h.params.Set("end_time", end.Format(time.RFC3339)) return h } func (h *HistoryCall) Limit(limit int) *HistoryCall { h.params.Set("limit", fmt.Sprintf("%d", limit)) return h } type History struct { RideHistory []RideDetail `json:"ride_history"` *ServerResponse } func (h *HistoryCall) Do(ctx context.Context) (*History, error) { resp, err := h.do(ctx) if err != nil { return nil, err } history := &History{ServerResponse: new(ServerResponse)} if err := decode(resp, history); err != nil { return nil, err } return history, nil } type UpdateDestinationCall struct { *putCall data *Location } func (s *Service) UpdateDestination(rideID string, dest Location) *UpdateDestinationCall { urlStr := fmt.Sprintf("https://api.lyft.com/v1/rides/%s/destination", rideID) return &UpdateDestinationCall{&putCall{s.c, urlStr}, &dest} } type UpdateDestinationResponse struct { Location *ServerResponse } func (u *UpdateDestinationCall) Do(ctx context.Context) (*UpdateDestinationResponse, error) { resp, err := u.do(ctx, u.data) if err != nil { return nil, err } dest := &UpdateDestinationResponse{ServerResponse: new(ServerResponse)} if err := decode(resp, dest); err != nil { return nil, err } return dest, nil }
package main import "fmt" import "time" func main() { jst, _ := time.LoadLocation("Asia/Tokyo") fmt.Println(time.Now().In(jst).Format("2006/01/02 15:04:05")) }
package public import ( "context" "time" "tpay_backend/merchantapi/internal/common" "tpay_backend/merchantapi/internal/svc" "tpay_backend/merchantapi/internal/types" "tpay_backend/model" "github.com/tal-tech/go-zero/core/logx" ) type HomeInfoLogic struct { logx.Logger ctx context.Context svcCtx *svc.ServiceContext userId int64 } func NewHomeInfoLogic(ctx context.Context, svcCtx *svc.ServiceContext, userId int64) HomeInfoLogic { return HomeInfoLogic{ Logger: logx.WithContext(ctx), ctx: ctx, svcCtx: svcCtx, userId: userId, } } func (l *HomeInfoLogic) HomeInfo() (*types.HomeInfoResponse, error) { merchant, err := model.NewMerchantModel(l.svcCtx.DbEngine).FindOneById(l.userId) if err != nil { l.Errorf("查询商户id出错, userId[%v], err[%v]", l.userId, err) return nil, common.NewCodeError(common.SysDBGet) } //当天 toDay := time.Now().Format("2006-01-02") toDayCount, err := model.NewPayOrderModel(l.svcCtx.DbEngine).FindMerchantToDayCountByDay(merchant.MerchantNo) if err != nil { l.Errorf("查询当天[%v]统计数据出错, userId[%v], err[%v]", toDay, l.userId, err) return nil, common.NewCodeError(common.SysDBGet) } var receiveData []types.ReceiveData // for i := 7; i > 0; i-- { dayTime := time.Now().Add(time.Hour * -24 * time.Duration(i)) successAmount, err := model.NewPayOrderModel(l.svcCtx.DbEngine).FindMerchantCountByDay(merchant.MerchantNo, dayTime.Format("2006-01-02")) if err != nil { l.Errorf("查询当天[%v]统计数据出错, userId[%v], err[%v]", dayTime.Format("2006-01-02"), l.userId, err) return nil, common.NewCodeError(common.SysDBGet) } receiveData = append(receiveData, types.ReceiveData{ CreateTime: dayTime.Unix(), Amount: successAmount, }) } return &types.HomeInfoResponse{ OrderNumber: toDayCount.OrderNumber, //今日收款总订单数 SuccessOrderNumber: toDayCount.SuccessOrderNumber, //今日收款成功订单数 SuccessAmount: toDayCount.SuccessAmount, //今日成功收款金额 ReceiveList: receiveData, //收款统计数据 }, nil }
package v5 import ( "bytes" "context" "encoding/json" "fmt" "github.com/elastic/go-elasticsearch/v5" "io/ioutil" ) type Elastic struct { client *elasticsearch.Client index string } func New(address string, index string) *Elastic { client, _ := elasticsearch.NewClient(elasticsearch.Config{ Addresses: []string{address}, }) return &Elastic{client: client, index: index} } func (e *Elastic) Search(body []byte) ([]byte, error) { response, err := e.client.Search( e.client.Search.WithContext(context.Background()), e.client.Search.WithIndex(fmt.Sprintf("%s*", e.index)), e.client.Search.WithBody(bytes.NewBuffer(body)), ) if err != nil { return nil, err } defer response.Body.Close() if response.IsError() { var e map[string]interface{} if err := json.NewDecoder(response.Body).Decode(&e); err != nil { return nil, err } else { // Print the response status and error information. e, _ := e["error"].(map[string]interface{}) return nil, fmt.Errorf("[%s] %s: %s", response.Status(), e["type"], e["reason"]) } } return ioutil.ReadAll(response.Body) } func (e *Elastic) GetTotalHitCount(v interface{}) int64 { f, _ := v.(float64) return int64(f) }
package main import ( "testing" ) func TestClean(t *testing.T) { for _, test := range []struct { input string expected string err bool }{ { "", "", false, }, { `*.c `, `*.c `, false, }, { `*.c ` + delimiterStart + `executable ` + delimiterEnd, `*.c `, false, }, { `*.c ` + delimiterStart + `executable ` + delimiterEnd + ` *.o`, `*.c *.o`, false, }, { `*.c ` + delimiterStart + `executable ` + delimiterEnd + ` *.o`, `*.c *.o`, false, }, } { got, err := cleanGitignore(test.input) if (err != nil) != test.err { t.Fatalf("Expected error: %t, got error: %t, with input '%s'", test.err, (err == nil), test.input) } if got != test.expected { t.Fatalf("With input '%s' expected '%s' got '%s'\n", test.input, test.expected, got) } } } func TestInsert(t *testing.T) { for _, test := range []struct { input string addition string expected string err bool }{ { "", "", "", false, }, { `*.c `, "", `*.c `, false, }, { "", "executable", delimiterStart + `executable ` + delimiterEnd, false, }, { `*.c `, `executable `, `*.c ` + delimiterStart + `executable ` + delimiterEnd, false, }, { "*.c", "executable", `*.c ` + delimiterStart + `executable ` + delimiterEnd, false, }, { `*.c ` + delimiterStart + `oldexecutable ` + delimiterEnd, "executable", `*.c ` + delimiterStart + `executable ` + delimiterEnd, false, }, } { got, err := insert(test.input, test.addition) if (err != nil) != test.err { t.Fatalf("Expected error: %t, got error: %t, with input '%s' and addition '%s'", test.err, (err == nil), test.input, test.addition) } if got != test.expected { t.Fatalf("With input '%s' and addition '%s' expected '%s' got '%s'\n", test.input, test.addition, test.expected, got) } } }
package response import ( "KServer/manage" "KServer/proto" "fmt" ) type ClientResponse struct { IManage manage.IManage } func NewClientResponse(m manage.IManage) *ClientResponse { return &ClientResponse{IManage: m} } // 用于接收客户端主题 func (c *ClientResponse) ResponseClient(data proto.IDataPack) { fmt.Println("收到客户端信息", data.GetClientId()) client := c.IManage.WebSocket().Client().GetClient(data.GetClientId()) if client != nil { client.Send(data.GetData().Bytes()) return } fmt.Println("客户端回调") } // 用于接收客户端主题 func (c *ClientResponse) ResponseRemoveClient(data proto.IDataPack) { client := c.IManage.WebSocket().Client().GetClient(data.GetClientId()) if client != nil { client.Send(data.GetData().Bytes()) client.Stop() return } fmt.Println("客户端回调") }
package requests type WalletContainsRequest struct { BaseRequest `mapstructure:",squash"` Account string `json:"account" mapstructure:"account"` }
package operations import ( "strings" "sync" "time" ) type order struct { Timestamp int64 `json:"timestamp"` Operation string `json:"operation"` IssuerName string `json:"IssuerName"` TotalShares int `json:"TotalShares"` SharePrice int `json:"SharePrice"` } type issuer struct { IssuerName string `json:"issuerName"` TotalShares int `json:"totalShares"` SharePrice int `json:"sharePrice"` } type balance struct { Cash int `json:"cash"` Issuers []issuer `json:"issuers"` } // Operation - holds the orders from a json file type Operation struct { InitialBalance balance `json:"initialBalances"` Orders []order `json:"orders"` } type businessError struct { ErrorType string OrderFailed order } // Output - Holds the result from running json file operations type Output struct { CurrentBalance balance `json:"currentBalance"` BusinessErrors []businessError `json:"businessErrors"` } // isOrderInvalid - verify if the structure of the order is valid, type and not null values func isOrderInvalid(order order) bool { return order.Timestamp < 0 || order.TotalShares < 0 || order.SharePrice < 0 || len(order.IssuerName) <= 0 || (order.Operation != "BUY" && order.Operation != "SELL") } // validMarketHoursOperation - check if the order is between 06:00 and 15:00 hours func validMarketHoursOperation(timestamp int64) bool { date := time.Unix(timestamp, 0) totalSeconds := date.Second() + date.Minute()*60 + date.Hour()*3600 return totalSeconds > 21600 && totalSeconds < 54000 } /* duplicatedOrder - validates if an orders is duplicated. the criteria is: - same issuer, shares and operation - the operation is in 5 minutes difference between other operations */ func duplicatedOrder(currentOrder order, ordersPerIssuer **map[string][]order) bool { orders, exists := (**ordersPerIssuer)[currentOrder.IssuerName] if !exists { (**ordersPerIssuer)[currentOrder.IssuerName] = []order{currentOrder} return false } for _, order := range orders { if currentOrder.TotalShares == order.TotalShares && currentOrder.SharePrice == order.SharePrice && currentOrder.Operation == order.Operation { if currentOrder.Timestamp == order.Timestamp { return true } if order.Timestamp > currentOrder.Timestamp { return order.Timestamp-currentOrder.Timestamp <= 300 } if currentOrder.Timestamp > order.Timestamp { return currentOrder.Timestamp-order.Timestamp <= 300 } } } (**ordersPerIssuer)[currentOrder.IssuerName] = append((**ordersPerIssuer)[currentOrder.IssuerName], currentOrder) return false } // canSell - validates the shares of the issuer to check amount func canSell(order order, balance balance) (can bool, cost int, shares int) { for _, issuer := range balance.Issuers { if issuer.IssuerName == order.IssuerName { operationCost := order.SharePrice * order.TotalShares return issuer.TotalShares >= order.TotalShares, operationCost, -order.TotalShares } } return false, 0, 0 } // canBuy - validates the cash of the issuer to check amount func canBuy(order order, balance balance) (can bool, cost int, shares int) { for _, issuer := range balance.Issuers { if issuer.IssuerName == order.IssuerName { operationCost := order.SharePrice * order.TotalShares return balance.Cash >= operationCost, -operationCost, order.TotalShares } } return false, 0, 0 } // updateBalance - depending if its buy/sell update share and cash accordingly func updateBalance(operation *Operation, operationIssuer string, cost int, shares int) { operation.InitialBalance.Cash += cost for i, issuer := range operation.InitialBalance.Issuers { if issuer.IssuerName == operationIssuer { operation.InitialBalance.Issuers[i].TotalShares += shares break } } } // runOrder - store the order in a map of issuers, for duplicated validations, update balance according of the order type func runOrder(operation *Operation, order order, ordersPerIssuer *map[string][]order, output *Output) { if isOrderInvalid(order) { bError := businessError{} bError.ErrorType = "INVALID OPERATION" bError.OrderFailed = order output.BusinessErrors = append(output.BusinessErrors, bError) return } if !validMarketHoursOperation(order.Timestamp) { bError := businessError{} bError.ErrorType = "CLOSED MARKET" bError.OrderFailed = order output.BusinessErrors = append(output.BusinessErrors, bError) return } if duplicatedOrder(order, &ordersPerIssuer) { bError := businessError{} bError.ErrorType = "DUPLICATED OPERATION" bError.OrderFailed = order output.BusinessErrors = append(output.BusinessErrors, bError) return } switch strings.ToUpper(order.Operation) { case "BUY": can, cost, shares := canBuy(order, operation.InitialBalance) if can { updateBalance(operation, order.IssuerName, cost, shares) } else { bError := businessError{} bError.ErrorType = "INSUFFICIENT BALANCE" bError.OrderFailed = order output.BusinessErrors = append(output.BusinessErrors, bError) } break case "SELL": can, cost, shares := canSell(order, operation.InitialBalance) if can { updateBalance(operation, order.IssuerName, cost, shares) } else { bError := businessError{} bError.ErrorType = "INSUFFICIENT STOCKS" bError.OrderFailed = order output.BusinessErrors = append(output.BusinessErrors, bError) } break } } // PerformOperation - run all orders in a json file. Uses go routines per file for better performance func PerformOperation(operation *Operation, wg *sync.WaitGroup) Output { defer wg.Done() output := Output{} ordersPerIssuer := make(map[string][]order) for _, order := range operation.Orders { runOrder(operation, order, &ordersPerIssuer, &output) } output.CurrentBalance.Cash = operation.InitialBalance.Cash output.CurrentBalance.Issuers = operation.InitialBalance.Issuers return output }
/* 2019-4-24: 程序主入口 花花CMS是一个内容管理系统,代码尽可能地补充必要注释,方便后人协作 **/ package main import ( "flag" "github.com/hunterhug/fafacms/core/config" "github.com/hunterhug/fafacms/core/controllers" "github.com/hunterhug/fafacms/core/flog" "github.com/hunterhug/fafacms/core/model" "github.com/hunterhug/fafacms/core/router" "github.com/hunterhug/fafacms/core/server" "github.com/hunterhug/fafacms/core/util/mail" ) var ( // 全局配置文件路径 configFile string // 是否创建数据库表 createTable bool // 开发时每次都发邮件的形式不好,可以先调试模式 mailDebug bool // 跳过授权,某些超级管理接口需要绑定组和路由,可以先开调试模式 canSkipAuth bool // 分布式Session开关,可以先开调试模式,存于内存中 sessionUseRedis bool ) // 初始化时解析命令行,辅助程序 // 这些调试参数不置于文件配置中 func init() { // 默认读取本路径下 ./config.json 配置 flag.StringVar(&configFile, "config", "./config.json", "config file") // 正式部署时,请全部设置为 false flag.BoolVar(&createTable, "init_db", true, "create db table") flag.BoolVar(&mailDebug, "email_debug", false, "Email debug") flag.BoolVar(&canSkipAuth, "auth_skip_debug", false, "Auth skip debug") // Session可以放在内存中 flag.BoolVar(&sessionUseRedis, "use_session_redis", false, "Use Redis Session") flag.Parse() } // 入口 // 欢迎查看优美代码,我是花花 func main() { // 将调试参数跨包注入 mail.Debug = mailDebug controllers.AuthDebug = canSkipAuth var err error // 初始化全局配置 err = server.InitConfig(configFile) if err != nil { panic(err) } // 初始化日志 flog.InitLog(config.FafaConfig.DefaultConfig.LogPath) // 如果全局调试,那么所有DEBUG以上级别日志将会打印 // 实际情况下,最好设置为 true, if config.FafaConfig.DefaultConfig.LogDebug { flog.SetLogLevel("DEBUG") } flog.Log.Notice("Hi! FaFa CMS!") flog.Log.Debugf("Hi! Config is %#v", config.FafaConfig) // 初始化数据库连接 err = server.InitRdb(config.FafaConfig.DbConfig) if err != nil { panic(err) } // 初始化网站Session存储 if sessionUseRedis { err = server.InitSession(config.FafaConfig.SessionConfig) if err != nil { panic(err) } } else { server.InitMemorySession() } // 创建数据库表,需要先手动创建DB if createTable { server.CreateTable([]interface{}{ model.User{}, // 用户表 model.Group{}, // 用户组表,用户可以拥有一个组 model.Resource{}, // 资源表,主要为需要管理员权限的路由服务 model.GroupResource{}, // 组可以被分配资源 model.Content{}, // 内容表 model.ContentHistory{}, // 内容历史表 model.ContentNode{}, // 内容节点表,内容必须拥有一个节点 model.File{}, // 文件表 //model.Comment{}, // 评论表 //model.Log{}, // 日志表 }) } // Server Run engine := server.Server() // Storage static API engine.Static("/storage", config.FafaConfig.DefaultConfig.StoragePath) engine.Static("/storage_x", config.FafaConfig.DefaultConfig.StoragePath+"_x") // Web welcome home! router.SetRouter(engine) // V1 API, will may be change to V2... v1 := engine.Group("/v1") v1.Use(controllers.AuthFilter) // Router Set router.SetAPIRouter(v1, router.V1Router) flog.Log.Noticef("Server run in %s", config.FafaConfig.DefaultConfig.WebPort) err = engine.Run(config.FafaConfig.DefaultConfig.WebPort) if err != nil { panic(err) } }
package service import ( "errors" "fmt" "io/ioutil" "log" "net/http" "github.com/binjamil/keyd/core" "github.com/binjamil/keyd/transact" "github.com/gorilla/mux" ) var TransactionLogger transact.TransactionLogger func GetHandler(rw http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) key := vars["key"] value, err := core.Get(key) if errors.Is(err, core.ErrorNoSuchKey) { http.Error(rw, err.Error(), http.StatusNotFound) return } if err != nil { http.Error(rw, err.Error(), http.StatusInternalServerError) return } rw.Write([]byte(value)) log.Printf("GET key=%s\n", key) } func PutHandler(rw http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) key := vars["key"] value, err := ioutil.ReadAll(r.Body) defer r.Body.Close() if err != nil { http.Error(rw, err.Error(), http.StatusInternalServerError) return } err = core.Put(key, string(value)) if err != nil { http.Error(rw, err.Error(), http.StatusInternalServerError) return } rw.WriteHeader(http.StatusCreated) TransactionLogger.WritePut(key, string(value)) log.Printf("PUT key=%s value=%s\n", key, string(value)) } func DeleteHandler(rw http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) key := vars["key"] err := core.Delete(key) if err != nil { http.Error(rw, err.Error(), http.StatusInternalServerError) return } TransactionLogger.WriteDelete(key) log.Printf("DELETE key=%s\n", key) } func InitializeTransactionLog() error { var err error TransactionLogger, err = transact.NewFileTransactionLogger("transaction.log") if err != nil { return fmt.Errorf("failed to create event logger: %w", err) } events, errors := TransactionLogger.ReadEvents() e, ok, count := transact.Event{}, true, 0 for ok && err == nil { select { case err, ok = <-errors: // Retrieve any errors case e, ok = <-events: switch e.EventType { case transact.EventDelete: // Got a DELETE event! err = core.Delete(e.Key) count++ case transact.EventPut: // Got a PUT event! err = core.Put(e.Key, e.Value) count++ } } } log.Printf("%d events replayed\n", count) TransactionLogger.Run() return err }
// +build !qml package view import ( "github.com/therecipe/qt/widgets" "github.com/therecipe/qt/internal/examples/sql/masterdetail_qml/controller" "github.com/therecipe/qt/internal/examples/sql/masterdetail_qml/view/album" "github.com/therecipe/qt/internal/examples/sql/masterdetail_qml/view/artist" "github.com/therecipe/qt/internal/examples/sql/masterdetail_qml/view/detail" "github.com/therecipe/qt/internal/examples/sql/masterdetail_qml/view/dialog" ) var ViewControllerInstance *viewController type viewController struct { widgets.QMainWindow _ func() `constructor:"init"` //->controller _ func() `signal:"aboutQt"` _ func() `signal:"addAlbumShowRequest"` _ func() `signal:"deleteAlbumRequest"` } func (v *viewController) init() { ViewControllerInstance = v layout := widgets.NewQGridLayout2() layout.AddWidget2(artist.NewArtistController2("Artist", nil), 0, 0, 0) layout.AddWidget2(album.NewAlbumController2("Album", nil), 1, 0, 0) layout.AddWidget3(detail.NewDetailController2("Detail", nil), 0, 1, 2, 1, 0) layout.SetColumnStretch(1, 1) layout.SetColumnMinimumWidth(0, 500) widget := widgets.NewQWidget(nil, 0) widget.SetLayout(layout) v.SetCentralWidget(widget) v.Resize2(850, 400) v.SetWindowTitle("Music Archive") dialog.NewAddDialogController(nil, 0) dialog.NewDeleteDialogController(nil) NewMenuBarController(nil) //->controller v.ConnectAboutQt(controller.Instance.AboutQt) v.ConnectAddAlbumShowRequest(controller.Instance.AddAlbumShowRequest) v.ConnectDeleteAlbumRequest(controller.Instance.DeleteAlbumRequest) }
package LICY_BLC import "fmt" func (cli *Licy_CLI) licy_createWallet(){ wallets ,_:=Licy_ReadWallets() wallets.Licy_CreateNewWallet() fmt.Println(len(wallets.Licy_WalletsMap)) }
package iptool import ( "fmt" "regexp" "testing" ) func TestSearchIPFail(t *testing.T) { err := SearchIP("192.168.2.2") if err == nil { t.Log(err) t.Fail() } } func TestSearchIPSucess(t *testing.T) { err := SearchIP("www.suncco.com") if err != nil { t.Log(err) t.Fail() } } func TestParseIpsOne(t *testing.T) { ips, err := ParseIps("192.1.1.1") fmt.Println(len(ips)) if err != nil { t.Log(err) t.Fail() } } func TestParseIpsTwo(t *testing.T) { ips, err := ParseIps("192.1.1.a") if err == nil { t.Log(ips) t.Fail() } fmt.Println(len(ips)) } func TestParseIpsThree(t *testing.T) { ips, err := ParseIps("192.1.1.266") fmt.Println(len(ips)) if err == nil { t.Log(ips) t.Fail() } } func TestParseIpsFour(t *testing.T) { ips, err := ParseIps("192.1.1.111~192.1.1.111") fmt.Println(len(ips)) if err != nil || ips[0] != "192.1.1.111" { // t.Log(ips) t.Fail() } // fmt.Println(ips) } func TestParseIps5(t *testing.T) { ips, err := ParseIps("192.1.1.111~192.1.1.211") fmt.Println(len(ips)) if err != nil { // t.Log(ips) t.Fail() } } func TestParseIps6(t *testing.T) { ips, err := ParseIps("192.1.1.111~192.1.2.211") fmt.Println(len(ips)) if err != nil { // t.Log(ips) t.Fail() } } func TestParseIps7(t *testing.T) { ips, err := ParseIps("192.1.1.111~192.2.2.211") fmt.Println(len(ips)) if err != nil { // t.Log(ips) t.Fail() } } func TestParseIps8(t *testing.T) { ips, err := ParseIps("192.1.1.111~193.2.2.211") fmt.Println(len(ips)) if err != nil { // t.Log(ips) t.Fail() } } func TestConnectPort(t *testing.T) { err := ConnectIPPort("172.16.10.20", 21) if err != nil { reg,_ := regexp.Compile(`refused`) if err != nil && reg.MatchString(err.Error()) { fmt.Println("没打开21端口", err) return } else { t.Log(err) t.Fail() return } } fmt.Println("打开了21端口") } func TestConnectPorts(t *testing.T) { result:= ConnectIPPosts("172.16.10.20", []int{21,23,80}) if len(result) == 0 { t.Fail() } fmt.Println(result) } func TestPort(t *testing.T) { result,err := Ports("20-20") if err != nil { t.Log(err) t.Fail() return } fmt.Println(result) } func TestPort1(t *testing.T) { result,err := Ports("20-50") if err != nil { t.Log(err) t.Fail() return } fmt.Println(result) }
// Copyright (C) 2018 Storj Labs, Inc. // See LICENSE for copying information. package boltdb import ( "time" "github.com/boltdb/bolt" "go.uber.org/zap" ) var ( defaultTimeout = 1 * time.Second ) const ( // fileMode sets permissions so owner can read and write fileMode = 0600 ) // Client is the storage interface for the Bolt database type Client struct { logger *zap.Logger db *bolt.DB Path string } // New instantiates a new BoltDB client func New(logger *zap.Logger, path string) (*Client, error) { db, err := bolt.Open(path, fileMode, &bolt.Options{Timeout: defaultTimeout}) if err != nil { return nil, err } return &Client{ logger: logger, db: db, Path: path, }, nil } // Close closes a BoltDB client func (c *Client) Close() error { return c.db.Close() }
package leetcode /*Given a Binary Search Tree and a target number, return true if there exist two elements in the BST such that their sum is equal to the given target. 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/two-sum-iv-input-is-a-bst 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。*/ /** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */ var arr []int func findTarget(root *TreeNode, k int) bool { arr = []int{} inOrder(root) for i := 0; i < len(arr)-1; i++ { target := k - arr[i] if binarySearch(i+1, target) { return true } } return false } func inOrder(root *TreeNode) { if root == nil { return } inOrder(root.Left) arr = append(arr, root.Val) inOrder(root.Right) } func binarySearch(begin int, target int) bool { end := len(arr) - 1 for begin <= end { mid := begin + (end-begin)/2 if arr[mid] == target { return true } else if arr[mid] > target { end = mid - 1 } else { begin = mid + 1 } } return false } /* var isFind bool var treeRoot *TreeNode func findTarget(root *TreeNode, k int) bool { isFind = false treeRoot = root inOrder(root, k) return isFind } func find(root *TreeNode, target int) bool { if root == nil { return false } res := false if target > root.Val { res = find(root.Right, target) } else if target == root.Val { res = true } else { res = find(root.Left, target) } return res } func inOrder(root *TreeNode, target int) { if root == nil || isFind { return } inOrder(root.Left, target) if target - root.Val != root.Val { if find(treeRoot,target - root.Val) { isFind = true } } inOrder(root.Right, target) }*/
package main import ( "fmt" ) func main() { a := make([]int, 6) for i := 0; i < 6; i++ { a[i] = i } b := append(a[:2], a[3:]...) fmt.Print(b) }
/* You are given an array of integers nums. You are also given an integer original which is the first number that needs to be searched for in nums. You then do the following steps: If original is found in nums, multiply it by two (i.e., set original = 2 * original). Otherwise, stop the process. Repeat this process with the new number as long as you keep finding the number. Return the final value of original. Example 1: Input: nums = [5,3,6,1,12], original = 3 Output: 24 Explanation: - 3 is found in nums. 3 is multiplied by 2 to obtain 6. - 6 is found in nums. 6 is multiplied by 2 to obtain 12. - 12 is found in nums. 12 is multiplied by 2 to obtain 24. - 24 is not found in nums. Thus, 24 is returned. Example 2: Input: nums = [2,7,9], original = 4 Output: 4 Explanation: - 4 is not found in nums. Thus, 4 is returned. Constraints: 1 <= nums.length <= 1000 1 <= nums[i], original <= 1000 */ package main func main() { assert(final([]int{5, 3, 6, 1, 12}, 3) == 24) assert(final([]int{2, 7, 9}, 4) == 4) } func assert(x bool) { if !x { panic("assertion failed") } } func final(a []int, x int) int { m := make(map[int]bool) for _, v := range a { m[v] = true } for i := 0; i < len(m) && m[x]; i++ { x *= 2 } return x }
package request import "github.com/agusbasari29/Skilltest-RSP-Akselerasi-2-Backend-Agus-Basari/entity" type RequestUser struct { ID uint `json:"id"` Username string `json:"username" validate:"required,alphanum"` Fullname string `json:"fullname" validate:"required"` Email string `json:"email" validate:"required,email"` Password string `json:"password" validate:"required"` Role entity.UserRole `json:"role"` } type RequestUserUpdate struct { ID uint `json:"id"` Username string `json:"username" validate:"required,alphanum"` Fullname string `json:"fullname" validate:"required"` Email string `json:"email" validate:"required,email"` } type RequestUserProfile struct { ID uint `json:"id"` }
package gen import ( "bytes" "errors" "fmt" "io" "io/ioutil" "os" "os/exec" "path/filepath" "sort" "strings" "unicode" // "github.com/vugu/vugu/internal/htmlx" // "github.com/vugu/vugu/internal/htmlx/atom" // "golang.org/x/net/html" // "golang.org/x/net/html/atom" "github.com/vugu/html" "github.com/vugu/html/atom" "github.com/vugu/vugu" ) // ParserGo is a template parser that emits Go source code that will construct the appropriately wired VGNodes. type ParserGo struct { PackageName string // name of package to use at top of files StructType string // just the struct name, no "*" (replaces ComponentType and DataType) // ComponentType string // just the struct name, no "*" // DataType string // just the struct name, no "*" OutDir string // output dir OutFile string // output file name with ".go" suffix NoOptimizeStatic bool // set to true to disable optimization of static blocks of HTML into vg-html expressions TinyGo bool // set to true to enable TinyGo compatability changes to the generated code } func gofmt(pgm string) (string, error) { // build up command to run cmd := exec.Command("gofmt") // I need to capture output var fmtOutput bytes.Buffer cmd.Stderr = &fmtOutput cmd.Stdout = &fmtOutput // also set up input pipe read, write := io.Pipe() defer write.Close() // make sure this always gets closed, it is safe to call more than once cmd.Stdin = read // copy down environment variables cmd.Env = os.Environ() // force wasm,js target cmd.Env = append(cmd.Env, "GOOS=js") cmd.Env = append(cmd.Env, "GOARCH=wasm") // start gofmt if err := cmd.Start(); err != nil { return pgm, fmt.Errorf("can't run gofmt: %v", err) } // stream in the raw source if _, err := write.Write([]byte(pgm)); err != nil && err != io.ErrClosedPipe { return pgm, fmt.Errorf("gofmt failed: %v", err) } write.Close() // wait until gofmt is done if err := cmd.Wait(); err != nil { return pgm, fmt.Errorf("go fmt error %v; full output: %s", err, fmtOutput.String()) } return fmtOutput.String(), nil } // Parse is an experiment... // r is the actual input, fname is only used to emit line directives func (p *ParserGo) Parse(r io.Reader, fname string) error { state := &parseGoState{} inRaw, err := ioutil.ReadAll(r) if err != nil { return err } // use a tokenizer to peek at the first element and see if it's an HTML tag state.isFullHTML = false tmpZ := html.NewTokenizer(bytes.NewReader(inRaw)) for { tt := tmpZ.Next() if tt == html.ErrorToken { return tmpZ.Err() } if tt != html.StartTagToken { // skip over non-tags continue } t := tmpZ.Token() if t.Data == "html" { state.isFullHTML = true break } break } // log.Printf("isFullHTML: %v", state.isFullHTML) if state.isFullHTML { n, err := html.Parse(bytes.NewReader(inRaw)) if err != nil { return err } state.docNodeList = append(state.docNodeList, n) // docNodeList is just this one item } else { nlist, err := html.ParseFragment(bytes.NewReader(inRaw), &html.Node{ Type: html.ElementNode, DataAtom: atom.Div, Data: "div", }) if err != nil { return err } // only add elements for _, n := range nlist { if n.Type != html.ElementNode { continue } // log.Printf("FRAGMENT: %#v", n) state.docNodeList = append(state.docNodeList, n) } } // run n through the optimizer and convert large chunks of static elements into // vg-html attributes, this should provide a significiant performance boost for static HTML if !p.NoOptimizeStatic { for _, n := range state.docNodeList { err = compactNodeTree(n) if err != nil { return err } } } // log.Printf("parsed document looks like so upon start of parsing:") // for i, n := range state.docNodeList { // var buf bytes.Buffer // err := html.Render(&buf, n) // if err != nil { // return fmt.Errorf("error during debug render: %v", err) // } // log.Printf("state.docNodeList[%d]:\n%s", i, buf.Bytes()) // } err = p.visitOverall(state) if err != nil { return err } var buf bytes.Buffer // log.Printf("goBuf.Len == %v", goBuf.Len()) buf.Write(state.goBuf.Bytes()) buf.Write(state.buildBuf.Bytes()) buf.Write(state.goBufBottom.Bytes()) outPath := filepath.Join(p.OutDir, p.OutFile) fo, err := gofmt(buf.String()) if err != nil { // if the gofmt errors, we still attempt to write out the non-fmt'ed output to the file, to assist in debugging ioutil.WriteFile(outPath, buf.Bytes(), 0644) return err } // run the import deduplicator var dedupedBuf bytes.Buffer err = dedupImports(bytes.NewReader([]byte(fo)), &dedupedBuf, p.OutFile) if err != nil { return err } // write to final output file err = ioutil.WriteFile(outPath, dedupedBuf.Bytes(), 0644) if err != nil { return err } return nil } type codeChunk struct { Line int Column int Code string } type parseGoState struct { isFullHTML bool // is the first node an <html> tag docNodeList []*html.Node // top level nodes parsed out of source file goBuf bytes.Buffer // additional Go code (at top) buildBuf bytes.Buffer // Build() method Go code (below) goBufBottom bytes.Buffer // additional Go code that is put as the very last thing // cssChunkList []codeChunk // jsChunkList []codeChunk outIsSet bool // set to true when vgout.Out has been set for to the level node } func (p *ParserGo) visitOverall(state *parseGoState) error { fmt.Fprintf(&state.goBuf, "package %s\n\n", p.PackageName) fmt.Fprintf(&state.goBuf, "// Code generated by vugu via vugugen. Please regenerate instead of editing or add additional code in a separate file. DO NOT EDIT.\n\n") fmt.Fprintf(&state.goBuf, "import %q\n", "fmt") fmt.Fprintf(&state.goBuf, "import %q\n", "reflect") fmt.Fprintf(&state.goBuf, "import %q\n", "github.com/vugu/vjson") fmt.Fprintf(&state.goBuf, "import %q\n", "github.com/vugu/vugu") fmt.Fprintf(&state.goBuf, "import js %q\n", "github.com/vugu/vugu/js") fmt.Fprintf(&state.goBuf, "\n") // TODO: we use a prefix like "vg" as our namespace; should document that user code should not use that prefix to avoid conflicts fmt.Fprintf(&state.buildBuf, "func (c *%s) Build(vgin *vugu.BuildIn) (vgout *vugu.BuildOut) {\n", p.StructType) fmt.Fprintf(&state.buildBuf, " \n") fmt.Fprintf(&state.buildBuf, " vgout = &vugu.BuildOut{}\n") fmt.Fprintf(&state.buildBuf, " \n") fmt.Fprintf(&state.buildBuf, " var vgiterkey interface{}\n") fmt.Fprintf(&state.buildBuf, " _ = vgiterkey\n") fmt.Fprintf(&state.buildBuf, " var vgn *vugu.VGNode\n") // fmt.Fprintf(&buildBuf, " var vgparent *vugu.VGNode\n") // NOTE: Use things that are lightweight here - e.g. don't do var _ = fmt.Sprintf because that brings in all of the // (possibly quite large) formatting code, which might otherwise be avoided. fmt.Fprintf(&state.goBufBottom, "// 'fix' unused imports\n") fmt.Fprintf(&state.goBufBottom, "var _ fmt.Stringer\n") fmt.Fprintf(&state.goBufBottom, "var _ reflect.Type\n") fmt.Fprintf(&state.goBufBottom, "var _ vjson.RawMessage\n") fmt.Fprintf(&state.goBufBottom, "var _ js.Value\n") fmt.Fprintf(&state.goBufBottom, "\n") // remove document node if present if len(state.docNodeList) == 1 && state.docNodeList[0].Type == html.DocumentNode { state.docNodeList = []*html.Node{state.docNodeList[0].FirstChild} } if state.isFullHTML { if len(state.docNodeList) != 1 { return fmt.Errorf("full HTML mode but not exactly 1 node found (found %d)", len(state.docNodeList)) } err := p.visitHTML(state, state.docNodeList[0]) if err != nil { return err } } else { gotTopNode := false for _, n := range state.docNodeList { // ignore comments if n.Type == html.CommentNode { continue } if n.Type == html.TextNode { // ignore whitespace text if strings.TrimSpace(n.Data) == "" { continue } // error on non-whitespace text return fmt.Errorf("unexpected text outside any element: %q", n.Data) } // must be an element at this point if n.Type != html.ElementNode { return fmt.Errorf("unexpected node type %v; node=%#v", n.Type, n) } if isScriptOrStyle(n) { err := p.visitScriptOrStyle(state, n) if err != nil { return err } continue } if gotTopNode { return fmt.Errorf("Found more than one top level element: %s", n.Data) } gotTopNode = true // handle top node // check for forbidden top level tags nodeName := strings.ToLower(n.Data) if nodeName == "head" || nodeName == "body" { return fmt.Errorf("component cannot use %q as top level tag", nodeName) } err := p.visitTopNode(state, n) if err != nil { return err } continue } } // for _, chunk := range state.cssChunkList { // // fmt.Fprintf(&buildBuf, " out.AppendCSS(/*line %s:%d*/%q)\n\n", fname, chunk.Line, chunk.Code) // // fmt.Fprintf(&state.buildBuf, " out.AppendCSS(%q)\n\n", chunk.Code) // _ = chunk // panic("need to append whole node, not AppendCSS") // } // for _, chunk := range state.jsChunkList { // // fmt.Fprintf(&buildBuf, " out.AppendJS(/*line %s:%d*/%q)\n\n", fname, chunk.Line, chunk.Code) // // fmt.Fprintf(&state.buildBuf, " out.AppendJS(%q)\n\n", chunk.Code) // _ = chunk // panic("need to append whole node, not AppendJS") // } fmt.Fprintf(&state.buildBuf, " return vgout\n") fmt.Fprintf(&state.buildBuf, "}\n\n") return nil } func (p *ParserGo) visitHTML(state *parseGoState, n *html.Node) error { pOutputTag(state, n) // fmt.Fprintf(&state.buildBuf, "vgn = &vugu.VGNode{Type:vugu.VGNodeType(%d),Data:%q,Attr:%#v}\n", n.Type, n.Data, staticVGAttr(n.Attr)) // fmt.Fprintf(&state.buildBuf, "vgout.Out = append(vgout.Out, vgn) // root for output\n") // for first element we need to assign as Doc on BuildOut // state.outIsSet = true // dynamic attrs writeDynamicAttributes(state, n) fmt.Fprintf(&state.buildBuf, "{\n") fmt.Fprintf(&state.buildBuf, "vgparent := vgn; _ = vgparent\n") // vgparent set for this block to vgn for childN := n.FirstChild; childN != nil; childN = childN.NextSibling { if childN.Type != html.ElementNode { continue } var err error if strings.ToLower(childN.Data) == "head" { err = p.visitHead(state, childN) } else if strings.ToLower(childN.Data) == "body" { err = p.visitBody(state, childN) } else { return fmt.Errorf("unknown tag inside html %q", childN.Data) } if err != nil { return err } } fmt.Fprintf(&state.buildBuf, "}\n") return nil } func (p *ParserGo) visitHead(state *parseGoState, n *html.Node) error { pOutputTag(state, n) // fmt.Fprintf(&state.buildBuf, "vgn = &vugu.VGNode{Type:vugu.VGNodeType(%d),Data:%q,Attr:%#v}\n", n.Type, n.Data, staticVGAttr(n.Attr)) // fmt.Fprintf(&state.buildBuf, "vgout.Out = append(vgout.Out, vgn) // root for output\n") // for first element we need to assign as Doc on BuildOut // state.outIsSet = true // dynamic attrs writeDynamicAttributes(state, n) fmt.Fprintf(&state.buildBuf, "{\n") fmt.Fprintf(&state.buildBuf, "vgparent := vgn; _ = vgparent\n") // vgparent set for this block to vgn for childN := n.FirstChild; childN != nil; childN = childN.NextSibling { if isScriptOrStyle(childN) { err := p.visitScriptOrStyle(state, childN) if err != nil { return err } continue } err := p.visitDefaultByType(state, childN) if err != nil { return err } } fmt.Fprintf(&state.buildBuf, "}\n") return nil } func (p *ParserGo) visitBody(state *parseGoState, n *html.Node) error { pOutputTag(state, n) // fmt.Fprintf(&state.buildBuf, "vgn = &vugu.VGNode{Type:vugu.VGNodeType(%d),Data:%q,Attr:%#v}\n", n.Type, n.Data, staticVGAttr(n.Attr)) // fmt.Fprintf(&state.buildBuf, "vgout.Out = append(vgout.Out, vgn) // root for output\n") // for first element we need to assign as Doc on BuildOut // state.outIsSet = true // dynamic attrs writeDynamicAttributes(state, n) fmt.Fprintf(&state.buildBuf, "{\n") fmt.Fprintf(&state.buildBuf, "vgparent := vgn; _ = vgparent\n") // vgparent set for this block to vgn foundMountEl := false for childN := n.FirstChild; childN != nil; childN = childN.NextSibling { // ignore whitespace and comments directly in body if childN.Type != html.ElementNode { continue } if isScriptOrStyle(childN) { err := p.visitScriptOrStyle(state, childN) if err != nil { return err } continue } if foundMountEl { return fmt.Errorf("element %q found after we already have a mount element", childN.Data) } foundMountEl = true err := p.visitDefaultByType(state, childN) if err != nil { return err } } fmt.Fprintf(&state.buildBuf, "}\n") return nil } // visitScriptOrStyle calls visitJS, visitCSS or visitGo accordingly, // will error if the node does not correspond to one of those func (p *ParserGo) visitScriptOrStyle(state *parseGoState, n *html.Node) error { nodeName := strings.ToLower(n.Data) // script tag if nodeName == "script" { var mt string // mime type ty := attrWithKey(n, "type") if ty == nil { // return fmt.Errorf("script tag without type attribute is not valid") mt = "" } else { // tinygo support: just split on semi, don't need to import mime package // mt, _, _ = mime.ParseMediaType(ty.Val) mt = strings.Split(strings.TrimSpace(ty.Val), ";")[0] } // go code if mt == "application/x-go" { err := p.visitGo(state, n) if err != nil { return err } return nil } // component js (type attr omitted okay - means it is JS) if mt == "text/javascript" || mt == "application/javascript" || mt == "" { err := p.visitJS(state, n) if err != nil { return err } return nil } return fmt.Errorf("found script tag with invalid mime type %q", mt) } // component css if nodeName == "style" || nodeName == "link" { err := p.visitCSS(state, n) if err != nil { return err } return nil } return fmt.Errorf("element %q is not a valid script or style - %#v", n.Data, n) } func (p *ParserGo) visitJS(state *parseGoState, n *html.Node) error { if n.Type != html.ElementNode { return fmt.Errorf("visitJS, not an element node %#v", n) } nodeName := strings.ToLower(n.Data) if nodeName != "script" { return fmt.Errorf("visitJS, tag %q not a script", nodeName) } // see if there's a script inside, or if this is a script include if n.FirstChild == nil { // script include - we pretty much just let this through, don't care what the attrs are } else { // if there is a script inside, we do not allow attributes other than "type", to avoid // people using features that might not be compatible with the funky stuff we have to do // in vugu to make all this work for _, a := range n.Attr { if a.Key != "type" { return fmt.Errorf("attribute %q not allowed on script tag that contains JS code", a.Key) } if a.Val != "text/javascript" && a.Val != "application/javascript" { return fmt.Errorf("script type %q invalid (must be text/javascript)", a.Val) } } // verify that all children are text nodes for childN := n.FirstChild; childN != nil; childN = childN.NextSibling { if childN.Type != html.TextNode { return fmt.Errorf("script tag contains non-text child: %#v", childN) } } } // allow control stuff, why not // vg-for if v, _ := vgForExpr(n); v.expr != "" { if err := p.emitForExpr(state, n); err != nil { return err } defer fmt.Fprintf(&state.buildBuf, "}\n") } // vg-if ife := vgIfExpr(n) if ife != "" { fmt.Fprintf(&state.buildBuf, "if %s {\n", ife) defer fmt.Fprintf(&state.buildBuf, "}\n") } // but then for the actual output, we append to vgout.JS, instead of parentNode fmt.Fprintf(&state.buildBuf, "vgn = &vugu.VGNode{Type:vugu.VGNodeType(%d),Data:%q,Attr:%#v}\n", n.Type, n.Data, staticVGAttr(n.Attr)) // output any text children if n.FirstChild != nil { fmt.Fprintf(&state.buildBuf, "{\n") for childN := n.FirstChild; childN != nil; childN = childN.NextSibling { // NOTE: we already verified above that these are just text nodes fmt.Fprintf(&state.buildBuf, "vgn.AppendChild(&vugu.VGNode{Type:vugu.VGNodeType(%d),Data:%q,Attr:%#v})\n", childN.Type, childN.Data, staticVGAttr(childN.Attr)) } fmt.Fprintf(&state.buildBuf, "}\n") } fmt.Fprintf(&state.buildBuf, "vgout.AppendJS(vgn)\n") // dynamic attrs writeDynamicAttributes(state, n) return nil } func (p *ParserGo) visitCSS(state *parseGoState, n *html.Node) error { if n.Type != html.ElementNode { return fmt.Errorf("visitCSS, not an element node %#v", n) } nodeName := strings.ToLower(n.Data) switch nodeName { case "link": // okay as long as nothing is inside this node if n.FirstChild != nil { return fmt.Errorf("link tag should not have children") } // and it needs to have an href (url) hrefAttr := attrWithKey(n, "href") if hrefAttr == nil { return fmt.Errorf("link tag must have href attribute but does not: %#v", n) } case "style": // style must have child (will verify it is text below) if n.FirstChild == nil { return fmt.Errorf("style must have contents but does not: %#v", n) } // okay as long as only text nodes inside for childN := n.FirstChild; childN != nil; childN = childN.NextSibling { if childN.Type != html.TextNode { return fmt.Errorf("style tag contains non-text child: %#v", childN) } } default: return fmt.Errorf("visitCSS, unexpected tag name %q", nodeName) } // allow control stuff, why not // vg-for if v, _ := vgForExpr(n); v.expr != "" { if err := p.emitForExpr(state, n); err != nil { return err } defer fmt.Fprintf(&state.buildBuf, "}\n") } // vg-if ife := vgIfExpr(n) if ife != "" { fmt.Fprintf(&state.buildBuf, "if %s {\n", ife) defer fmt.Fprintf(&state.buildBuf, "}\n") } // but then for the actual output, we append to vgout.CSS, instead of parentNode fmt.Fprintf(&state.buildBuf, "vgn = &vugu.VGNode{Type:vugu.VGNodeType(%d),Data:%q,Attr:%#v}\n", n.Type, n.Data, staticVGAttr(n.Attr)) // output any text children if n.FirstChild != nil { fmt.Fprintf(&state.buildBuf, "{\n") for childN := n.FirstChild; childN != nil; childN = childN.NextSibling { // NOTE: we already verified above that these are just text nodes fmt.Fprintf(&state.buildBuf, "vgn.AppendChild(&vugu.VGNode{Type:vugu.VGNodeType(%d),Data:%q,Attr:%#v})\n", childN.Type, childN.Data, staticVGAttr(childN.Attr)) } fmt.Fprintf(&state.buildBuf, "}\n") } fmt.Fprintf(&state.buildBuf, "vgout.AppendCSS(vgn)\n") // dynamic attrs writeDynamicAttributes(state, n) return nil } func (p *ParserGo) visitGo(state *parseGoState, n *html.Node) error { for childN := n.FirstChild; childN != nil; childN = childN.NextSibling { if childN.Type != html.TextNode { return fmt.Errorf("unexpected node type %v inside of script tag", childN.Type) } // if childN.Line > 0 { // fmt.Fprintf(&goBuf, "//line %s:%d\n", fname, childN.Line) // } state.goBuf.WriteString(childN.Data) } return nil } // visitTopNode handles the "mount point" func (p *ParserGo) visitTopNode(state *parseGoState, n *html.Node) error { // handle the top element other than <html> err := p.visitNodeJustElement(state, n) if err != nil { return err } return nil } // visitNodeElementAndCtrl handles an element that supports vg-if, vg-for etc func (p *ParserGo) visitNodeElementAndCtrl(state *parseGoState, n *html.Node) error { // vg-for if v, _ := vgForExpr(n); v.expr != "" { if err := p.emitForExpr(state, n); err != nil { return err } defer fmt.Fprintf(&state.buildBuf, "}\n") } // vg-if ife := vgIfExpr(n) if ife != "" { fmt.Fprintf(&state.buildBuf, "if %s {\n", ife) defer fmt.Fprintf(&state.buildBuf, "}\n") } err := p.visitNodeJustElement(state, n) if err != nil { return err } return nil } // visitNodeJustElement handles an element, ignoring any vg-if, vg-for (but it does handle vg-html - since that is not really "control" just a shorthand for it's contents) func (p *ParserGo) visitNodeJustElement(state *parseGoState, n *html.Node) error { // regular element // if n.Line > 0 { // fmt.Fprintf(&buildBuf, "//line %s:%d\n", fname, n.Line) // } pOutputTag(state, n) // fmt.Fprintf(&state.buildBuf, "vgn = &vugu.VGNode{Type:vugu.VGNodeType(%d),Data:%q,Attr:%#v}\n", n.Type, n.Data, staticVGAttr(n.Attr)) // if state.outIsSet { // fmt.Fprintf(&state.buildBuf, "vgparent.AppendChild(vgn)\n") // if not root, make AppendChild call // } else { // fmt.Fprintf(&state.buildBuf, "vgout.Out = append(vgout.Out, vgn) // root for output\n") // for first element we need to assign as Doc on BuildOut // state.outIsSet = true // } // dynamic attrs writeDynamicAttributes(state, n) // vg-js-* writeJSCallbackAttributes(state, n) // js properties propExprMap, propExprMapKeys := propVGAttrExpr(n) for _, k := range propExprMapKeys { valExpr := propExprMap[k] fmt.Fprintf(&state.buildBuf, "{b, err := vjson.Marshal(%s); if err != nil { panic(err) }; vgn.Prop = append(vgn.Prop, vugu.VGProperty{Key:%q,JSONVal:vjson.RawMessage(b)})}\n", valExpr, k) } // vg-html htmlExpr := vgHTMLExpr(n) if htmlExpr != "" { fmt.Fprintf(&state.buildBuf, "vgn.SetInnerHTML(%s)\n", htmlExpr) } // DOM events eventMap, eventKeys := vgDOMEventExprs(n) for _, k := range eventKeys { expr := eventMap[k] fmt.Fprintf(&state.buildBuf, "vgn.DOMEventHandlerSpecList = append(vgn.DOMEventHandlerSpecList, vugu.DOMEventHandlerSpec{\n") fmt.Fprintf(&state.buildBuf, "EventType: %q,\n", k) fmt.Fprintf(&state.buildBuf, "Func: func(event vugu.DOMEvent) { %s },\n", expr) fmt.Fprintf(&state.buildBuf, "// TODO: implement capture, etc. mostly need to decide syntax\n") fmt.Fprintf(&state.buildBuf, "})\n") } if n.FirstChild != nil { fmt.Fprintf(&state.buildBuf, "{\n") fmt.Fprintf(&state.buildBuf, "vgparent := vgn; _ = vgparent\n") // vgparent set for this block to vgn // iterate over children for childN := n.FirstChild; childN != nil; childN = childN.NextSibling { err := p.visitDefaultByType(state, childN) if err != nil { return err } } fmt.Fprintf(&state.buildBuf, "}\n") } return nil } func (p *ParserGo) visitDefaultByType(state *parseGoState, n *html.Node) error { // handle child according to type var err error switch { case n.Type == html.CommentNode: err = p.visitNodeComment(state, n) case n.Type == html.TextNode: err = p.visitNodeText(state, n) case n.Type == html.ElementNode: if strings.Contains(n.Data, ":") { // NOTE: this should check for a capital letter after the colon - this would distinguish // svg:svg (valid regular HTML) from svg:Svg (a component reference) err = p.visitNodeComponentElement(state, n) } else if n.Data == "vg-comp" { err = p.visitVGCompTag(state, n) } else if n.Data == "vg-template" { err = p.visitVGTemplateTag(state, n) } else { err = p.visitNodeElementAndCtrl(state, n) } default: return fmt.Errorf("child node of unknown type %v: %#v", n.Type, n) } if err != nil { return err } return nil } func (p *ParserGo) visitNodeText(state *parseGoState, n *html.Node) error { fmt.Fprintf(&state.buildBuf, "vgn = &vugu.VGNode{Type:vugu.VGNodeType(%d),Data:%q}\n", n.Type, n.Data) fmt.Fprintf(&state.buildBuf, "vgparent.AppendChild(vgn)\n") return nil } func (p *ParserGo) visitNodeComment(state *parseGoState, n *html.Node) error { fmt.Fprintf(&state.buildBuf, "vgn = &vugu.VGNode{Type:vugu.VGNodeType(%d),Data:%q}\n", n.Type, n.Data) fmt.Fprintf(&state.buildBuf, "vgparent.AppendChild(vgn)\n") return nil } // visitVGCompTag handles a vg-comp func (p *ParserGo) visitVGCompTag(state *parseGoState, n *html.Node) error { // vg-for not allowed here // vg-if is supported ife := vgIfExpr(n) if ife != "" { fmt.Fprintf(&state.buildBuf, "if %s {\n", ife) defer fmt.Fprintf(&state.buildBuf, "}\n") } // for now, nothing else supported // must have a "expr" which gives the Go expression which will result in a component expr := vgCompExpr(n) if expr == "" { return fmt.Errorf("vg-comp must have an `expr` attribute with a Go expression in it") } fmt.Fprintf(&state.buildBuf, "{\n") defer fmt.Fprintf(&state.buildBuf, "}\n") fmt.Fprintf(&state.buildBuf, "var vgcomp vugu.Builder = %s\n", expr) fmt.Fprintf(&state.buildBuf, "if vgcomp != nil {\n") fmt.Fprintf(&state.buildBuf, " vgin.BuildEnv.WireComponent(vgcomp)\n") fmt.Fprintf(&state.buildBuf, " vgout.Components = append(vgout.Components, vgcomp)\n") fmt.Fprintf(&state.buildBuf, " vgn = &vugu.VGNode{Component:vgcomp}\n") fmt.Fprintf(&state.buildBuf, " vgparent.AppendChild(vgn)\n") fmt.Fprintf(&state.buildBuf, "}\n") return nil } // visitVGTemplateTag handles vg-template func (p *ParserGo) visitVGTemplateTag(state *parseGoState, n *html.Node) error { // vg-for if v, _ := vgForExpr(n); v.expr != "" { if err := p.emitForExpr(state, n); err != nil { return err } defer fmt.Fprintf(&state.buildBuf, "}\n") } // vg-if ife := vgIfExpr(n) if ife != "" { fmt.Fprintf(&state.buildBuf, "if %s {\n", ife) defer fmt.Fprintf(&state.buildBuf, "}\n") } // output a node with type Element but empty data fmt.Fprintf(&state.buildBuf, "vgn = &vugu.VGNode{Type:vugu.VGNodeType(%d)} // <vg-template>\n", vugu.ElementNode) fmt.Fprintf(&state.buildBuf, "vgparent.AppendChild(vgn)\n") // and then only process children if n.FirstChild != nil { fmt.Fprintf(&state.buildBuf, "{\n") fmt.Fprintf(&state.buildBuf, "vgparent := vgn; _ = vgparent\n") // vgparent set for this block to vgn // iterate over children for childN := n.FirstChild; childN != nil; childN = childN.NextSibling { err := p.visitDefaultByType(state, childN) if err != nil { return err } } fmt.Fprintf(&state.buildBuf, "}\n") } return nil } // visitNodeComponentElement handles an element that is a call to a component func (p *ParserGo) visitNodeComponentElement(state *parseGoState, n *html.Node) error { // components are just different so we handle all of our own vg-for vg-if and everything else // vg-for if v, _ := vgForExpr(n); v.expr != "" { if err := p.emitForExpr(state, n); err != nil { return err } defer fmt.Fprintf(&state.buildBuf, "}\n") } // vg-if ife := vgIfExpr(n) if ife != "" { fmt.Fprintf(&state.buildBuf, "if %s {\n", ife) defer fmt.Fprintf(&state.buildBuf, "}\n") } nodeName := n.OrigData // use original case of element nodeNameParts := strings.Split(nodeName, ":") if len(nodeNameParts) != 2 { return fmt.Errorf("invalid component tag name %q must contain exactly one colon", nodeName) } // x.Y or just Y depending on if in same package typeExpr := strings.Join(nodeNameParts, ".") pkgPrefix := nodeNameParts[0] + "." // needed so we can calc pkg name for pkg.WhateverEvent if nodeNameParts[0] == p.PackageName { typeExpr = nodeNameParts[1] pkgPrefix = "" } compKeyID := compHashCounted(p.StructType + "." + n.OrigData) fmt.Fprintf(&state.buildBuf, "{\n") defer fmt.Fprintf(&state.buildBuf, "}\n") keyExpr := vgKeyExpr(n) if keyExpr != "" { fmt.Fprintf(&state.buildBuf, "vgcompKey := vugu.MakeCompKey(0x%X^vgin.CurrentPositionHash(), %s)\n", compKeyID, keyExpr) } else { fmt.Fprintf(&state.buildBuf, "vgcompKey := vugu.MakeCompKey(0x%X^vgin.CurrentPositionHash(), vgiterkey)\n", compKeyID) } fmt.Fprintf(&state.buildBuf, "// ask BuildEnv for prior instance of this specific component\n") fmt.Fprintf(&state.buildBuf, "vgcomp, _ := vgin.BuildEnv.CachedComponent(vgcompKey).(*%s)\n", typeExpr) fmt.Fprintf(&state.buildBuf, "if vgcomp == nil {\n") fmt.Fprintf(&state.buildBuf, "// create new one if needed\n") fmt.Fprintf(&state.buildBuf, "vgcomp = new(%s)\n", typeExpr) fmt.Fprintf(&state.buildBuf, "vgin.BuildEnv.WireComponent(vgcomp)\n") fmt.Fprintf(&state.buildBuf, "}\n") fmt.Fprintf(&state.buildBuf, "vgin.BuildEnv.UseComponent(vgcompKey, vgcomp) // ensure we can use this in the cache next time around\n") // now that we have vgcomp with the right type and a correct value, we can declare the vg-var if specified if vgv := vgVarExpr(n); vgv != "" { fmt.Fprintf(&state.buildBuf, "var %s = vgcomp // vg-var\n", vgv) // NOTE: It's a bit too much to have "unused variable" errors coming from a Vugu code-generated file, // too far off the beaten path of making "type-safe HTML templates with Go". It makes sense with // hand-written Go code but I don't think so here. fmt.Fprintf(&state.buildBuf, "_ = %s\n", vgv) // avoid unused var error } didAttrMap := false // dynamic attrs dynExprMap, dynExprMapKeys := dynamicVGAttrExpr(n) for _, k := range dynExprMapKeys { // if k == "" { // return fmt.Errorf("invalid empty dynamic attribute name on component %#v", n) // } valExpr := dynExprMap[k] // if starts with upper case, it's a field name if hasUpperFirst(k) { fmt.Fprintf(&state.buildBuf, "vgcomp.%s = %s\n", k, valExpr) } else { // otherwise we use an "AttrMap" if !didAttrMap { didAttrMap = true fmt.Fprintf(&state.buildBuf, "vgcomp.AttrMap = make(map[string]interface{}, 8)\n") } fmt.Fprintf(&state.buildBuf, "vgcomp.AttrMap[%q] = %s\n", k, valExpr) } } // static attrs vgAttrs := staticVGAttr(n.Attr) for _, a := range vgAttrs { // if starts with upper case, it's a field name if hasUpperFirst(a.Key) { fmt.Fprintf(&state.buildBuf, "vgcomp.%s = %q\n", a.Key, a.Val) } else { // otherwise we use an "AttrMap" if !didAttrMap { didAttrMap = true fmt.Fprintf(&state.buildBuf, "vgcomp.AttrMap = make(map[string]interface{}, 8)\n") } fmt.Fprintf(&state.buildBuf, "vgcomp.AttrMap[%q] = %q\n", a.Key, a.Val) } } // component events // NOTE: We keep component events really simple and the @ is just a thin wrapper around a field assignment: // <pkg:Comp @Something="log.Println(event)"></pkg:Comp> // is shorthand for: // <pkg:Comp :Something='func(event pkg.SomethingEvent) { log.Println(event) }'></pkg:Comp> // // I considered using the handler interface function approach for this, but it would mean // SomethingHandlerFunc would have to exist as a type, with a SomethingHandle method, which // implements a SomethingHandler interface, so the type of Comp.Something could be SomethingHandler, // and the emitted code could be vgcomp.Something = pkg.SomethingHandlerFunc(func...) // But that's two additional types and a method for every event. I'm very concerned that it will // make component events feel crufty and arduous to implement (unless we could find a good way // to automatically generate those when missing - that's a possibility - actually I think // I'm going to try this, see https://github.com/vugu/vugu/issues/128). // But this this way with a func you can just do // type SomethingEvent struct { /* whatever relevant data */ } and then define your field on // your component as Something func(SomethingEvent) - still type-safe but very straightforward. // So far it seems like the best approach. eventMap, eventKeys := vgEventExprs(n) for _, k := range eventKeys { expr := eventMap[k] // fmt.Fprintf(&state.buildBuf, "vgcomp.%s = func(event %s%sEvent){%s}\n", k, pkgPrefix, k, expr) // switched to using interfaces fmt.Fprintf(&state.buildBuf, "vgcomp.%s = %s%sFunc(func(event %s%sEvent){%s})\n", k, pkgPrefix, k, pkgPrefix, k, expr) } // NOTE: vugugen:slot might come in really handy, have to work out the types involved - update: as it stands, this won't be needed. // slots: // scan children and see if it's default slot mode or vg-slot tags foundTagSlot, foundDefSlot := false, false var foundTagSlotNames []string for childN := n.FirstChild; childN != nil; childN = childN.NextSibling { // non-ws text means default slot if childN.Type == html.TextNode { if strings.TrimSpace(childN.Data) != "" { foundDefSlot = true } continue } // ignore comments if childN.Type == html.CommentNode { continue } // should only be element at this point if childN.Type != html.ElementNode { return fmt.Errorf("in tag %q unexpected node found where slot expected: %#v", n.Data, childN) } if childN.Data == "vg-slot" { foundTagSlot = true name := strings.TrimSpace(vgSlotName(childN)) if name != "" { foundTagSlotNames = append(foundTagSlotNames, name) } } else { foundDefSlot = true } } // now process slot(s) appropriately according to format switch { case foundTagSlot && foundDefSlot: return fmt.Errorf("in tag %q found both vg-slot and other markup, only one or the other is allowed", n.Data) case foundTagSlot: // NOTE: // <vg-slot name="X"> will assign to vgcomp.X // <vg-slot name='X[Y]'> will assume X is of type map[string]Builder and create the map and then assign with X[Y] = // find any names with map expressions and clear the maps sort.Strings(foundTagSlotNames) slotMapInited := make(map[string]bool) for _, slotName := range foundTagSlotNames { slotNameParts := strings.Split(slotName, "[") // check for map expr if len(slotNameParts) > 1 { // if map if slotMapInited[slotNameParts[0]] { // if not already initialized continue } slotMapInited[slotNameParts[0]] = true // if nil create map, otherwise reuse fmt.Fprintf(&state.buildBuf, "if vgcomp.%s == nil {\n", slotNameParts[0]) fmt.Fprintf(&state.buildBuf, " vgcomp.%s = make(map[string]vugu.Builder)\n", slotNameParts[0]) fmt.Fprintf(&state.buildBuf, "} else {\n") fmt.Fprintf(&state.buildBuf, " for k := range vgcomp.%s { delete(vgcomp.%s, k) }\n", slotNameParts[0], slotNameParts[0]) fmt.Fprintf(&state.buildBuf, "}\n") } } // iterate over children for childN := n.FirstChild; childN != nil; childN = childN.NextSibling { // ignore white space and coments if childN.Type == html.CommentNode || (childN.Type == html.TextNode && strings.TrimSpace(childN.Data) == "") { continue } if childN.Type != html.ElementNode { // should be impossible from foundTagSlot check above, just making sure panic(fmt.Errorf("unexpected non-element found where vg-slot should be: %#v", childN)) } if childN.Data != "vg-slot" { // should also be imposible panic(fmt.Errorf("unexpected element found where vg-slot should be: %#v", childN)) } slotName := strings.TrimSpace(vgSlotName(childN)) if slotName == "" { return fmt.Errorf("found vg-slot tag without a 'name' attribute, the name is required") } fmt.Fprintf(&state.buildBuf, "vgcomp.%s = vugu.NewBuilderFunc(func(vgin *vugu.BuildIn) (vgout *vugu.BuildOut) {\n", slotName) fmt.Fprintf(&state.buildBuf, "vgn := &vugu.VGNode{Type:vugu.VGNodeType(%d)}\n", vugu.ElementNode) fmt.Fprintf(&state.buildBuf, "vgout = &vugu.BuildOut{}\n") fmt.Fprintf(&state.buildBuf, "vgout.Out = append(vgout.Out, vgn)\n") fmt.Fprintf(&state.buildBuf, "vgparent := vgn; _ = vgparent\n") fmt.Fprintf(&state.buildBuf, "\n") // iterate over children and do the usual with each one for innerChildN := childN.FirstChild; innerChildN != nil; innerChildN = innerChildN.NextSibling { err := p.visitDefaultByType(state, innerChildN) if err != nil { return err } } fmt.Fprintf(&state.buildBuf, "return\n") fmt.Fprintf(&state.buildBuf, "})\n") } case foundDefSlot: fmt.Fprintf(&state.buildBuf, "vgcomp.DefaultSlot = vugu.NewBuilderFunc(func(vgin *vugu.BuildIn) (vgout *vugu.BuildOut) {\n") // vgn is the equivalent of a vg-template tag and becomes the contents of vgout.Out and the vgparent fmt.Fprintf(&state.buildBuf, "vgn := &vugu.VGNode{Type:vugu.VGNodeType(%d)}\n", vugu.ElementNode) fmt.Fprintf(&state.buildBuf, "vgout = &vugu.BuildOut{}\n") fmt.Fprintf(&state.buildBuf, "vgout.Out = append(vgout.Out, vgn)\n") fmt.Fprintf(&state.buildBuf, "vgparent := vgn; _ = vgparent\n") fmt.Fprintf(&state.buildBuf, "\n") // iterate over children and do the usual with each one for childN := n.FirstChild; childN != nil; childN = childN.NextSibling { err := p.visitDefaultByType(state, childN) if err != nil { return err } } fmt.Fprintf(&state.buildBuf, "return\n") fmt.Fprintf(&state.buildBuf, "})\n") default: // nothing meaningful inside this component tag } // // keep track of contents for default slot // var defSlotNodes []*html.Node // defSlotMode := false // start off not in default slot mode and look for <vg-slot> tags // // loop over all component children // for childN := n.FirstChild; childN != nil; childN = childN.NextSibling { // if !defSlotMode { // // anything not an element just add to the list for default // if childN.Type != html.ElementNode { // defSlotNodes = append(defSlotNodes, childN) // continue // } // if childN.Data == "vg-slot" { // } // } // } // ignore whitespace // first non-slot, non-ws child, assume "DefaultSlot" (or whatever name) and consume rest of children // if vg-slot, then consume with specified name // <vg-slot name="SomeSlot"> <!-- field name syntax // <vg-slot name='SomeDynaSlot' index='"Row.FirstName"'> <!-- expression syntax, HM, NO // <vg-slot index='SomeDynaSlot["Row.FirstName"]'> <!-- maybe this - still annoying that we have to limit it to a map expression, but whatever // emit vgcomp.SlotName = vugu.NewBuilderFunc(func(vgin *vugu.BuildIn) (vgout *BuildOut, vgerr error) { ... }) // and descend into children fmt.Fprintf(&state.buildBuf, "vgout.Components = append(vgout.Components, vgcomp)\n") fmt.Fprintf(&state.buildBuf, "vgn = &vugu.VGNode{Component:vgcomp}\n") fmt.Fprintf(&state.buildBuf, "vgparent.AppendChild(vgn)\n") return nil // return fmt.Errorf("component tag not yet supported (%q)", nodeName) } // NOTE: caller is responsible for emitting the closing curly bracket func (p *ParserGo) emitForExpr(state *parseGoState, n *html.Node) error { forattr, err := vgForExpr(n) if err != nil { return err } forx := forattr.expr if forx == "" { return errors.New("no for expression, code should not be calling emitForExpr when no vg-for is present") } // cases to select vgiterkey: // * check for vg-key attribute // * _, v := // replace _ with vgiterkey // * key, value := // unused vars, use 'key' as iter val // * k, v := // detect `k` and use as iterval vgiterkeyx := vgKeyExpr(n) // determine iteration variables var iterkey, iterval string if !strings.Contains(forx, ":=") { // make it so `w` is a shorthand for `key, value := range w` iterkey, iterval = "key", "value" forx = "key, value := range " + forx } else { // extract iteration variables var ( itervars [2]string iteridx int ) for _, c := range forx { if c == ':' { break } if c == ',' { iteridx++ continue } if unicode.IsSpace(c) { continue } itervars[iteridx] += string(c) } iterkey = itervars[0] iterval = itervars[1] } // detect "_, k := " form combined with no vg-key specified and replace if vgiterkeyx == "" && iterkey == "_" { iterkey = "vgiterkeyt" forx = "vgiterkeyt " + forx[1:] } // if still no vgiterkeyx use the first identifier if vgiterkeyx == "" { vgiterkeyx = iterkey } fmt.Fprintf(&state.buildBuf, "for %s {\n", forx) fmt.Fprintf(&state.buildBuf, "var vgiterkey interface{} = %s\n", vgiterkeyx) fmt.Fprintf(&state.buildBuf, "_ = vgiterkey\n") if !forattr.noshadow { if iterkey != "_" && iterkey != "vgiterkeyt" { fmt.Fprintf(&state.buildBuf, "%[1]s := %[1]s\n", iterkey) fmt.Fprintf(&state.buildBuf, "_ = %s\n", iterkey) } if iterval != "_" && iterval != "" { fmt.Fprintf(&state.buildBuf, "%[1]s := %[1]s\n", iterval) fmt.Fprintf(&state.buildBuf, "_ = %s\n", iterval) } } return nil } func hasUpperFirst(s string) bool { for _, c := range s { return unicode.IsUpper(c) } return false } // isScriptOrStyle returns true if this is a "script", "style" or "link" tag func isScriptOrStyle(n *html.Node) bool { if n.Type != html.ElementNode { return false } switch strings.ToLower(n.Data) { case "script", "style", "link": return true } return false } func pOutputTag(state *parseGoState, n *html.Node) { fmt.Fprintf(&state.buildBuf, "vgn = &vugu.VGNode{Type:vugu.VGNodeType(%d),Namespace:%q,Data:%q,Attr:%#v}\n", n.Type, n.Namespace, n.Data, staticVGAttr(n.Attr)) if state.outIsSet { fmt.Fprintf(&state.buildBuf, "vgparent.AppendChild(vgn)\n") // if not root, make AppendChild call } else { fmt.Fprintf(&state.buildBuf, "vgout.Out = append(vgout.Out, vgn) // root for output\n") // for first element we need to assign as Doc on BuildOut state.outIsSet = true } } func attrWithKey(n *html.Node, key string) *html.Attribute { for i := range n.Attr { if n.Attr[i].Key == key { return &n.Attr[i] } } return nil } func writeDynamicAttributes(state *parseGoState, n *html.Node) { dynExprMap, dynExprMapKeys := dynamicVGAttrExpr(n) for _, k := range dynExprMapKeys { valExpr := dynExprMap[k] if k == "" || k == "vg-attr" { fmt.Fprintf(&state.buildBuf, "vgn.AddAttrList(%s)\n", valExpr) } else { fmt.Fprintf(&state.buildBuf, "vgn.AddAttrInterface(%q,%s)\n", k, valExpr) } } } // writeJSCallbackAttributes handles vg-js-create and vg-js-populate func writeJSCallbackAttributes(state *parseGoState, n *html.Node) { m := jsCallbackVGAttrExpr(n) createStmt := m["vg-js-create"] if createStmt != "" { fmt.Fprintf(&state.buildBuf, "vgn.JSCreateHandler = vugu.JSValueFunc(func(value js.Value) { %s })\n", createStmt) } populateStmt := m["vg-js-populate"] if populateStmt != "" { fmt.Fprintf(&state.buildBuf, "vgn.JSPopulateHandler = vugu.JSValueFunc(func(value js.Value) { %s })\n", populateStmt) } }
package floc import "fmt" // ResultSet is the set of possible results. This set is the simple // implementation of Set with no check for duplicate values and it covers only // basic needs of floc. type ResultSet []Result // NewResultSet constructs the set with given results. The function validates // all result values first and panics on any invalid result. func NewResultSet(results ...Result) ResultSet { // Validate results for _, res := range results { if !res.IsValid() { panic(fmt.Errorf("invalid result %s in result set", res.String())) } } return results } // Contains tests if the set contains the result. func (set ResultSet) Contains(result Result) bool { for _, res := range set { if res == result { return true } } return false }
package workers_test import ( "encoding/json" "fmt" "github.com/APTrust/exchange/constants" "github.com/APTrust/exchange/models" "github.com/APTrust/exchange/network" "github.com/APTrust/exchange/util/testutil" "github.com/APTrust/exchange/workers" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "io/ioutil" "net/http" "net/http/httptest" "os" "regexp" "strconv" "strings" "sync" "testing" "time" ) // The following package-level vars tell the HTTP test handlers // how to behave when we make requests. We have to do this because // we don't have control over the requests themselves, which are // generated by other libraries. var NumberOfRequestsToIncludeInState = 0 const ( NotStartedHead = 0 NotStartedAcceptNow = 1 NotStartedRejectNow = 2 InProgressHead = 3 InProgressGlacier = 4 Completed = 5 ) var DescribeRestoreStateAs = NotStartedHead const TEST_ID = 1000 var updatedWorkItem = &models.WorkItem{} var createdWorkItem = &models.WorkItem{} var updatedWorkItemState = &models.WorkItemState{} // Regex to extract ID from URL var URL_ID_REGEX = regexp.MustCompile(`\/(\d+)\/`) // Test server to handle Pharos requests var pharosTestServer = httptest.NewServer(http.HandlerFunc(pharosHandler)) // Test server to handle S3 requests var s3TestServer = httptest.NewServer(http.HandlerFunc(s3Handler)) func getGlacierRestoreWorker(t *testing.T) *workers.APTGlacierRestoreInit { _context, err := testutil.GetContext("integration.json") require.Nil(t, err) if !testutil.ShouldRunIntegrationTests() { _context.PharosClient = getPharosClientForTest(pharosTestServer.URL) } return workers.NewGlacierRestore(_context) } func getObjectWorkItem(id int, objectIdentifier string) *models.WorkItem { workItemStateId := 1000 return &models.WorkItem{ Id: id, ObjectIdentifier: objectIdentifier, GenericFileIdentifier: "", Name: "glacier_bag.tar", Bucket: "aptrust.receiving.test.edu", ETag: "0000000000000000", BagDate: testutil.RandomDateTime(), InstitutionId: 33, User: "frank.zappa@example.com", Date: testutil.RandomDateTime(), Note: "", Action: constants.ActionGlacierRestore, Stage: constants.StageRequested, Status: constants.StatusPending, Outcome: "", Retry: true, Node: "", Pid: 0, NeedsAdminReview: false, WorkItemStateId: &workItemStateId, } } func getFileWorkItem(id int, objectIdentifier, fileIdentifier string) *models.WorkItem { workItem := getObjectWorkItem(id, objectIdentifier) workItem.GenericFileIdentifier = fileIdentifier return workItem } func getPharosClientForTest(url string) *network.PharosClient { client, _ := network.NewPharosClient(url, "v2", "frankzappa", "abcxyz") return client } func getTestComponents(t *testing.T, fileOrObject string) (*workers.APTGlacierRestoreInit, *models.GlacierRestoreState) { worker := getGlacierRestoreWorker(t) require.NotNil(t, worker) // Tell the worker to talk to our S3 test server and Pharos // test server, defined below worker.S3Url = s3TestServer.URL worker.Context.PharosClient = getPharosClientForTest(pharosTestServer.URL) // Set up the GlacierRestoreStateObject objIdentifier := "test.edu/glacier_bag" // Note that we're getting a WorkItem that has a GenericFileIdentifier var workItem *models.WorkItem if fileOrObject == "object" { workItem = getObjectWorkItem(TEST_ID, objIdentifier) } else { workItem = getFileWorkItem(TEST_ID, objIdentifier, objIdentifier+"/file1.txt") } nsqMessage := testutil.MakeNsqMessage(fmt.Sprintf("%d", TEST_ID)) state, err := worker.GetGlacierRestoreState(nsqMessage, workItem) require.Nil(t, err) require.NotNil(t, state) return worker, state } // ------ TESTS -------- func TestNewGlacierRestore(t *testing.T) { glacierRestore := getGlacierRestoreWorker(t) require.NotNil(t, glacierRestore) assert.NotNil(t, glacierRestore.Context) assert.NotNil(t, glacierRestore.RequestChannel) assert.NotNil(t, glacierRestore.CleanupChannel) } func TestGetGlacierRestoreState(t *testing.T) { worker, state := getTestComponents(t, "object") NumberOfRequestsToIncludeInState = 0 worker.Context.PharosClient = getPharosClientForTest(pharosTestServer.URL) state, err := worker.GetGlacierRestoreState(state.NSQMessage, state.WorkItem) require.Nil(t, err) require.NotNil(t, state) assert.NotNil(t, state.WorkSummary) assert.Empty(t, state.Requests) NumberOfRequestsToIncludeInState = 10 state, err = worker.GetGlacierRestoreState(state.NSQMessage, state.WorkItem) require.Nil(t, err) require.NotNil(t, state) assert.NotNil(t, state.WorkSummary) require.NotEmpty(t, state.Requests) assert.Equal(t, NumberOfRequestsToIncludeInState, len(state.Requests)) } func TestRequestObject(t *testing.T) { NumberOfRequestsToIncludeInState = 0 DescribeRestoreStateAs = NotStartedHead worker, state := getTestComponents(t, "object") require.Nil(t, state.IntellectualObject) worker.RequestObject(state) require.NotNil(t, state.IntellectualObject) require.NotEmpty(t, state.IntellectualObject.GenericFiles) // Should be 12 of each assert.Equal(t, len(state.IntellectualObject.GenericFiles), len(state.Requests)) for _, req := range state.Requests { assert.NotEmpty(t, req.GenericFileIdentifier) assert.NotEmpty(t, req.GlacierBucket) assert.NotEmpty(t, req.GlacierKey) assert.False(t, req.RequestedAt.IsZero()) assert.False(t, req.RequestAccepted) assert.False(t, req.IsAvailableInS3) } DescribeRestoreStateAs = NotStartedAcceptNow worker, state = getTestComponents(t, "object") require.Nil(t, state.IntellectualObject) worker.RequestObject(state) assert.Equal(t, len(state.IntellectualObject.GenericFiles), len(state.Requests)) for _, req := range state.Requests { assert.NotEmpty(t, req.GenericFileIdentifier) assert.NotEmpty(t, req.GlacierBucket) assert.NotEmpty(t, req.GlacierKey) assert.False(t, req.RequestedAt.IsZero()) assert.True(t, req.RequestAccepted) assert.False(t, req.IsAvailableInS3) } } func TestRestoreRequestNeeded(t *testing.T) { worker, state := getTestComponents(t, "object") require.Nil(t, state.IntellectualObject) // Now let's check to see if we need to issue a Glacier restore // request for the following file. Tell the s3 test server to // reply that this restore has not been requested yet for this item. DescribeRestoreStateAs = NotStartedHead gf := testutil.MakeGenericFile(0, 0, state.WorkItem.ObjectIdentifier) fileUUID, _ := gf.PreservationStorageFileName() requestNeeded, err := worker.RestoreRequestNeeded(state, gf) require.Nil(t, err) assert.True(t, requestNeeded) // Make sure the GlacierRestore worker created a // GlacierRestoreRequest record for this file. // In the test environment, glacierRestoreRequest.GlacierBucket // will be an empty string. glacierRestoreRequest := state.FindRequest(gf.Identifier) require.NotNil(t, glacierRestoreRequest) assert.Equal(t, fileUUID, glacierRestoreRequest.GlacierKey) // Request cannot have been accepted, because it hasn't been issued. assert.False(t, glacierRestoreRequest.RequestAccepted) assert.False(t, glacierRestoreRequest.IsAvailableInS3) assert.False(t, glacierRestoreRequest.SomeoneElseRequested) assert.True(t, glacierRestoreRequest.RequestedAt.IsZero()) assert.WithinDuration(t, time.Now().UTC(), glacierRestoreRequest.LastChecked, 10*time.Second) // Check to see if we need to issue a Glacier restore // request for a file that we've already requested and whose // restoration is currently in progress. Tell the s3 test server to // reply that restore is in progress for this item. DescribeRestoreStateAs = InProgressHead gf = testutil.MakeGenericFile(0, 0, state.WorkItem.ObjectIdentifier) fileUUID, _ = gf.PreservationStorageFileName() requestNeeded, err = worker.RestoreRequestNeeded(state, gf) require.Nil(t, err) assert.False(t, requestNeeded) // Make sure the GlacierRestore worker created a // GlacierRestoreRequest record for this file. glacierRestoreRequest = state.FindRequest(gf.Identifier) require.NotNil(t, glacierRestoreRequest) assert.Equal(t, fileUUID, glacierRestoreRequest.GlacierKey) // Request must have been accepted, because the restore is in progress. assert.True(t, glacierRestoreRequest.RequestAccepted) assert.False(t, glacierRestoreRequest.IsAvailableInS3) assert.False(t, glacierRestoreRequest.SomeoneElseRequested) assert.False(t, glacierRestoreRequest.RequestedAt.IsZero()) assert.WithinDuration(t, time.Now().UTC(), glacierRestoreRequest.LastChecked, 10*time.Second) // Check to see if we need to issue a Glacier restore // request for a file that's already been restored to S3. // Tell the s3 test server to reply that restore is complete for this item. DescribeRestoreStateAs = Completed gf = testutil.MakeGenericFile(0, 0, state.WorkItem.ObjectIdentifier) fileUUID, _ = gf.PreservationStorageFileName() requestNeeded, err = worker.RestoreRequestNeeded(state, gf) require.Nil(t, err) assert.False(t, requestNeeded) // Make sure the GlacierRestore worker created a // GlacierRestoreRequest record for this file. glacierRestoreRequest = state.FindRequest(gf.Identifier) require.NotNil(t, glacierRestoreRequest) assert.Equal(t, fileUUID, glacierRestoreRequest.GlacierKey) // Request must have been accepted, because the restore is in progress. assert.True(t, glacierRestoreRequest.RequestAccepted) assert.True(t, glacierRestoreRequest.IsAvailableInS3) assert.False(t, glacierRestoreRequest.SomeoneElseRequested) assert.False(t, glacierRestoreRequest.RequestedAt.IsZero()) assert.False(t, glacierRestoreRequest.EstimatedDeletionFromS3.IsZero()) assert.WithinDuration(t, time.Now().UTC(), glacierRestoreRequest.LastChecked, 10*time.Second) } func TestGetS3HeadClient(t *testing.T) { worker := getGlacierRestoreWorker(t) require.NotNil(t, worker) // Standard client, err := worker.GetS3HeadClient(constants.StorageStandard) require.Nil(t, err) require.NotNil(t, client) assert.Equal(t, worker.Context.Config.APTrustS3Region, client.AWSRegion) assert.Equal(t, worker.Context.Config.PreservationBucket, client.BucketName) // Glacier OH client, err = worker.GetS3HeadClient(constants.StorageGlacierOH) require.Nil(t, err) require.NotNil(t, client) assert.Equal(t, worker.Context.Config.GlacierRegionOH, client.AWSRegion) assert.Equal(t, worker.Context.Config.GlacierBucketOH, client.BucketName) // Glacier OR client, err = worker.GetS3HeadClient(constants.StorageGlacierOR) require.Nil(t, err) require.NotNil(t, client) assert.Equal(t, worker.Context.Config.GlacierRegionOR, client.AWSRegion) assert.Equal(t, worker.Context.Config.GlacierBucketOR, client.BucketName) // Glacier VA client, err = worker.GetS3HeadClient(constants.StorageGlacierVA) require.Nil(t, err) require.NotNil(t, client) assert.Equal(t, worker.Context.Config.GlacierRegionVA, client.AWSRegion) assert.Equal(t, worker.Context.Config.GlacierBucketVA, client.BucketName) } func TestGetIntellectualObject(t *testing.T) { worker, state := getTestComponents(t, "object") require.Nil(t, state.IntellectualObject) require.Nil(t, state.IntellectualObject) obj, err := worker.GetIntellectualObject(state) assert.Nil(t, err) require.NotNil(t, obj) assert.Equal(t, 12, len(obj.GenericFiles)) } func TestGetGenericFile(t *testing.T) { worker, state := getTestComponents(t, "file") require.Nil(t, state.GenericFile) state, err := worker.GetGlacierRestoreState(state.NSQMessage, state.WorkItem) require.Nil(t, err) require.NotNil(t, state) require.Nil(t, state.GenericFile) gf, err := worker.GetGenericFile(state) assert.Nil(t, err) require.NotNil(t, gf) assert.NotEmpty(t, gf.Identifier) assert.NotEmpty(t, gf.StorageOption) assert.NotEmpty(t, gf.URI) } func TestUpdateWorkItem(t *testing.T) { worker, state := getTestComponents(t, "object") state.WorkItem.Note = "Updated note" state.WorkItem.Node = "blah-blah-blah" state.WorkItem.Pid = 9800 state.WorkItem.Status = constants.StatusSuccess worker.UpdateWorkItem(state) assert.Empty(t, state.WorkSummary.Errors) assert.Equal(t, "Updated note", updatedWorkItem.Note) assert.Equal(t, "blah-blah-blah", updatedWorkItem.Node) assert.Equal(t, 9800, updatedWorkItem.Pid) assert.Equal(t, constants.StatusSuccess, updatedWorkItem.Status) } func TestSaveWorkItemState(t *testing.T) { worker, state := getTestComponents(t, "object") requestCount := len(state.Requests) for i := 0; i < 10; i++ { request := &models.GlacierRestoreRequest{ GenericFileIdentifier: fmt.Sprintf("%s/file%d.txt", state.WorkItem.ObjectIdentifier, i), } state.Requests = append(state.Requests, request) } worker.SaveWorkItemState(state) require.NotNil(t, updatedWorkItemState) require.True(t, updatedWorkItemState.HasData()) glacierRestoreState, err := updatedWorkItemState.GlacierRestoreState() require.Nil(t, err) assert.Equal(t, requestCount+10, len(glacierRestoreState.Requests)) } func TestFinishWithError(t *testing.T) { worker, state := getTestComponents(t, "object") delegate := testutil.NewNSQTestDelegate() state.NSQMessage.Delegate = delegate state.WorkSummary.AddError("Error 1") state.WorkSummary.AddError("Error 2") worker.FinishWithError(state) assert.Equal(t, "finish", delegate.Operation) assert.Equal(t, state.WorkSummary.AllErrorsAsString(), state.WorkItem.Note) assert.Equal(t, constants.StatusFailed, state.WorkItem.Status) assert.False(t, state.WorkItem.Retry) assert.True(t, state.WorkItem.NeedsAdminReview) } func TestRequeueForAdditionalRequests(t *testing.T) { worker, state := getTestComponents(t, "object") delegate := testutil.NewNSQTestDelegate() state.NSQMessage.Delegate = delegate worker.RequeueForAdditionalRequests(state) assert.Equal(t, "requeue", delegate.Operation) assert.Equal(t, 1*time.Minute, delegate.Delay) assert.Equal(t, "Requeued to make additional Glacier restore requests.", state.WorkItem.Note) assert.Equal(t, constants.StatusStarted, state.WorkItem.Status) assert.True(t, state.WorkItem.Retry) assert.False(t, state.WorkItem.NeedsAdminReview) } func TestRequeueToCheckState(t *testing.T) { worker, state := getTestComponents(t, "object") delegate := testutil.NewNSQTestDelegate() state.NSQMessage.Delegate = delegate worker.RequeueToCheckState(state) assert.Equal(t, "requeue", delegate.Operation) assert.Equal(t, 2*time.Hour, delegate.Delay) assert.Equal(t, "Requeued to check on status of Glacier restore requests.", state.WorkItem.Note) assert.Equal(t, constants.StatusStarted, state.WorkItem.Status) assert.True(t, state.WorkItem.Retry) assert.False(t, state.WorkItem.NeedsAdminReview) } func TestCreateRestoreWorkItem(t *testing.T) { createdWorkItem = &models.WorkItem{} worker, state := getTestComponents(t, "object") worker.CreateRestoreWorkItem(state) assert.Equal(t, constants.StatusSuccess, state.WorkItem.Status) assert.Equal(t, state.WorkItem.ObjectIdentifier, createdWorkItem.ObjectIdentifier) assert.Equal(t, state.WorkItem.GenericFileIdentifier, createdWorkItem.GenericFileIdentifier) assert.Equal(t, state.WorkItem.Name, createdWorkItem.Name) assert.Equal(t, state.WorkItem.Bucket, createdWorkItem.Bucket) assert.Equal(t, state.WorkItem.ETag, createdWorkItem.ETag) assert.Equal(t, state.WorkItem.Size, createdWorkItem.Size) assert.Equal(t, state.WorkItem.BagDate, createdWorkItem.BagDate) assert.Equal(t, state.WorkItem.InstitutionId, createdWorkItem.InstitutionId) assert.Equal(t, state.WorkItem.User, createdWorkItem.User) assert.Equal(t, constants.ActionRestore, createdWorkItem.Action) assert.Equal(t, constants.StageRequested, createdWorkItem.Stage) assert.Equal(t, constants.StatusPending, createdWorkItem.Status) assert.Equal(t, "Restore requested. Files have been moved from Glacier to S3.", createdWorkItem.Note) assert.Equal(t, "Not started", createdWorkItem.Outcome) assert.False(t, createdWorkItem.Date.IsZero()) assert.True(t, createdWorkItem.Retry) } func TestRequestAllFiles(t *testing.T) { NumberOfRequestsToIncludeInState = 0 DescribeRestoreStateAs = NotStartedAcceptNow worker, state := getTestComponents(t, "object") state.IntellectualObject = testutil.MakeIntellectualObject(12, 0, 0, 0) DescribeRestoreStateAs = NotStartedAcceptNow worker.RequestAllFiles(state) assert.Empty(t, state.WorkSummary.Errors) assert.NotNil(t, state.IntellectualObject) assert.Equal(t, 12, len(state.Requests)) for _, req := range state.Requests { assert.NotEmpty(t, req.GenericFileIdentifier) assert.NotEmpty(t, req.GlacierBucket) assert.NotEmpty(t, req.GlacierKey) assert.False(t, req.RequestedAt.IsZero()) assert.True(t, req.RequestAccepted) assert.False(t, req.IsAvailableInS3) } } func TestRequestFile(t *testing.T) { worker, state := getTestComponents(t, "file") delegate := testutil.NewNSQTestDelegate() state.NSQMessage.Delegate = delegate gf, err := worker.GetGenericFile(state) assert.Nil(t, err) require.NotNil(t, gf) // Call RequestFile then check the state of the // GlacierRestoreRequest for that file. DescribeRestoreStateAs = NotStartedRejectNow worker.RequestFile(state, gf) glacierRestoreRequest := worker.GetRequestRecord(state, gf, make(map[string]string)) timeOfFirstRequest := glacierRestoreRequest.RequestedAt require.NotNil(t, glacierRestoreRequest) assert.False(t, glacierRestoreRequest.RequestedAt.IsZero()) assert.True(t, glacierRestoreRequest.LastChecked.IsZero()) assert.False(t, glacierRestoreRequest.RequestAccepted) assert.False(t, glacierRestoreRequest.IsAvailableInS3) // Now accept the request and make sure the request record // was properly updated. DescribeRestoreStateAs = NotStartedAcceptNow worker.RequestFile(state, gf) glacierRestoreRequest = worker.GetRequestRecord(state, gf, make(map[string]string)) require.NotNil(t, glacierRestoreRequest) assert.True(t, glacierRestoreRequest.LastChecked.IsZero()) assert.True(t, glacierRestoreRequest.RequestedAt.After(timeOfFirstRequest)) assert.False(t, glacierRestoreRequest.IsAvailableInS3) // Make sure LastChecked is updated when we do a status check // via S3 Head on a file whose restoration request was accepted by Glacier. DescribeRestoreStateAs = InProgressGlacier worker.RequestFile(state, gf) glacierRestoreRequest = worker.GetRequestRecord(state, gf, make(map[string]string)) require.NotNil(t, glacierRestoreRequest) assert.True(t, glacierRestoreRequest.LastChecked.IsZero()) assert.False(t, glacierRestoreRequest.IsAvailableInS3) } func TestGetRequestDetails(t *testing.T) { worker, state := getTestComponents(t, "file") require.Nil(t, state.GenericFile) state, err := worker.GetGlacierRestoreState(state.NSQMessage, state.WorkItem) require.Nil(t, err) require.NotNil(t, state) require.Nil(t, state.GenericFile) gf, err := worker.GetGenericFile(state) assert.Nil(t, err) require.NotNil(t, gf) fileUUID, err := gf.PreservationStorageFileName() require.Nil(t, err) // Glacier Ohio gf.StorageOption = constants.StorageGlacierOH details, err := worker.GetRequestDetails(gf) require.Nil(t, err) require.NotNil(t, details) assert.Equal(t, fileUUID, details["fileUUID"]) assert.Equal(t, worker.Context.Config.GlacierRegionOH, details["region"]) assert.Equal(t, worker.Context.Config.GlacierBucketOH, details["bucket"]) // Glacier Oregon gf.StorageOption = constants.StorageGlacierOR details, err = worker.GetRequestDetails(gf) require.Nil(t, err) require.NotNil(t, details) assert.Equal(t, fileUUID, details["fileUUID"]) assert.Equal(t, worker.Context.Config.GlacierRegionOR, details["region"]) assert.Equal(t, worker.Context.Config.GlacierBucketOR, details["bucket"]) // Glacier Virginia gf.StorageOption = constants.StorageGlacierVA details, err = worker.GetRequestDetails(gf) require.Nil(t, err) require.NotNil(t, details) assert.Equal(t, fileUUID, details["fileUUID"]) assert.Equal(t, worker.Context.Config.GlacierRegionVA, details["region"]) assert.Equal(t, worker.Context.Config.GlacierBucketVA, details["bucket"]) // Standard storage gf.StorageOption = constants.StorageStandard details, err = worker.GetRequestDetails(gf) require.Nil(t, err) require.NotNil(t, details) assert.Equal(t, fileUUID, details["fileUUID"]) assert.Equal(t, worker.Context.Config.APTrustGlacierRegion, details["region"]) assert.Equal(t, worker.Context.Config.ReplicationBucket, details["bucket"]) // Bogus storage - should cause error gf.StorageOption = "ThumbDrive" details, err = worker.GetRequestDetails(gf) require.NotNil(t, err) require.Nil(t, details) } func TestGetRequestRecord(t *testing.T) { worker, state := getTestComponents(t, "file") require.Nil(t, state.GenericFile) state, err := worker.GetGlacierRestoreState(state.NSQMessage, state.WorkItem) require.Nil(t, err) require.NotNil(t, state) require.Nil(t, state.GenericFile) gf, err := worker.GetGenericFile(state) assert.Nil(t, err) require.NotNil(t, gf) assert.NotEmpty(t, gf.Identifier) gf.StorageOption = constants.StorageGlacierOH details, err := worker.GetRequestDetails(gf) require.Nil(t, err) require.NotNil(t, details) fileUUID, err := gf.PreservationStorageFileName() require.Nil(t, err) // Should create a new request with correct information glacierRestoreRequest := worker.GetRequestRecord(state, gf, details) assert.Equal(t, gf.Identifier, glacierRestoreRequest.GenericFileIdentifier) assert.Equal(t, worker.Context.Config.GlacierBucketOH, glacierRestoreRequest.GlacierBucket) assert.Equal(t, fileUUID, glacierRestoreRequest.GlacierKey) assert.False(t, glacierRestoreRequest.RequestAccepted) assert.True(t, glacierRestoreRequest.RequestedAt.IsZero()) // Should retrieve an exising request. gf = testutil.MakeGenericFile(0, 0, "test.edu/bag-of-glass") request := &models.GlacierRestoreRequest{ GenericFileIdentifier: gf.Identifier, GlacierBucket: "6-piece fried chicken bucket", GlacierKey: "extra crispy", RequestAccepted: true, SomeoneElseRequested: true, } state.Requests = append(state.Requests, request) glacierRestoreRequest = worker.GetRequestRecord(state, gf, details) assert.Equal(t, request.GenericFileIdentifier, glacierRestoreRequest.GenericFileIdentifier) assert.Equal(t, request.GlacierBucket, glacierRestoreRequest.GlacierBucket) assert.Equal(t, request.GlacierKey, glacierRestoreRequest.GlacierKey) assert.Equal(t, request.RequestAccepted, glacierRestoreRequest.RequestAccepted) assert.Equal(t, request.SomeoneElseRequested, glacierRestoreRequest.SomeoneElseRequested) } func TestInitializeRetrieval(t *testing.T) { worker, state := getTestComponents(t, "file") require.Nil(t, state.GenericFile) state, err := worker.GetGlacierRestoreState(state.NSQMessage, state.WorkItem) require.Nil(t, err) require.NotNil(t, state) require.Nil(t, state.GenericFile) gf, err := worker.GetGenericFile(state) assert.Nil(t, err) require.NotNil(t, gf) assert.NotEmpty(t, gf.Identifier) assert.NotEmpty(t, gf.StorageOption) assert.NotEmpty(t, gf.URI) details, err := worker.GetRequestDetails(gf) require.Nil(t, err) require.NotNil(t, details) glacierRestoreRequest := worker.GetRequestRecord(state, gf, details) assert.False(t, glacierRestoreRequest.RequestAccepted) assert.True(t, glacierRestoreRequest.RequestedAt.IsZero()) // Set our S3 mock responder to accept a Glacier restore request, // and then test InitializeRetrieval to ensure it sets // properties correctly for an accepted request. DescribeRestoreStateAs = NotStartedAcceptNow worker.InitializeRetrieval(state, gf, details, glacierRestoreRequest) assert.Empty(t, state.WorkSummary.Errors) assert.True(t, glacierRestoreRequest.RequestAccepted) assert.False(t, glacierRestoreRequest.RequestedAt.IsZero()) // Reset these properties... glacierRestoreRequest.RequestAccepted = false glacierRestoreRequest.RequestedAt = time.Time{} // And then make sure InitializeRetrieval sets them correctly // on a restore that's already in progress. DescribeRestoreStateAs = InProgressGlacier worker.InitializeRetrieval(state, gf, details, glacierRestoreRequest) assert.Empty(t, state.WorkSummary.Errors) assert.True(t, glacierRestoreRequest.RequestAccepted) assert.False(t, glacierRestoreRequest.RequestedAt.IsZero()) } // ------------------------------------------------------------------------- // End-to-end tests // ------------------------------------------------------------------------- // --- The following test cannot run with our current setup, // --- due to conflicting calls to describe restore state. // func TestGlacierNotStarted(t *testing.T) { // NumberOfRequestsToIncludeInState = 0 // DescribeRestoreStateAs = NotStartedHead // worker, state := getTestComponents(t, "object") // //state.IntellectualObject = testutil.MakeIntellectualObject(12, 0, 0, 0) // delegate := testutil.NewNSQTestDelegate() // state.NSQMessage.Delegate = delegate // // Create a post-test channel to check the state of various // // items after they've gone through the entire workflow. // worker.PostTestChannel = make(chan *models.GlacierRestoreState) // var wg sync.WaitGroup // wg.Add(1) // go func() { // for state := range worker.PostTestChannel { // assert.Empty(t, state.WorkSummary.Errors) // assert.NotNil(t, state.IntellectualObject) // assert.Equal(t, 12, len(state.Requests)) // for _, req := range state.Requests { // assert.NotEmpty(t, req.GenericFileIdentifier) // assert.NotEmpty(t, req.GlacierBucket) // assert.NotEmpty(t, req.GlacierKey) // assert.False(t, req.RequestedAt.IsZero()) // assert.True(t, req.RequestAccepted) // assert.False(t, req.IsAvailableInS3) // } // assert.Equal(t, "requeue", delegate.Operation) // assert.Equal(t, 1*time.Minute, delegate.Delay) // assert.Equal(t, "Requeued to make additional Glacier restore requests.", state.WorkItem.Note) // assert.Equal(t, constants.StatusStarted, state.WorkItem.Status) // assert.True(t, state.WorkItem.Retry) // assert.False(t, state.WorkItem.NeedsAdminReview) // wg.Done() // } // }() // worker.RequestChannel <- state // wg.Wait() // } func TestGlacierAcceptNow(t *testing.T) { NumberOfRequestsToIncludeInState = 0 DescribeRestoreStateAs = NotStartedAcceptNow worker, state := getTestComponents(t, "object") state.IntellectualObject = testutil.MakeIntellectualObject(12, 0, 0, 0) delegate := testutil.NewNSQTestDelegate() state.NSQMessage.Delegate = delegate worker.PostTestChannel = make(chan *models.GlacierRestoreState) var wg sync.WaitGroup wg.Add(1) go func() { for state := range worker.PostTestChannel { assert.Empty(t, state.WorkSummary.Errors) assert.NotNil(t, state.IntellectualObject) assert.Equal(t, 12, len(state.Requests)) for _, req := range state.Requests { assert.NotEmpty(t, req.GenericFileIdentifier) assert.NotEmpty(t, req.GlacierBucket) assert.NotEmpty(t, req.GlacierKey) assert.False(t, req.RequestedAt.IsZero()) assert.True(t, req.RequestAccepted) assert.False(t, req.IsAvailableInS3) } assert.Equal(t, "requeue", delegate.Operation) assert.Equal(t, 2*time.Hour, delegate.Delay) assert.Equal(t, "Requeued to check on status of Glacier restore requests.", state.WorkItem.Note) assert.Equal(t, constants.StatusStarted, state.WorkItem.Status) assert.True(t, state.WorkItem.Retry) assert.False(t, state.WorkItem.NeedsAdminReview) wg.Done() } }() worker.RequestChannel <- state wg.Wait() } // --- Rejections cause problems in tests. // --- We'll have to come back to this one. // func TestGlacierRejectNow(t *testing.T) { // NumberOfRequestsToIncludeInState = 0 // DescribeRestoreStateAs = NotStartedRejectNow // worker, state := getTestComponents(t, "object") // state.IntellectualObject = testutil.MakeIntellectualObject(12, 0, 0, 0) // delegate := testutil.NewNSQTestDelegate() // state.NSQMessage.Delegate = delegate // worker.PostTestChannel = make(chan *models.GlacierRestoreState) // var wg sync.WaitGroup // wg.Add(1) // go func() { // for state := range worker.PostTestChannel { // assert.Empty(t, state.WorkSummary.Errors) // assert.NotNil(t, state.IntellectualObject) // assert.Equal(t, 12, len(state.Requests)) // for _, req := range state.Requests { // assert.NotEmpty(t, req.GenericFileIdentifier) // assert.NotEmpty(t, req.GlacierBucket) // assert.NotEmpty(t, req.GlacierKey) // assert.False(t, req.RequestedAt.IsZero()) // assert.True(t, req.RequestAccepted) // assert.False(t, req.IsAvailableInS3) // } // assert.Equal(t, "requeue", delegate.Operation) // assert.Equal(t, 1*time.Minute, delegate.Delay) // assert.Equal(t, "Requeued to make additional Glacier restore requests.", state.WorkItem.Note) // assert.Equal(t, constants.StatusStarted, state.WorkItem.Status) // assert.True(t, state.WorkItem.Retry) // assert.False(t, state.WorkItem.NeedsAdminReview) // wg.Done() // } // }() // worker.RequestChannel <- state // wg.Wait() // } func TestGlacierInProgressHead(t *testing.T) { NumberOfRequestsToIncludeInState = 0 DescribeRestoreStateAs = InProgressHead worker, state := getTestComponents(t, "object") state.IntellectualObject = testutil.MakeIntellectualObject(12, 0, 0, 0) delegate := testutil.NewNSQTestDelegate() state.NSQMessage.Delegate = delegate worker.PostTestChannel = make(chan *models.GlacierRestoreState) var wg sync.WaitGroup wg.Add(1) go func() { for state := range worker.PostTestChannel { assert.Empty(t, state.WorkSummary.Errors) assert.NotNil(t, state.IntellectualObject) assert.Equal(t, 12, len(state.Requests)) for _, req := range state.Requests { assert.NotEmpty(t, req.GenericFileIdentifier) assert.NotEmpty(t, req.GlacierBucket) assert.NotEmpty(t, req.GlacierKey) assert.False(t, req.RequestedAt.IsZero()) assert.True(t, req.RequestAccepted) assert.False(t, req.IsAvailableInS3) } assert.Equal(t, "requeue", delegate.Operation) assert.Equal(t, 2*time.Hour, delegate.Delay) assert.Equal(t, "Requeued to check on status of Glacier restore requests.", state.WorkItem.Note) assert.Equal(t, constants.StatusStarted, state.WorkItem.Status) assert.True(t, state.WorkItem.Retry) assert.False(t, state.WorkItem.NeedsAdminReview) wg.Done() } }() worker.RequestChannel <- state wg.Wait() } func TestGlacierInProgressGlacier(t *testing.T) { NumberOfRequestsToIncludeInState = 0 DescribeRestoreStateAs = InProgressGlacier worker, state := getTestComponents(t, "object") state.IntellectualObject = testutil.MakeIntellectualObject(12, 0, 0, 0) delegate := testutil.NewNSQTestDelegate() state.NSQMessage.Delegate = delegate worker.PostTestChannel = make(chan *models.GlacierRestoreState) var wg sync.WaitGroup wg.Add(1) go func() { for state := range worker.PostTestChannel { assert.Empty(t, state.WorkSummary.Errors) assert.NotNil(t, state.IntellectualObject) assert.Equal(t, 12, len(state.Requests)) for _, req := range state.Requests { assert.NotEmpty(t, req.GenericFileIdentifier) assert.NotEmpty(t, req.GlacierBucket) assert.NotEmpty(t, req.GlacierKey) assert.False(t, req.RequestedAt.IsZero()) assert.True(t, req.RequestAccepted) assert.False(t, req.IsAvailableInS3) } assert.Equal(t, "requeue", delegate.Operation) assert.Equal(t, 2*time.Hour, delegate.Delay) assert.Equal(t, "Requeued to check on status of Glacier restore requests.", state.WorkItem.Note) assert.Equal(t, constants.StatusStarted, state.WorkItem.Status) assert.True(t, state.WorkItem.Retry) assert.False(t, state.WorkItem.NeedsAdminReview) wg.Done() } }() worker.RequestChannel <- state wg.Wait() } func TestGlacierCompleted(t *testing.T) { NumberOfRequestsToIncludeInState = 0 DescribeRestoreStateAs = Completed createdWorkItem = &models.WorkItem{} worker, state := getTestComponents(t, "object") state.IntellectualObject = testutil.MakeIntellectualObject(12, 0, 0, 0) delegate := testutil.NewNSQTestDelegate() state.NSQMessage.Delegate = delegate worker.PostTestChannel = make(chan *models.GlacierRestoreState) var wg sync.WaitGroup wg.Add(1) go func() { for state := range worker.PostTestChannel { assert.Empty(t, state.WorkSummary.Errors) assert.NotNil(t, state.IntellectualObject) assert.Equal(t, 12, len(state.Requests)) for _, req := range state.Requests { assert.NotEmpty(t, req.GenericFileIdentifier) assert.NotEmpty(t, req.GlacierBucket) assert.NotEmpty(t, req.GlacierKey) assert.False(t, req.RequestedAt.IsZero()) assert.True(t, req.RequestAccepted) assert.True(t, req.IsAvailableInS3) } assert.Equal(t, "finish", delegate.Operation) assert.Equal(t, "All files have been moved from Glacier to S3. Created new WorkItem #0 to finish restoration.", state.WorkItem.Note) assert.Equal(t, constants.StatusSuccess, state.WorkItem.Status) assert.True(t, state.WorkItem.Retry) assert.False(t, state.WorkItem.NeedsAdminReview) // Make sure that after all items are successfully moved from // Glacier to S3, we create a normal Restore WorkItem, so // we can restore the bag from S3 to the depositor's restore // bucket. assert.Equal(t, state.WorkItem.ObjectIdentifier, createdWorkItem.ObjectIdentifier) assert.Equal(t, state.WorkItem.GenericFileIdentifier, createdWorkItem.GenericFileIdentifier) assert.Equal(t, state.WorkItem.Name, createdWorkItem.Name) assert.Equal(t, state.WorkItem.Bucket, createdWorkItem.Bucket) assert.Equal(t, state.WorkItem.ETag, createdWorkItem.ETag) assert.Equal(t, state.WorkItem.Size, createdWorkItem.Size) assert.Equal(t, state.WorkItem.BagDate, createdWorkItem.BagDate) assert.Equal(t, state.WorkItem.InstitutionId, createdWorkItem.InstitutionId) assert.Equal(t, state.WorkItem.User, createdWorkItem.User) assert.Equal(t, constants.ActionRestore, createdWorkItem.Action) assert.Equal(t, constants.StageRequested, createdWorkItem.Stage) assert.Equal(t, constants.StatusPending, createdWorkItem.Status) assert.True(t, createdWorkItem.Retry) wg.Done() } }() worker.RequestChannel <- state wg.Wait() } // ------------------------------------------------------------------------- // HTTP test handlers // ------------------------------------------------------------------------- func getRequestData(r *http.Request) (map[string]interface{}, error) { decoder := json.NewDecoder(r.Body) decoder.UseNumber() data := make(map[string]interface{}) err := decoder.Decode(&data) return data, err } func getIdFromUrl(url string) int { id := 1000 matches := URL_ID_REGEX.FindAllStringSubmatch(url, 1) if len(matches[0]) > 0 { id, _ = strconv.Atoi(matches[0][1]) } return id } func workItemGetHandler(w http.ResponseWriter, r *http.Request) { obj := testutil.MakeWorkItem() objJson, _ := json.Marshal(obj) w.Header().Set("Content-Type", "application/json") fmt.Fprintln(w, string(objJson)) } func institutionListHandler(w http.ResponseWriter, r *http.Request) { jsonData := `{ "count": 1, "next": null, "previous": "https://repo.aptrust.org/institutions?page=-1&per_page=0", "results": [{ "id": 8675309, "name": "Test University", "identifier": "test.edu", "receiving_bucket": "aptrust.receiving.test.test.edu", "restore_bucket": "aptrust.restore.test.test.edu" }] }` w.Header().Set("Content-Type", "application/json") fmt.Fprintln(w, jsonData) } // Simulate updating of WorkItem. Pharos returns the updated WorkItem, // so this mock can just return the JSON as-is, and then the test // code can check that to see whether the worker sent the right data // to Pharos. func workItemPutHandler(w http.ResponseWriter, r *http.Request) { defer r.Body.Close() body, err := ioutil.ReadAll(r.Body) if err != nil { fmt.Fprintln(w, err.Error()) return } _ = json.Unmarshal(body, updatedWorkItem) w.Header().Set("Content-Type", "application/json") fmt.Fprintln(w, string(body)) } func workItemPostHandler(w http.ResponseWriter, r *http.Request) { defer r.Body.Close() body, err := ioutil.ReadAll(r.Body) if err != nil { fmt.Fprintln(w, err.Error()) return } _ = json.Unmarshal(body, createdWorkItem) w.Header().Set("Content-Type", "application/json") fmt.Fprintln(w, string(body)) } func workItemStateGetHandler(w http.ResponseWriter, r *http.Request) { id := getIdFromUrl(r.URL.String()) obj := testutil.MakeWorkItemState() obj.WorkItemId = id obj.Action = constants.ActionGlacierRestore obj.State = "" state := &models.GlacierRestoreState{} state.WorkSummary = testutil.MakeWorkSummary() // Add some Glacier request records to this object, if necessary for i := 0; i < NumberOfRequestsToIncludeInState; i++ { fileIdentifier := fmt.Sprintf("test.edu/glacier_bag/file_%d.pdf", i+1) request := testutil.MakeGlacierRestoreRequest(fileIdentifier, true) state.Requests = append(state.Requests, request) } jsonBytes, err := json.Marshal(state) if err != nil { fmt.Fprintf(os.Stderr, "Error encoding JSON data: %v", err) fmt.Fprintln(w, err.Error()) return } obj.State = string(jsonBytes) objJson, _ := json.Marshal(obj) w.Header().Set("Content-Type", "application/json") fmt.Fprintln(w, string(objJson)) } // Send back the same JSON we received. func workItemStatePutHandler(w http.ResponseWriter, r *http.Request) { defer r.Body.Close() body, err := ioutil.ReadAll(r.Body) if err != nil { fmt.Fprintln(w, err.Error()) return } _ = json.Unmarshal(body, updatedWorkItemState) w.Header().Set("Content-Type", "application/json") fmt.Fprintln(w, string(body)) } func intellectualObjectGetHandler(w http.ResponseWriter, r *http.Request) { obj := testutil.MakeIntellectualObject(12, 0, 0, 0) obj.StorageOption = constants.StorageGlacierOH for i, gf := range obj.GenericFiles { gf.Identifier = fmt.Sprintf("%s/file_%d.txt", obj.Identifier, i) gf.StorageOption = constants.StorageGlacierOH } objJson, _ := json.Marshal(obj) w.Header().Set("Content-Type", "application/json") fmt.Fprintln(w, string(objJson)) } func genericFileGetHandler(w http.ResponseWriter, r *http.Request) { obj := testutil.MakeGenericFile(0, 2, "test.edu/glacier_bag") obj.StorageOption = constants.StorageGlacierOH objJson, _ := json.Marshal(obj) w.Header().Set("Content-Type", "application/json") fmt.Fprintln(w, string(objJson)) } // pharosHandler handles all requests that the GlacierRestoreInit // worker would send to Pharos. func pharosHandler(w http.ResponseWriter, r *http.Request) { url := r.URL.String() if strings.Contains(url, "/item_state/") { if r.Method == http.MethodGet { workItemStateGetHandler(w, r) } else { workItemStatePutHandler(w, r) } } else if strings.Contains(url, "/items/") { if r.Method == http.MethodGet { workItemGetHandler(w, r) } else if r.Method == http.MethodPut { workItemPutHandler(w, r) } else if r.Method == http.MethodPost { workItemPostHandler(w, r) } } else if strings.Contains(url, "/objects/") { intellectualObjectGetHandler(w, r) } else if strings.Contains(url, "/institutions/") { institutionListHandler(w, r) } else if strings.Contains(url, "/files/") { genericFileGetHandler(w, r) } else { panic(fmt.Sprintf("Don't know how to handle request for %s", url)) } } // s3Handler handles all the requests that the GlacierRestoreInit // worker would send to S3 (including requests to move Glacier objects // back into S3). func s3Handler(w http.ResponseWriter, r *http.Request) { if DescribeRestoreStateAs == NotStartedHead { // S3 HEAD handler will tell us this item is in Glacier, but not yet S3 network.S3HeadHandler(w, r) } else if DescribeRestoreStateAs == NotStartedAcceptNow { // Restore handler accepts a Glacier restore requests network.S3RestoreHandler(w, r) } else if DescribeRestoreStateAs == NotStartedRejectNow { // Reject handler reject a Glacier restore requests network.S3RestoreRejectHandler(w, r) } else if DescribeRestoreStateAs == InProgressHead { // This handler is an S3 call that tells us the Glacier restore // is in progress, but not yet complete. network.S3HeadRestoreInProgressHandler(w, r) } else if DescribeRestoreStateAs == InProgressGlacier { // This is a Glacier API call that tells us the restore is // in progress, but not yet complete. network.S3RestoreInProgressHandler(w, r) } else if DescribeRestoreStateAs == Completed { // This is an S3 API call, where the HEAD response includes // info saying the restore is complete and the item will be // available in S3 until a specific date/time. network.S3HeadRestoreCompletedHandler(w, r) } }
package utils import ( "fmt" "os" "sort" "strconv" "strings" ) const sourceCodeUrl = "https://github.com/mingchoi/LeetCode-Solution/blob/master/" const markdownReportHeader = `# LeetCode Solution Solutions are written in Golang or Java. Here are the result: (higher is better, max at 100) ` type Result struct { Id string RuntimeBeat float64 RuntimeMS float64 MemoryBeat float64 MemoryMB float64 Language string Path string } type ReportSummaryRow struct { Difficulty string Total int Runtime float64 Memory float64 } func (row ReportSummaryRow) ToMarkdownTitle() string { return "|difficulty|total|runtime beat(avg)|memory beat(avg)|\n|---|---|---|---|\n" } func (row ReportSummaryRow) ToMarkdown() string { return fmt.Sprintf("|%v|%v|%.2f|%.2f|\n", row.Difficulty, row.Total, row.Runtime, row.Memory) } type ReportResultRow struct { Id int Name string Difficulty string Runtime float64 Memory float64 Language string Path string } func (row ReportResultRow) ToMarkdownTitle() string { return "|id|title|difficulty|runtime beat|memory beat|lang/ code|\n|---|---|---|---|---|---|\n" } func (row ReportResultRow) ToMarkdown() string { return fmt.Sprintf("|%v|%v|%v|%.2f|%.2f|[%v](%v)|\n", row.Id, row.Name, row.Difficulty, row.Runtime, row.Memory, row.Language, sourceCodeUrl+row.Path) } func GenerateMarkdownReport(results []Result) { if len(leetCodeInMemDB) == 0 { createInMemLeetCodeQuestionDB() } reportStr := generateMarkdownReportString(results) err := os.WriteFile("README.md", []byte(reportStr), 0644) if err != nil { panic(err) } } func generateMarkdownReportString(results []Result) string { sum := map[string]ReportSummaryRow{ "Easy": {Difficulty: "Easy"}, "Medium": {Difficulty: "Medium"}, "Hard": {Difficulty: "Hard"}, } rows := make([]ReportResultRow, 0) // Collect data form results for _, r := range results { q, ok := leetCodeInMemDB[r.Id] if !ok { panic("question not found in leetcode in memory db") } // Add data to sum table sumRow := sum[q.Difficulty] sumRow.Total += 1 sumRow.Runtime += r.RuntimeBeat sumRow.Memory += r.MemoryBeat sum[q.Difficulty] = sumRow // Add record to result table id, err := strconv.Atoi(r.Id) if err != nil { panic(err) } row := ReportResultRow{ Id: id, Name: q.Title, Difficulty: q.Difficulty, Runtime: r.RuntimeBeat, Memory: r.MemoryBeat, Language: r.Language, Path: r.Path, } rows = append(rows, row) } // Update sum data totalRow := ReportSummaryRow{Difficulty: "Total"} for _, r := range sum { totalRow.Total += r.Total totalRow.Runtime += r.Runtime totalRow.Memory += r.Memory r.Runtime /= float64(r.Total) r.Memory /= float64(r.Total) sum[r.Difficulty] = r } totalRow.Runtime /= float64(totalRow.Total) totalRow.Memory /= float64(totalRow.Total) // sort results sort.Slice(rows, func(i, j int) bool { if rows[i].Id == rows[j].Id { return rows[i].Language == "Go" } return rows[i].Id < rows[j].Id }) // Build report builder := strings.Builder{} builder.WriteString(markdownReportHeader) builder.WriteString(ReportSummaryRow{}.ToMarkdownTitle()) builder.WriteString(sum["Easy"].ToMarkdown()) builder.WriteString(sum["Medium"].ToMarkdown()) builder.WriteString(sum["Hard"].ToMarkdown()) builder.WriteString(totalRow.ToMarkdown()) builder.WriteString("\n") builder.WriteString(ReportResultRow{}.ToMarkdownTitle()) for _, r := range rows { builder.WriteString(r.ToMarkdown()) } return builder.String() }
// program subscribes and listens to the nanomsg stream publiched by the Wasp host // and displays it in the console package main import ( "fmt" "github.com/iotaledger/wasp/packages/subscribe" "os" "os/signal" "strings" "sync" "syscall" ) func main() { if len(os.Args) != 2 { fmt.Printf("Usage: submsg <pub host>\n") os.Exit(1) } chMsg := make(chan []string) chDone := make(chan bool) fmt.Printf("dialing %s\n", os.Args[1]) err := subscribe.Subscribe(os.Args[1], chMsg, chDone, true, "") if err != nil { fmt.Printf("error: %v\n", err) os.Exit(1) } fmt.Printf("reading from %s\n", os.Args[1]) wg := &sync.WaitGroup{} wg.Add(1) go func() { defer wg.Done() for msgSplit := range chMsg { fmt.Printf("%s\n", strings.Join(msgSplit, " ")) } }() c := make(chan os.Signal) signal.Notify(c, os.Interrupt, syscall.SIGTERM) go func() { <-c fmt.Printf("interrupt received..\n") close(chDone) }() wg.Wait() }
package main import ( "bytes" "errors" "flag" "net" "net/http" "strings" "crypto/aes" "crypto/cipher" "encoding/base64" "encoding/json" "github.com/ssoor/socks" ) func Decrypt(base64Code []byte) (decode []byte, err error) { type encodeStruct struct { IV string `json:"iv"` Code string `json:"code"` } key := []byte("890161F37139989CFA9433BAF32BDAFB") var jsonEninfo []byte for i := 0; i < len(base64Code); i++ { base64Code[i] = base64Code[i] - 0x90 } if jsonEninfo, err = base64.StdEncoding.DecodeString(string(base64Code)); err != nil { return nil, err } eninfo := encodeStruct{} if err := json.Unmarshal(jsonEninfo, &eninfo); err != nil { return nil, err } var iv, code []byte iv, err = base64.StdEncoding.DecodeString(eninfo.IV) if err != nil { return nil, err } code, err = base64.StdEncoding.DecodeString(eninfo.Code) if err != nil { return nil, err } var block cipher.Block if block, err = aes.NewCipher(key); err != nil { return nil, err } mode := cipher.NewCBCDecrypter(block, iv) mode.CryptBlocks(code, code) return code, nil } func GetValidByte(src []byte) []byte { var str_buf []byte for _, v := range src { if v != 0 { str_buf = append(str_buf, v) } } return str_buf } func getSRules(srcurl string) (jsonRules []byte, err error) { resp, err := http.Get(srcurl) if nil != err { return nil, err } defer resp.Body.Close() var bodyBuf bytes.Buffer bodyBuf.ReadFrom(resp.Body) jsonRules, err = Decrypt(bodyBuf.Bytes()) if err != nil { return nil, err } return GetValidByte(jsonRules), nil } func main() { var isEncode bool var configFile string var userGUID string flag.BoolVar(&isEncode, "encode", true, "is start httpproxy encode to packets") flag.StringVar(&userGUID, "guid", "00000000_00000000", "is socksd start guid") flag.StringVar(&configFile, "config", "socksd.json", "socksd start config info file path") flag.Parse() conf, err := LoadConfig(configFile) if err != nil { InfoLog.Printf("Load config: %s failed, err: %s\n", configFile, err) return } InfoLog.Printf("Load config: %s succeeded\n", configFile) srules, err := getSRules("http://120.26.80.61/issued/rules/20160308/" + userGUID + ".rules") if err != nil { InfoLog.Printf("Load srules: %s failed, err: %s\n", "http://angels.lingpao8.com/"+userGUID, err) return } InfoLog.Printf("Load srules: %s succeeded\n", "http://angels.lingpao8.com/"+userGUID) for _, c := range conf.Proxies { router := BuildUpstreamRouter(c) if isEncode { runHTTPEncodeProxyServer(c, router, srules) } else { runHTTPProxyServer(c, router, srules) } runSOCKS4Server(c, router) runSOCKS5Server(c, router) } /* sigChan := make(chan os.Signal, 1) signal.Notify(sigChan, os.Kill, os.Interrupt) <-sigChan */ runPACServer(conf.PAC) } func BuildUpstream(upstream Upstream, forward socks.Dialer) (socks.Dialer, error) { cipherDecorator := NewCipherConnDecorator(upstream.Crypto, upstream.Password) forward = NewDecorateClient(forward, cipherDecorator) switch strings.ToLower(upstream.Type) { case "socks5": { return socks.NewSocks5Client("tcp", upstream.Address, "", "", forward) } case "shadowsocks": { return socks.NewShadowSocksClient("tcp", upstream.Address, forward) } } return nil, errors.New("unknown upstream type" + upstream.Type) } func BuildUpstreamRouter(conf Proxy) socks.Dialer { var allForward []socks.Dialer for _, upstream := range conf.Upstreams { var forward socks.Dialer var err error forward = NewDecorateDirect(conf.DNSCacheTimeout) forward, err = BuildUpstream(upstream, forward) if err != nil { ErrLog.Println("failed to BuildUpstream, err:", err) continue } allForward = append(allForward, forward) } if len(allForward) == 0 { router := NewDecorateDirect(conf.DNSCacheTimeout) allForward = append(allForward, router) } return NewUpstreamDialer(allForward) } func runHTTPProxyServer(conf Proxy, router socks.Dialer, data []byte) { if conf.HTTP != "" { listener, err := net.Listen("tcp", conf.HTTP) if err != nil { ErrLog.Println("net.Listen at ", conf.HTTP, " failed, err:", err) return } go func() { defer listener.Close() httpProxy := socks.NewHTTPProxy(router, socks.NewHTTPTransport(router,data)) http.Serve(listener, httpProxy) }() } } func runHTTPEncodeProxyServer(conf Proxy, router socks.Dialer, data []byte) { if conf.HTTP != "" { listener, err := net.Listen("tcp", conf.HTTP) if err != nil { ErrLog.Println("net.Listen at ", conf.HTTP, " failed, err:", err) return } listener = socks.NewHTTPEncodeListener(listener) go func() { defer listener.Close() httpProxy := socks.NewHTTPProxy(router, socks.NewHTTPTransport(router,data)) http.Serve(listener, httpProxy) }() } } func runSOCKS4Server(conf Proxy, forward socks.Dialer) { if conf.SOCKS4 != "" { listener, err := net.Listen("tcp", conf.SOCKS4) if err != nil { ErrLog.Println("net.Listen failed, err:", err, conf.SOCKS4) return } cipherDecorator := NewCipherConnDecorator(conf.Crypto, conf.Password) listener = NewDecorateListener(listener, cipherDecorator) socks4Svr, err := socks.NewSocks4Server(forward) if err != nil { listener.Close() ErrLog.Println("socks.NewSocks4Server failed, err:", err) } go func() { defer listener.Close() socks4Svr.Serve(listener) }() } } func runSOCKS5Server(conf Proxy, forward socks.Dialer) { if conf.SOCKS5 != "" { listener, err := net.Listen("tcp", conf.SOCKS5) if err != nil { ErrLog.Println("net.Listen failed, err:", err, conf.SOCKS5) return } cipherDecorator := NewCipherConnDecorator(conf.Crypto, conf.Password) listener = NewDecorateListener(listener, cipherDecorator) socks5Svr, err := socks.NewSocks5Server(forward) if err != nil { listener.Close() ErrLog.Println("socks.NewSocks5Server failed, err:", err) return } go func() { defer listener.Close() socks5Svr.Serve(listener) }() } } func runPACServer(pac PAC) { pu, err := NewPACUpdater(pac) if err != nil { ErrLog.Println("failed to NewPACUpdater, err:", err) return } http.HandleFunc("/proxy.pac", func(w http.ResponseWriter, r *http.Request) { w.Header().Add("Content-Type", "application/x-ns-proxy-autoconfig") data, time := pu.get() reader := bytes.NewReader(data) http.ServeContent(w, r, "proxy.pac", time, reader) }) err = http.ListenAndServe(pac.Address, nil) if err != nil { ErrLog.Println("listen failed, err:", err) return } }
package model type DashWebmRepresentation struct { // Id of the resource Id string `json:"id,omitempty"` // UUID of an encoding EncodingId string `json:"encodingId,omitempty"` // UUID of a muxing MuxingId string `json:"muxingId,omitempty"` Type DashRepresentationType `json:"type,omitempty"` Mode DashRepresentationTypeMode `json:"mode,omitempty"` // Path to segments. Will be used as the representation id if the type is set to TEMPLATE_ADAPTATION_SET SegmentPath string `json:"segmentPath,omitempty"` // Number of the first segment StartSegmentNumber *int64 `json:"startSegmentNumber,omitempty"` // Number of the last segment. Default is the last one that was encoded EndSegmentNumber *int64 `json:"endSegmentNumber,omitempty"` // Id of the Keyframe to start with StartKeyframeId string `json:"startKeyframeId,omitempty"` // Id of the Keyframe to end with EndKeyframeId string `json:"endKeyframeId,omitempty"` }
package server import ( "api/entities" "api/utils" routing "github.com/qiangxue/fasthttp-routing" ) // GetCurrentUser ... func (s *Server) GetCurrentUser() routing.Handler { return func(c *routing.Context) error { user, ok := c.Get("user").(*entities.User) if !ok { return utils.Respond(c, 401, map[string]interface{}{ "error": "Authentication credentials were not provided", }) } return utils.Respond(c, 200, user) } } // GetAllUsers ... func (s *Server) GetAllUsers() routing.Handler { return func(c *routing.Context) error { users, err := s.db.User().GetAll() if err != nil { return utils.Respond(c, 400, map[string]interface{}{ "error": err.Error(), }) } return utils.Respond(c, 200, users) } }
package baikal type MinerStats struct { Devs []SGDev Pools []SGPool Stats []SGStat Summary SGSummary System MinerStatsSystem } type MinerStatsSystem struct { TempCPU string }
/* Every package should have a package comment, a block comment preceding the package clause. For multi-file packages, the package comment only needs to be present in one file, and any one will do. The package comment should introduce the package and provide information relevant to the package as a whole. It will appear first on the godoc page and should set up the detailed documentation that follows. */ package cookie import ( "encoding/base64" "encoding/json" "errors" "github.com/MerinEREN/iiPackages/crypto" "github.com/MerinEREN/iiPackages/session" "log" "net/http" "strings" ) // Cookie error variables var ( ErrCorruptedCookie = errors.New("Cookie data corrupted") ) // CHANGE THIS DUMMY COOKIE STRUCT !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! type SessionData struct { Photo string } // Adding uuid and hash to the cookie and check hash code func Set(s *session.Session, name, value string) error { // COOKIE IS A PART OF THE HEADER, SO U SHOULD SET THE COOKIE BEFORE EXECUTING A // TEMPLATE OR WRITING SOMETHING TO THE BODY !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! c, err := s.R.Cookie(name) if err == http.ErrNoCookie { c, err = create(name, value) http.SetCookie(s.W, c) } else { if isUserDataChanged(c) { // DELETING CORRUPTED COOKIE AND CREATING NEW ONE !!!!!!!!!!!!!!!!! Delete(s, name) c, _ = create(name, value) http.SetCookie(s.W, c) err = ErrCorruptedCookie } } return err } func create(n, v string) (c *http.Cookie, err error) { c = &http.Cookie{ Name: n, // U CAN USE UUID AS VALUE !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! Value: v, // NOT GOOD PRACTICE // ADDING USER DATA TO A COOKIE // WITH NO WAY OF KNOWING WHETER OR NOT THEY MIGHT HAVE ALTERED // THAT DATA !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! // HMAC WOULD ALLOW US TO DETERMINE WHETHER OR NOT THE DATA IN THE // COOKIE WAS ALTERED !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! // HOWEVER, BEST TO STORE USER DATA ON THE SERVER AND KEEP // BACKUPS !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! // Value: "emil = merin@inceis.net" + "JSON data" + "whatever", // IF SECURE IS TRUE THIS COOKIE ONLY SEND WITH HTTP2 !!!!!!!!!!!!!!!!!!!!! // Secure: true, // HttpOnly: true MEANS JAVASCRIPT CAN NOT ACCESS THE COOKIE !!!!!!!!!!!!!! HttpOnly: false, } err = setValue(c) return } func Delete(s *session.Session, n string) error { c, err := s.R.Cookie(n) if err == http.ErrNoCookie { return err } c.MaxAge = -1 // If path is different can't delete cookie without cookie's path. // Maybe should use cookie path even paths are same. c.Path = s.R.URL.Path http.SetCookie(s.W, c) return err } // Setting different kind of struct for different cookies func setValue(c *http.Cookie) (err error) { var cd interface{} if strings.Contains(c.Name, "/") { cd = SessionData{ Photo: "img/MKA.jpg", } } var bs []byte bs, err = json.Marshal(cd) if err != nil { return } c.Value += "|" + base64.StdEncoding.EncodeToString(bs) code, err := crypto.GetMAC(c.Value) if err != nil { return } c.Value += "|" + code return } func isUserDataChanged(c *http.Cookie) bool { cvSlice := strings.Split(c.Value, "|") uuidData := cvSlice[0] + "|" + cvSlice[1] if !crypto.CheckMAC(uuidData, cvSlice[2]) { log.Printf("%s cookie value is corrupted.", c.Name) return true } return false } // MAKE GENERIC RETURN TYPE !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! func GetData(s session.Session, n string) (*SessionData, error) { c, err := s.R.Cookie(n) if err == http.ErrNoCookie { return &SessionData{}, err } cvSlice := strings.Split(c.Value, "|") return decodeThanUnmarshall(cvSlice[1]), nil } // MAKE GENERIC RETURN TYPE !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! func decodeThanUnmarshall(cd string) *SessionData { decodedBase64, err := base64.StdEncoding.DecodeString(cd) if err != nil { log.Printf("Error while decoding cookie data. Error is %v\n", err) } var cookieData SessionData err = json.Unmarshal(decodedBase64, &cookieData) if err != nil { log.Printf("Cookie data unmarshaling error. %v\n", err) } return &cookieData }
package repository import ( "fmt" "github.com/jinzhu/gorm" "log" "time" ) type ExchangeRateData struct { ID int64 ExchangeRateID int64 Rate float64 ValidTime time.Time } type RateDataRepositoryItf interface { InsertDailyExchangeRateData(*ExchangeRate, *ExchangeRateData) error GetExchangeRateDataByExchangeRateIDAndDate(*ExchangeRateData) *ExchangeRateData GetSevenSpecificExchangeRateData(*ExchangeRate) []ExchangeRateData GetSevenDaysAverageExchangeRateDataByExchangeRateIDAndDate(*ExchangeRateData) (float64, error) } type RateDataRepository struct { DB *gorm.DB } func (rd RateDataRepository) InsertDailyExchangeRateData(rate *ExchangeRate, data *ExchangeRateData) error { result := rd.DB.Exec("INSERT INTO exchange_rate_datas (exchange_rate_id, rate, valid_time) "+ "VALUES (?, ?, ?) "+ "ON CONFLICT (exchange_rate_id, valid_time) "+ "DO UPDATE"+ " SET rate = EXCLUDED.rate", rate.ID, data.Rate, data.ValidTime) if result.Error != nil { log.Printf("[RateDataRepository - InsertDailyExchangeRateData] : %s", result.Error) return result.Error } return nil } func (rd RateDataRepository) GetExchangeRateDataByExchangeRateIDAndDate(data *ExchangeRateData) *ExchangeRateData { result := rd.DB.Table("exchange_rate_datas"). Where("exchange_rate_id = ? AND valid_time = ?", data.ExchangeRateID, data.ValidTime).Find(&data) if result.Error != nil { log.Printf("[RateDataRepository - GetExchangeRateDataByExchangeRateIDAndDate] : %s", result.Error) return nil } return data } func (rd RateDataRepository) GetSevenSpecificExchangeRateData(rate *ExchangeRate) []ExchangeRateData { var rateDataList []ExchangeRateData result := rd.DB.Raw("SELECT * "+ "FROM exchange_rate_datas WHERE exchange_rate_id = ?"+ "ORDER BY valid_time DESC LIMIT 7", rate.ID).Scan(&rateDataList) if result.Error != nil { log.Printf("[RateDataRepository - GetSevenSpecificExchangeRateData] : %s", result.Error) return nil } return rateDataList } func (rd RateDataRepository) GetSevenDaysAverageExchangeRateDataByExchangeRateIDAndDate(data *ExchangeRateData) (float64, error) { var averageRate float64 date := data.ValidTime.Format("2006-01-02") queryStmt := fmt.Sprintf("SELECT (CASE WHEN COUNT(*) < 7 THEN 0 ELSE AVG(rate) END) AS average "+ "FROM exchange_rate_datas "+ "WHERE "+ " exchange_rate_id = %d AND "+ " valid_time BETWEEN (DATE '%s' - interval '6 days') AND (DATE '%s')", data.ExchangeRateID, date, date) result := rd.DB.Raw(queryStmt).Row() err := result.Scan(&averageRate) if err != nil { log.Printf("[RateDataRepository - GetSevenDaysAverageExchangeRateDataByExchangeRateIDAndDate] : %s", err) return 0, err } return averageRate, nil }
package core import ( "strings" "time" ) type dbType string type Uri struct { DbType dbType Proto string Host string Port string DbName string User string Passwd string Charset string Laddr string Raddr string Timeout time.Duration } // a dialect is a driver's wrapper type Dialect interface { Init(*Uri, string, string) error URI() *Uri DBType() dbType SqlType(t *Column) string SupportInsertMany() bool QuoteStr() string AutoIncrStr() string SupportEngine() bool SupportCharset() bool IndexOnTable() bool IndexCheckSql(tableName, idxName string) (string, []interface{}) TableCheckSql(tableName string) (string, []interface{}) ColumnCheckSql(tableName, colName string) (string, []interface{}) GetColumns(tableName string) ([]string, map[string]*Column, error) GetTables() ([]*Table, error) GetIndexes(tableName string) (map[string]*Index, error) CreateTableSql(table *Table, tableName, storeEngine, charset string) string Filters() []Filter DriverName() string DataSourceName() string } type Base struct { dialect Dialect driverName string dataSourceName string *Uri } func (b *Base) Init(dialect Dialect, uri *Uri, drivername, dataSourceName string) error { b.dialect = dialect b.driverName, b.dataSourceName = drivername, dataSourceName b.Uri = uri return nil } func (b *Base) URI() *Uri { return b.Uri } func (b *Base) DBType() dbType { return b.Uri.DbType } func (b *Base) DriverName() string { return b.driverName } func (b *Base) DataSourceName() string { return b.dataSourceName } func (b *Base) Quote(c string) string { return b.dialect.QuoteStr() + c + b.dialect.QuoteStr() } func (b *Base) CreateTableSql(table *Table, tableName, storeEngine, charset string) string { var sql string sql = "CREATE TABLE IF NOT EXISTS " if tableName == "" { tableName = table.Name } sql += b.Quote(tableName) + " (" pkList := table.PrimaryKeys for _, colName := range table.ColumnsSeq() { col := table.GetColumn(colName) if col.IsPrimaryKey && len(pkList) == 1 { sql += col.String(b.dialect) } else { sql += col.StringNoPk(b.dialect) } sql = strings.TrimSpace(sql) sql += ", " } if len(pkList) > 1 { sql += "PRIMARY KEY ( " sql += b.Quote(strings.Join(pkList, b.Quote(","))) sql += " ), " } sql = sql[:len(sql)-2] + ")" if b.dialect.SupportEngine() && storeEngine != "" { sql += " ENGINE=" + storeEngine } if b.dialect.SupportCharset() { if charset == "" { charset = b.dialect.URI().Charset } sql += " DEFAULT CHARSET " + charset } sql += ";" return sql } var ( dialects = map[dbType]Dialect{} ) func RegisterDialect(dbName dbType, dialect Dialect) { if dialect == nil { panic("core: Register dialect is nil") } if _, dup := dialects[dbName]; dup { panic("core: Register called twice for dialect " + dbName) } dialects[dbName] = dialect } func QueryDialect(dbName dbType) Dialect { return dialects[dbName] }
package fateRPGtest import ( "testing" "github.com/faterpg" ) func TestNewConsequence(t *testing.T) { var con *faterpg.Consequence con = faterpg.NewConsequence() if con == nil { t.Error("NewConsequence return nil") } } func TestConsequenceAttr(t *testing.T) { con := faterpg.NewConsequence() con.Name = "Test name" con.Description = "Test description" }
package main import ( "fmt" "os" cli "gx/ipfs/QmckeQ2zrYLAXoSHYTGn5BDdb22BqbUoHEHm8KZ9YWRxd1/iptb/cli" testbed "gx/ipfs/QmckeQ2zrYLAXoSHYTGn5BDdb22BqbUoHEHm8KZ9YWRxd1/iptb/testbed" browser "gx/ipfs/QmXZuSpcGSesFXDWwZnESp2YEcYNcR4em9P86XsZtcuzWR/iptb-plugins/browser" docker "gx/ipfs/QmXZuSpcGSesFXDWwZnESp2YEcYNcR4em9P86XsZtcuzWR/iptb-plugins/docker" local "gx/ipfs/QmXZuSpcGSesFXDWwZnESp2YEcYNcR4em9P86XsZtcuzWR/iptb-plugins/local" localp2pd "gx/ipfs/QmXZuSpcGSesFXDWwZnESp2YEcYNcR4em9P86XsZtcuzWR/iptb-plugins/localp2pd" ) func init() { _, err := testbed.RegisterPlugin(testbed.IptbPlugin{ From: "<builtin>", NewNode: local.NewNode, GetAttrList: local.GetAttrList, GetAttrDesc: local.GetAttrDesc, PluginName: local.PluginName, BuiltIn: true, }, false) if err != nil { panic(err) } _, err = testbed.RegisterPlugin(testbed.IptbPlugin{ From: "<builtin>", NewNode: localp2pd.NewNode, GetAttrList: localp2pd.GetAttrList, GetAttrDesc: localp2pd.GetAttrDesc, PluginName: localp2pd.PluginName, BuiltIn: true, }, false) if err != nil { panic(err) } _, err = testbed.RegisterPlugin(testbed.IptbPlugin{ From: "<builtin>", NewNode: docker.NewNode, GetAttrList: docker.GetAttrList, GetAttrDesc: docker.GetAttrDesc, PluginName: docker.PluginName, BuiltIn: true, }, false) if err != nil { panic(err) } _, err = testbed.RegisterPlugin(testbed.IptbPlugin{ From: "<builtin>", NewNode: browser.NewNode, PluginName: browser.PluginName, BuiltIn: true, }, false) if err != nil { panic(err) } } func main() { cli := cli.NewCli() if err := cli.Run(os.Args); err != nil { fmt.Fprintf(cli.ErrWriter, "%s\n", err) os.Exit(1) } }
package map_test import ( "fmt" ) func ExampleArray() { a := [3]int{1, 2, 3} b := [10]int{1, 2, 3} c := [...]int{1, 2, 3} fmt.Println(a) fmt.Println(b) fmt.Println(c) // Output: // [1 2 3] // [1 2 3 0 0 0 0 0 0 0] // [1 2 3] } func ExampleSlice() { s1 := []int{1, 2, 3} s2 := make([]int, 3) fmt.Println(s1) fmt.Println(s2) // Output: // [1 2 3] // [0 0 0] } func ExampleMap() { m1 := make(map[string]int) m1["one"] = 1 fmt.Println(m1) delete(m1, "one") // Output: // map[one:1] }
package kubeconfig import ( "encoding/base64" "net/http" "os" "strings" "time" "github.com/pkg/errors" "k8s.io/client-go/plugin/pkg/client/auth/exec" restclient "k8s.io/client-go/rest" "k8s.io/client-go/tools/clientcmd" "k8s.io/client-go/transport" ) const ( BasicAuthScheme = "Basic" BearerAuthScheme = "Bearer" ) // get the default one from the filesystem func DefaultRestConfig() (*restclient.Config, error) { rules := clientcmd.NewDefaultClientConfigLoadingRules() config := clientcmd.NewNonInteractiveDeferredLoadingClientConfig(rules, &clientcmd.ConfigOverrides{}) return config.ClientConfig() } func IsBasicAuthScheme(token string) bool { return strings.HasPrefix(token, BasicAuthScheme) } func IsBearerAuthScheme(token string) bool { return strings.HasPrefix(token, BearerAuthScheme) } func GetRestConfig(token string) (*restclient.Config, error) { if IsBasicAuthScheme(token) { token = strings.TrimSpace(strings.TrimPrefix(token, BasicAuthScheme)) username, password, ok := decodeBasicAuthToken(token) if !ok { return nil, errors.New("Error parsing Basic Authentication") } return GetBasicRestConfig(username, password) } if IsBearerAuthScheme(token) { token = strings.TrimSpace(strings.TrimPrefix(token, BearerAuthScheme)) return GetBearerRestConfig(token) } return nil, errors.New("Unsupported authentication scheme") } // convert a basic token (username, password) into a REST config func GetBasicRestConfig(username, password string) (*restclient.Config, error) { restConfig, err := DefaultRestConfig() if err != nil { return nil, err } restConfig.BearerToken = "" restConfig.BearerTokenFile = "" restConfig.Username = username restConfig.Password = password return restConfig, nil } // convert a bearer token into a REST config func GetBearerRestConfig(token string) (*restclient.Config, error) { restConfig, err := DefaultRestConfig() if err != nil { return nil, err } restConfig.BearerToken = "" restConfig.BearerTokenFile = "" restConfig.Username = "" restConfig.Password = "" if token != "" { restConfig.BearerToken = token } return restConfig, nil } //Return the AuthString include Auth type(Basic or Bearer) func GetAuthString(in *restclient.Config, explicitKubeConfigPath string) (string, error) { //Checking Basic Auth if in.Username != "" { token, err := GetBasicAuthToken(in) return BasicAuthScheme + " " + token, err } token, err := GetBearerToken(in, explicitKubeConfigPath) return BearerAuthScheme + " " + token, err } func GetBasicAuthToken(in *restclient.Config) (string, error) { if in == nil { return "", errors.Errorf("RestClient can't be nil") } return encodeBasicAuthToken(in.Username, in.Password), nil } // convert the REST config into a bearer token func GetBearerToken(in *restclient.Config, explicitKubeConfigPath string) (string, error) { if len(in.BearerToken) > 0 { return in.BearerToken, nil } if in == nil { return "", errors.Errorf("RestClient can't be nil") } if in.ExecProvider != nil { tc, err := in.TransportConfig() if err != nil { return "", err } auth, err := exec.GetAuthenticator(in.ExecProvider) if err != nil { return "", err } //This function will return error because of TLS Cert missing, // This code is not making actual request. We can ignore it. _ = auth.UpdateTransportConfig(tc) rt, err := transport.New(tc) if err != nil { return "", err } req := http.Request{Header: map[string][]string{}} _, _ = rt.RoundTrip(&req) token := req.Header.Get("Authorization") return strings.TrimPrefix(token, "Bearer "), nil } if in.AuthProvider != nil { if in.AuthProvider.Name == "gcp" { token := in.AuthProvider.Config["access-token"] token, err := RefreshTokenIfExpired(in, explicitKubeConfigPath, token) if err != nil { return "", err } return strings.TrimPrefix(token, "Bearer "), nil } } return "", errors.Errorf("could not find a token") } func encodeBasicAuthToken(username, password string) string { auth := username + ":" + password return base64.StdEncoding.EncodeToString([]byte(auth)) } func decodeBasicAuthToken(auth string) (username, password string, ok bool) { c, err := base64.StdEncoding.DecodeString(auth) if err != nil { return } cs := string(c) s := strings.IndexByte(cs, ':') if s < 0 { return } return cs[:s], cs[s+1:], true } func ReloadKubeConfig(explicitPath string) clientcmd.ClientConfig { loadingRules := clientcmd.NewDefaultClientConfigLoadingRules() loadingRules.DefaultClientConfig = &clientcmd.DefaultClientConfig loadingRules.ExplicitPath = explicitPath overrides := clientcmd.ConfigOverrides{} return clientcmd.NewInteractiveDeferredLoadingClientConfig(loadingRules, &overrides, os.Stdin) } func RefreshTokenIfExpired(restConfig *restclient.Config, explicitPath, curentToken string) (string, error) { if restConfig.AuthProvider != nil { timestr := restConfig.AuthProvider.Config["expiry"] if timestr != "" { t, err := time.Parse(time.RFC3339, timestr) if err != nil { return "", errors.Errorf("Invalid expiry date in Kubeconfig. %v", err) } if time.Now().After(t) { err = RefreshAuthToken(restConfig) if err != nil { return "", err } config := ReloadKubeConfig(explicitPath) restConfig, err = config.ClientConfig() if err != nil { return "", err } return restConfig.AuthProvider.Config["access-token"], nil } } } return curentToken, nil } func RefreshAuthToken(in *restclient.Config) error { tc, err := in.TransportConfig() if err != nil { return err } auth, err := restclient.GetAuthProvider(in.Host, in.AuthProvider, in.AuthConfigPersister) if err != nil { return err } rt, err := transport.New(tc) if err != nil { return err } rt = auth.WrapTransport(rt) req := http.Request{Header: map[string][]string{}} _, _ = rt.RoundTrip(&req) return nil }
package retry import "fmt" func StopRetryWithError(err error) error { if err == nil { return nil } return stopRetryError{originError: err} } type stopRetryError struct { originError error } func (err stopRetryError) Error() string { return fmt.Sprintf("stop retry with error: %s", err.originError) }
package main import "fmt" type A interface { Yuwen() } type B interface { English() } type nil interface { // 空接口可以被任何类型都实现,所以可以把任意变量都赋给他~ } type exams interface { // 要想继承A和B的接口~ 那么就需要全部实现A和B中的所有方法~~~ A B score() } type student struct { } func (stu student) Yuwen() { fmt.Println("参加语文考试中~~~~") } func (stu student) English() { fmt.Println("参加英语考试中~~~~") } func (stu student) score() { fmt.Println("得分为~~~~") } func main() { var stu student var a A = stu // 证实A被完全实现 var b B = stu // 证实B被完全实现 var exam exams = stu // 证实exam中完全继承了A和B 被完全实现 a.Yuwen() b.English() exam.Yuwen() exam.English() exam.score() // 如何使用空接口~ var num1 float64 = 10.01 var N nil = num1 fmt.Println(N) }
package runtime import ( "fmt" "sync" ) type waitQueue struct { lock sync.Mutex queue []*GoRoutine } func NewWaitQueue() *waitQueue { return &waitQueue{ queue: make([]*GoRoutine, 0), } } func (q *waitQueue) add(g *GoRoutine) { q.lock.Lock() defer q.lock.Unlock() g.Block() fmt.Printf("[Block Queue] Goroutine ID :%v is add to block queue now\n", g.ID) q.queue = append(q.queue, g) } func (q *waitQueue) get() (*GoRoutine, error) { q.lock.Lock() defer q.lock.Unlock() if q.isEmpty() { return nil, EmptyQueue } g := q.queue[0] q.queue = q.queue[1:len(q.queue)] fmt.Printf("[Block Queue] Get Goroutine ID :%v from block queue now\n", g.ID) return g, nil } func (q *waitQueue) isEmpty() bool { return q.size() == 0 } func (q *waitQueue) size() int { return len(q.queue) }
package goSolution /** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */ func sortedArrayToBST(nums []int) *TreeNode { if len(nums) == 0 { return nil } if len(nums) == 1 { return &TreeNode{Val: nums[0]} } l, r := 0, len(nums) mid := (l + r) >> 1 return &TreeNode{Val: nums[mid], Left: sortedArrayToBST(nums[0:mid]), Right: sortedArrayToBST(nums[mid+1:])} }
package historian import ( "bytes" "errors" "time" "github.com/fuserobotics/historian/dbproto" "github.com/fuserobotics/statestream" "github.com/golang/glog" r "gopkg.in/dancannon/gorethink.v2" ) var changeUnnecessaryError error = errors.New("change applied locally already") type Stream struct { dispose chan bool h *Historian dataTable r.Term Data *dbproto.Stream StateStream *stream.Stream } // Instantiate a new stream and start watch thread. func (h *Historian) NewStream(data *dbproto.Stream) (*Stream, error) { str := &Stream{ h: h, dispose: make(chan bool, 1), dataTable: r.Table(DbStreamTableName(data)), Data: data, } sstr, err := stream.NewStream(str, data.Config) if err != nil { return nil, err } str.StateStream = sstr /* if err := sstr.InitWriter(); err != nil { return nil, err } */ go str.watchThread() return str, nil } // The stream ID is the same as the tabe name. func StreamTableName(deviceHostname, componentName, stateName string) string { var buf bytes.Buffer if deviceHostname != "" { buf.WriteString(deviceHostname) buf.WriteString("_") } if componentName != "" { buf.WriteString(componentName) buf.WriteString("_") } buf.WriteString(stateName) return buf.String() } func DbStreamTableName(stream *dbproto.Stream) string { return StreamTableName(stream.DeviceHostname, stream.ComponentName, stream.StateName) } func (s *Stream) watchThread() (watchError error) { disposed := false select { case <-s.dispose: disposed = true return nil default: } defer func() { if watchError != nil { glog.Warningf("Error while watching for changes to %s, %v", s.Data.Id, watchError) } if !disposed && watchError != nil { time.Sleep(time.Duration(2) * time.Second) go s.watchThread() } else { glog.Infof("No longer watching for changes to %s.", s.Data.Id) } }() // force a db hit s.StateStream.ResetWriter() writeCursor, err := s.StateStream.WriteCursor() if err != nil { return nil } // Start cursor to watch for new entries // this isn't possible since they might come in unordered: // query := s.dataTable.Filter(r.Row.Field("timestamp").Gt(writeCursor.ComputedTimestamp())) // instead we will just accept we may drop entries in the 1ms between the last read and now. cursor, err := s.dataTable.Changes().Run(s.h.rctx) if err != nil { return err } defer cursor.Close() changesChan := make(chan streamEntryChange) cursor.Listen(changesChan) glog.Infof("Watching for changes to %s.", s.Data.Id) for { select { case <-s.dispose: disposed = true return case change, ok := <-changesChan: if !ok { return errors.New("RethinkDB closed the change channel.") } if err := s.handleChange(&change, writeCursor); err != nil { return err } } } } func (s *Stream) handleChange(cha *streamEntryChange, writeCursor *stream.Cursor) error { // nothing we can do about this if cha.NewValue == nil || cha.OldValue != nil { return nil } var wcts time.Time // wait until all local writes are done writeCursor.WriteGuard(func() error { wcts = writeCursor.ComputedTimestamp() return nil }) if cha.NewValue.Timestamp.Before(wcts) || cha.NewValue.Timestamp.Equal(wcts) { // glog.Infof("Ignoring stream entry change as it's before the latest computed timestamp.") return nil } glog.Infof("Handling stream entry for %s someone else wrote at ts %v local ts %v.", s.Data.Id, cha.NewValue.Timestamp, wcts) if err := writeCursor.HandleEntry(cha.NewValue); err != nil { return err } return nil } func (s *Stream) dataTableName() string { return StreamTableName(s.Data.DeviceHostname, s.Data.ComponentName, s.Data.StateName) } func (s *Stream) Dispose() { s.dispose <- true }