Dataset Viewer
Auto-converted to Parquet Duplicate
text
stringlengths
11
4.05M
package main import "fmt" func main() { var numOfTests int fmt.Scanf("%d", &numOfTests) var a, b int for i := 0; i < numOfTests; i++ { fmt.Scanf("%d %d", &a, &b) if b == 0 { fmt.Println("divisao impossivel") continue } result := float32(a) / float32(b) fmt.Printf("%.1f\n", result) } }
package controller type response struct { Description string Content interface{} }
package log import ( "sync" "github.com/gogf/gf/frame/g" "github.com/gogf/gf/os/glog" ) var _logger *glog.Logger var _loggerOnce sync.Once const logName = "cnbs" // init init func init() { if err := NewLogger().SetConfigWithMap(g.Map{ // "path": "/var/log", "level": "all", "stdout": true, "StStatus": 0, "project": logName, }); err != nil { panic(err) } } // NewLogger logger func NewLogger() *glog.Logger { if _logger != nil { return _logger } _loggerOnce.Do(func() { _logger = glog.New() }) return _logger } // Warn warn func Warn(args ...interface{}) { NewLogger().Warning(args...) } // Info info func Info(args ...interface{}) { NewLogger().Info(args...) } // Info info func InfoF(f string, args ...interface{}) { NewLogger().Infof(f, args...) } // Debug dev func Debug(args ...interface{}) { NewLogger().Debug(args...) } // DebugF dev func DebugF(f string, args ...interface{}) { NewLogger().Debugf(f, args...) } // // Trace dev // func Trace(args ...interface{}) { // NewLogger().(args...) // } // Fatal dev func Fatal(args ...interface{}) { NewLogger().Fatal(args...) } // Error dev func Error(args ...interface{}) { NewLogger().Error(args...) } // ErrorF ErrorF func ErrorF(f string, args ...interface{}) { NewLogger().Errorf(f, args...) }
/** *@Author: haoxiongxiao *@Date: 2019/1/28 *@Description: CREATE GO FILE models */ package models import ( "fmt" "time" "github.com/garyburd/redigo/redis" "github.com/jinzhu/gorm" _ "github.com/jinzhu/gorm/dialects/mysql" "github.com/lexkong/log" "github.com/spf13/viper" "gopkg.in/mgo.v2" ) type Database struct { Mysql *gorm.DB Redis *redis.Pool Mgo *mgo.Session } var DB *Database /* * * @msg mysql的初始化和连接 * @author haoxiong * @date 2019/1/28 17:27 */ func openMysqlDB(username, password, addr, name string) *gorm.DB { config := fmt.Sprintf("%s:%s@tcp(%s)/%s?charset=utf8&parseTime=%t&loc=%s", username, password, addr, name, true, //"Asia/Shanghai"), "Local") db, err := gorm.Open("mysql", config) if err != nil { log.Errorf(err, "Database connection failed. Database name: %s", name) } // set for db connection setupDB(db) go keepAlive(db) return db } func setupDB(db *gorm.DB) { db.LogMode(viper.GetBool("gormlog")) //db.DB().SetMaxOpenConns(20000) // 用于设置最大打开的连接数,默认值为0表示不限制.设置最大的连接数,可以避免并发太高导致连接mysql出现too many connections的错误。 db.DB().SetMaxIdleConns(2) // 用于设置闲置的连接数.设置闲置的连接数则当开启的一个连接使用完成后可以放在池里等候下一次使用。 db.SingularTable(true) //设置表名不为负数 //autoMigrate(db) } func (db *Database) Init() { DB = &Database{ Mysql: GetMysqlDB(), Redis: GetRedis(), Mgo: GetMgoDB(), } } func GetMysqlDB() *gorm.DB { return InitMysql() } func InitMysql() *gorm.DB { return openMysqlDB(viper.GetString("mysql.username"), viper.GetString("mysql.password"), viper.GetString("mysql.addr"), viper.GetString("mysql.name")) } func keepAlive(dbc *gorm.DB) { for { dbc.DB().Ping() time.Sleep(60 * time.Second) } } /* * * @msg redis 的初始化和连接 * @author haoxiong * @date 2019/1/28 17:26 */ func GetRedis() *redis.Pool { return InitRedis() } func InitRedis() *redis.Pool { return openRedisDB(viper.GetString("redis.redis_url"), viper.GetInt("redis.redis_idle_timeout_sec"), time.Duration(viper.GetInt("redis.redis_idle_timeout_sec")), viper.GetString("redis.password")) } func openRedisDB(redisURL string, redisMaxIdle int, redisIdleTimeoutSec time.Duration, redisPassword string) *redis.Pool { return &redis.Pool{ MaxIdle: redisMaxIdle, IdleTimeout: redisIdleTimeoutSec * time.Second, Dial: func() (redis.Conn, error) { c, err := redis.Dial("tcp", redisURL) if err != nil { return nil, fmt.Errorf("redis connection error: %s", err) } //验证redis密码 //if _, authErr := c.Do("AUTH", redisPassword); authErr != nil { // return nil, fmt.Errorf("redis auth password error: %s", authErr) //} return c, err }, TestOnBorrow: func(c redis.Conn, t time.Time) error { _, err := c.Do("PING") if err != nil { return fmt.Errorf("ping redis error: %s", err) } return nil }, } } /* * * @msg mgo连接 * @author haoxiong * @date 2019/1/29 15:31 */ func GetMgoDB() *mgo.Session { return InitMgo() } func InitMgo() *mgo.Session { timeout, _ := time.ParseDuration(viper.GetString("timeout")) authdb := viper.GetString("authdb") authuser := viper.GetString("authuser") authpass := viper.GetString("authpass") poollimit := viper.GetInt("poollimit") dialInfo := &mgo.DialInfo{ Addrs: []string{""}, //数据库地址 dbhost: mongodb://user@123456:127.0.0.1:27017 Timeout: timeout, // 连接超时时间 timeout: 60 * time.Second Source: authdb, // 设置权限的数据库 authdb: admin Username: authuser, // 设置的用户名 authuser: user Password: authpass, // 设置的密码 authpass: 123456 PoolLimit: poollimit, // 连接池的数量 poollimit: 100 } return openMgoDB(dialInfo) } func openMgoDB(dialInfo *mgo.DialInfo) *mgo.Session { s, err := mgo.DialWithInfo(dialInfo) if err != nil { log.Errorf(err, "连接mongo 失败") panic(err) } return s }
package okex_websocket import . "exchange_websocket/common" type OkexCylce struct { OkexCycles []string OkexCycleMap map[string]int } func NewOkexCycle() *OkexCylce { okCycle := new(OkexCylce) return okCycle.OkexCycleInit() } func (o *OkexCylce) OkexCycleInit() *OkexCylce { o.OkexCycles = []string{"1min", "3min", "5min", "15min", "30min", "1hour", "4hour", "day", "week"} o.OkexCycleMap = map[string]int{ "1min": int(KLine1Min), "3min": int(KLine3Min), "5min": int(KLine5Min), "15min": int(KLine15Min), "30min": int(KLine30Min), "1hour": int(KLine1hour), "4hour": int(KLine4hour), "day": int(KLineDay), "week": int(KLineWeek), } return o } func (o *OkexCylce) OkexCycleTransfer(cycle string) int { isExist, _ := Contain(cycle, o.OkexCycles) if isExist { return o.OkexCycleMap[cycle] } return 0 }
package allow_list import ( "context" "fmt" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/client-go/kubernetes" ) func DeployedDockerImages(kubernetesClient kubernetes.Interface, kubernetesNamespace string) ([]string, error) { var deployedDockerImages []string images, err := getPodsImages(kubernetesClient, kubernetesNamespace) if err != nil { return nil, fmt.Errorf("cannot get Pods images: %s", err) } deployedDockerImages = append(deployedDockerImages, images...) images, err = getReplicationControllersImages(kubernetesClient, kubernetesNamespace) if err != nil { return nil, fmt.Errorf("cannot get ReplicationControllers images: %s", err) } deployedDockerImages = append(deployedDockerImages, images...) images, err = getDeploymentsImages(kubernetesClient, kubernetesNamespace) if err != nil { return nil, fmt.Errorf("cannot get Deployments images: %s", err) } deployedDockerImages = append(deployedDockerImages, images...) images, err = getStatefulSetsImages(kubernetesClient, kubernetesNamespace) if err != nil { return nil, fmt.Errorf("cannot get StatefulSets images: %s", err) } deployedDockerImages = append(deployedDockerImages, images...) images, err = getDaemonSetsImages(kubernetesClient, kubernetesNamespace) if err != nil { return nil, fmt.Errorf("cannot get DaemonSets images: %s", err) } deployedDockerImages = append(deployedDockerImages, images...) images, err = getReplicaSetsImages(kubernetesClient, kubernetesNamespace) if err != nil { return nil, fmt.Errorf("cannot get ReplicaSets images: %s", err) } deployedDockerImages = append(deployedDockerImages, images...) images, err = getCronJobsImages(kubernetesClient, kubernetesNamespace) if err != nil { return nil, fmt.Errorf("cannot get CronJobs images: %s", err) } deployedDockerImages = append(deployedDockerImages, images...) images, err = getJobsImages(kubernetesClient, kubernetesNamespace) if err != nil { return nil, fmt.Errorf("cannot get Jobs images: %s", err) } deployedDockerImages = append(deployedDockerImages, images...) return deployedDockerImages, nil } func getPodsImages(kubernetesClient kubernetes.Interface, kubernetesNamespace string) ([]string, error) { var images []string list, err := kubernetesClient.CoreV1().Pods(kubernetesNamespace).List(context.Background(), metav1.ListOptions{}) if err != nil { return nil, err } for _, pod := range list.Items { for _, container := range append( pod.Spec.Containers, pod.Spec.InitContainers..., ) { images = append(images, container.Image) } } return images, nil } func getReplicationControllersImages(kubernetesClient kubernetes.Interface, kubernetesNamespace string) ([]string, error) { var images []string list, err := kubernetesClient.CoreV1().ReplicationControllers(kubernetesNamespace).List(context.Background(), metav1.ListOptions{}) if err != nil { return nil, err } for _, replicationController := range list.Items { for _, container := range append( replicationController.Spec.Template.Spec.Containers, replicationController.Spec.Template.Spec.InitContainers..., ) { images = append(images, container.Image) } } return images, nil } func getDeploymentsImages(kubernetesClient kubernetes.Interface, kubernetesNamespace string) ([]string, error) { var images []string list, err := kubernetesClient.AppsV1().Deployments(kubernetesNamespace).List(context.Background(), metav1.ListOptions{}) if err != nil { return nil, err } for _, deployment := range list.Items { for _, container := range append( deployment.Spec.Template.Spec.Containers, deployment.Spec.Template.Spec.InitContainers..., ) { images = append(images, container.Image) } } return images, nil } func getStatefulSetsImages(kubernetesClient kubernetes.Interface, kubernetesNamespace string) ([]string, error) { var images []string list, err := kubernetesClient.AppsV1().StatefulSets(kubernetesNamespace).List(context.Background(), metav1.ListOptions{}) if err != nil { return nil, err } for _, statefulSet := range list.Items { for _, container := range append( statefulSet.Spec.Template.Spec.Containers, statefulSet.Spec.Template.Spec.InitContainers..., ) { images = append(images, container.Image) } } return images, nil } func getDaemonSetsImages(kubernetesClient kubernetes.Interface, kubernetesNamespace string) ([]string, error) { var images []string list, err := kubernetesClient.AppsV1().DaemonSets(kubernetesNamespace).List(context.Background(), metav1.ListOptions{}) if err != nil { return nil, err } for _, daemonSets := range list.Items { for _, container := range append( daemonSets.Spec.Template.Spec.Containers, daemonSets.Spec.Template.Spec.InitContainers..., ) { images = append(images, container.Image) } } return images, nil } func getReplicaSetsImages(kubernetesClient kubernetes.Interface, kubernetesNamespace string) ([]string, error) { var images []string list, err := kubernetesClient.AppsV1().ReplicaSets(kubernetesNamespace).List(context.Background(), metav1.ListOptions{}) if err != nil { return nil, err } for _, replicaSet := range list.Items { for _, container := range append( replicaSet.Spec.Template.Spec.Containers, replicaSet.Spec.Template.Spec.InitContainers..., ) { images = append(images, container.Image) } } return images, nil } func getCronJobsImages(kubernetesClient kubernetes.Interface, kubernetesNamespace string) ([]string, error) { var images []string list, err := kubernetesClient.BatchV1beta1().CronJobs(kubernetesNamespace).List(context.Background(), metav1.ListOptions{}) if err != nil { return nil, err } for _, cronJob := range list.Items { for _, container := range append( cronJob.Spec.JobTemplate.Spec.Template.Spec.Containers, cronJob.Spec.JobTemplate.Spec.Template.Spec.InitContainers..., ) { images = append(images, container.Image) } } return images, nil } func getJobsImages(kubernetesClient kubernetes.Interface, kubernetesNamespace string) ([]string, error) { var images []string list, err := kubernetesClient.BatchV1().Jobs(kubernetesNamespace).List(context.Background(), metav1.ListOptions{}) if err != nil { return nil, err } for _, job := range list.Items { for _, container := range append( job.Spec.Template.Spec.Containers, job.Spec.Template.Spec.InitContainers..., ) { images = append(images, container.Image) } } return images, nil }
// +build nobootstrap package hashes import ( "encoding/hex" "fmt" "runtime" "strings" "gopkg.in/op/go-logging.v1" "build" "core" "parse" ) var log = logging.MustGetLogger("hashes") // RewriteHashes rewrites the hashes in a BUILD file. func RewriteHashes(state *core.BuildState, labels []core.BuildLabel) { // Collect the targets per-package so we only rewrite each file once. m := map[string]map[string]string{} for _, l := range labels { for _, target := range state.Graph.PackageOrDie(l.PackageName).AllChildren(state.Graph.TargetOrDie(l)) { // Ignore targets with no hash specified. if len(target.Hashes) == 0 { continue } h, err := build.OutputHash(target) if err != nil { log.Fatalf("%s\n", err) } // Interior targets won't appear in the BUILD file directly, look for their parent instead. l := target.Label.Parent() hashStr := hex.EncodeToString(h) if m2, present := m[l.PackageName]; present { m2[l.Name] = hashStr } else { m[l.PackageName] = map[string]string{l.Name: hashStr} } } } for pkgName, hashes := range m { if err := rewriteHashes(state, state.Graph.PackageOrDie(pkgName).Filename, runtime.GOOS+"_"+runtime.GOARCH, hashes); err != nil { log.Fatalf("%s\n", err) } } } // rewriteHashes rewrites hashes in a single file. func rewriteHashes(state *core.BuildState, filename, platform string, hashes map[string]string) error { log.Notice("Rewriting hashes in %s...", filename) data := string(MustAsset("hash_rewriter.py")) // Template in the variables we want. h := make([]string, 0, len(hashes)) for k, v := range hashes { h = append(h, fmt.Sprintf(`"%s": "%s"`, k, v)) } data = strings.Replace(data, "__FILENAME__", filename, 1) data = strings.Replace(data, "__TARGETS__", strings.Join(h, ",\n"), 1) data = strings.Replace(data, "__PLATFORM__", platform, 1) return parse.RunCode(state, data) }
// Copyright 2016 Sevki <[email protected]>. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Package internal is used for registering types in build, it had no clear place // in other packages to go which is why it gets it's own package package internal import ( "fmt" "reflect" ) var ( rules map[string]reflect.Type ) func init() { rules = make(map[string]reflect.Type) } // Register function is used to register new types of targets. func Register(name string, t interface{}) error { ty := reflect.TypeOf(t) if _, build := reflect.PtrTo(reflect.TypeOf(t)).MethodByName("Build"); !build { return fmt.Errorf("%s doesn't implement Build", reflect.TypeOf(t)) } rules[name] = ty return nil } // Get returns a reflect.Type for a given name. func Get(name string) reflect.Type { if t, ok := rules[name]; ok { return t } return nil } // GetFieldByTag returns field by tag func GetFieldByTag(tn, tag string, p reflect.Type) (*reflect.StructField, error) { if p == nil { return nil, fmt.Errorf("%s isn't a registered type", tn) } for i := 0; i < p.NumField(); i++ { f := p.Field(i) if f.Tag.Get(tn) == tag { return &f, nil } } return nil, fmt.Errorf("%s isn't a field of %s", tag, tn) } // Rules returns registered RulesTypes func Rules() []string { s := []string{} for k := range rules { s = append(s, k) } return s }
package util import ( tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api" ) func GetAcceptingMessage(message *MessageData, acceptingString string) tgbotapi.MessageConfig { msg := tgbotapi.NewMessage(message.Chat.ID, acceptingString) row := make([]tgbotapi.KeyboardButton, 0) yesBtn := tgbotapi.NewKeyboardButton("Да") noBtn := tgbotapi.NewKeyboardButton("Нет") row = append(row, yesBtn) row = append(row, noBtn) keyboard := tgbotapi.NewReplyKeyboard(row) msg.ReplyMarkup = keyboard return msg }
package leetcode /*Given a m * n matrix mat of ones (representing soldiers) and zeros (representing civilians), return the indexes of the k weakest rows in the matrix ordered from the weakest to the strongest. A row i is weaker than row j, if the number of soldiers in row i is less than the number of soldiers in row j, or they have the same number of soldiers but i is less than j. Soldiers are always stand in the frontier of a row, that is, always ones may appear first and then zeros. 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/the-k-weakest-rows-in-a-matrix 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。*/ import "sort" func kWeakestRows(mat [][]int, k int) []int { m, n := len(mat), len(mat[0]) res := make([]int, m) ans := make([]int, m) for i := 0; i < m; i++ { ans[i] = i for j := 0; j < n; j++ { if mat[i][j] == 1 { res[i]++ } else { break } } } sort.Slice(ans, func(i, j int) bool { return res[ans[i]] < res[ans[j]] || (res[ans[i]] == res[ans[j]] && ans[i] < ans[j]) }) return ans[:k] }
// Command reposize takes a newline-separated list of github repos on stdin, // clones them, computes their size, deletes them, and outputs to stdout // a CSV table with rows of sizebytes,repo. package main // import "github.com/ijt/reposize" import ( "bufio" "flag" "fmt" "io/ioutil" "log" "net/http" "os" "os/exec" "path/filepath" "strings" "github.com/pkg/errors" ) var verboseFlag = flag.Bool("v", false, "whether to log verbosely") var numWorkers = flag.Int("n", 10, "number of workers to run") func main() { if err := reposize(); err != nil { log.Fatal(err) } } type token struct{} func reposize() error { flag.Parse() // Start the work, using the semaphore pattern at // https://www.youtube.com/watch?v=5zXAHh5tJqQ&t=33m22s sem := make(chan token, *numWorkers) s := bufio.NewScanner(os.Stdin) for s.Scan() { repo := s.Text() sem <- token{} go func(r string) { defer func() { <-sem }() sb, err := sizeOfOneRepo(r) if err != nil { log.Printf("error sizing repo %s: %v", r, err) return } fmt.Printf("%d,%s\n", sb, r) }(repo) } // Wait for completion. for n := *numWorkers; n > 0; n-- { sem <- token{} } return nil } func sizeOfOneRepo(repo string) (int, error) { td, err := ioutil.TempDir("", "reposize") if err != nil { return 0, errors.Wrap(err, "making temp dir") } // Clone the repo. d := filepath.Join(td, filepath.Base(repo)) cmd := exec.Command("git", "clone", fmt.Sprintf("https://%s.git", repo), d) cmd.Env = []string{"GIT_TERMINAL_PROMPT=0"} out, err := cmd.CombinedOutput() if err != nil { return 0, errors.Wrapf(err, "clone failed: %s", out) } // Add the size of the repo. sb, err := dirSizeBytes(d) if err != nil { return 0, errors.Wrap(err, "computing size of repo") } // Delete the repo. if err := os.RemoveAll(td); err != nil { return 0, errors.Wrapf(err, "removing %s", td) } return sb, nil } func dirSizeBytes(d string) (int, error) { sb := 0 err := filepath.Walk(d, func(path string, info os.FileInfo, err error) error { if err != nil { return nil } f, err := os.Open(path) if err != nil { log.Printf("Failed to open %s. Skipping it.", path) return nil } defer f.Close() b := make([]byte, 512) n, err := f.Read(b) if err != nil { log.Printf("Failed to read beginning of %s. Skipping it.", path) return nil } typ := http.DetectContentType(b[:n]) if !strings.HasPrefix(typ, "text/") { if *verboseFlag { log.Printf("Skipping file %s with type %s", path, typ) } return nil } sb += int(info.Size()) return nil }) if err != nil { return 0, errors.Wrapf(err, "walking from %s", d) } return sb, nil }
package main /* * @lc app=leetcode id=145 lang=golang * * [145] Binary Tree Postorder Traversal */ /** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */ func prepend(s []int, t int) []int { s = append(s, 0) copy(s[1:], s) s[0] = t return s } // 用前序遍历的方式作弊 func postorderTraversal(root *TreeNode) []int { var res []int if root == nil { return res } var stack Stack stack.push(root) for !stack.isEmpty() { node := stack.pop() res = prepend(res, node.Val) if node.Left != nil { stack.push(node.Left) } if node.Right != nil { stack.push(node.Right) } } return res } func postorderTraversal_Recursively(root *TreeNode) []int { var res []int traverse(root, &res) return res } func traverse(root *TreeNode, res *[]int) { if root == nil { return } traverse(root.Left, res) traverse(root.Right, res) *res = append(*res, root.Val) } type Stack []*TreeNode func (s Stack) isEmpty() bool { return len(s) == 0 } func (s *Stack) push(n *TreeNode) { *s = append(*s, n) } func (s *Stack) pop() *TreeNode { t := (*s)[len(*s)-1] *s = (*s)[:len(*s)-1] return t }
package postgres import ( "database/sql" "database/sql/driver" "errors" "fmt" ) type PostgresDriver struct { } func (d PostgresDriver) Open(string) (driver.Conn, error) { fmt.Println("Open a postgres driver") return nil, errors.New("UnImplemented") } var d *PostgresDriver func init() { d = new(PostgresDriver) sql.Register("postgres", d) }
package main import "fmt" func main() { // START OMIT i := 0 fmt.Printf("%d\n", i++) // END OMIT }
package test import ( "testing" "sync" "fmt" "time" "sub_account_service/order_server/entity" "sub_account_service/order_server/dto" "encoding/json" "bytes" "sub_account_service/order_server/utils" ) func TestAddOrder(t *testing.T) { var wg sync.WaitGroup timeStamp := fmt.Sprintf("%v",time.Now().Unix() * 1000) developKey := "a9cd0f73a013f6f2704c9d0fcc72ab8f" sign := utils.MD5(timeStamp + developKey) url := "http://localhost:7777/orders/save?Sign="+sign +"&AppId=9527&Timestamp="+timeStamp beginTime := time.Now().UnixNano() count := 1 for i :=0;i<count;i++ { wg.Add(1) go func(z int64) { defer wg.Done() orderState := entity.Normal thirdNo := "third" + fmt.Sprintf("%v",time.Now().Unix() * 1000 + z) orderNo := fmt.Sprintf("%v",time.Now().Unix() * 1000 + z) bill := dto.BillOrderSaveDTO{ ThirdTradeNo: thirdNo , OrderNo: orderNo, SubNumber: "AC:2acea93ab7bfff66e492c4169bf615b1",//AC:aee8a4c271a2572623ed3294706c826a Company: "测试", BranchShop: "测试公司", OrderTime: "2018-12-12 11:11:11", PayWay: "支付宝", Discount: 300, SumPrice: 900, Price: 600, OrderState:orderState, Remarks:"1212", } out, _ := json.Marshal(bill) tt,err := utils.Post(url, bytes.NewReader(out),nil,nil) time.Sleep(time.Second) fmt.Println(string(tt),err) }(int64(i)) } wg.Wait() endTime := time.Now().UnixNano() diffTime := (endTime - beginTime)/int64(time.Millisecond) fmt.Printf("count:%v,duration:%v",count,diffTime) }
// Copyright 2020 Readium Foundation. All rights reserved. // Use of this source code is governed by a BSD-style license // that can be found in the LICENSE file exposed on Github (readium) in the project repository. package index import ( "database/sql" "testing" _ "github.com/mattn/go-sqlite3" "github.com/readium/readium-lcp-server/config" ) func TestIndexCreation(t *testing.T) { config.Config.LcpServer.Database = "sqlite" // FIXME db, err := sql.Open("sqlite3", ":memory:") idx, err := Open(db) if err != nil { t.Error("Can't open index") t.Error(err) t.FailNow() } c := Content{ID: "test", EncryptionKey: []byte("1234"), Location: "test.epub"} err = idx.Add(c) if err != nil { t.Error(err) } _, err = idx.Get("test") if err != nil { t.Error(err) } }
/* Package context "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 context import ( "crypto/md5" "github.com/MerinEREN/iiPackages/datastore/pageContext" "golang.org/x/net/context" "google.golang.org/appengine/datastore" "io" "time" ) /* GetNextLimited returns limited entitities within an order after the given cursor. If limit is 0 or greater than 40, default limit will be used. */ func GetNextLimited(ctx context.Context, crsrAsString string, lim int) ( Contexts, string, error) { var err error var after datastore.Cursor cs := make(Contexts) q := datastore.NewQuery("Context"). Order("-LastModified") if crsrAsString != "" { if after, err = datastore.DecodeCursor(crsrAsString); err != nil { return nil, crsrAsString, err } q = q.Start(after) } // if lim > 0 && lim < 40 { if lim != 0 { q = q.Limit(lim) } else { q = q.Limit(12) } for it := q.Run(ctx); ; { c := new(Context) k, err := it.Next(c) if err == datastore.Done { after, err = it.Cursor() return cs, after.String(), err } if err != nil { return nil, crsrAsString, err } c.ID = k.Encode() cs[c.ID] = c } } /* UpdateMulti is a transaction that delets all PageContext entities for corresponding context and then creates and puts new ones. Finally, puts modified Contexts and returns nil map and an error. */ func UpdateMulti(ctx context.Context, cx []*Context) (Contexts, error) { var kx []*datastore.Key var kpcxDelete []*datastore.Key var kpcxPut []*datastore.Key var pcx pageContext.PageContexts var err error for _, v := range cx { k := new(datastore.Key) k, err = datastore.DecodeKey(v.ID) if err != nil { return nil, err } kpcx, err := pageContext.GetKeys(ctx, k) if err != nil { return nil, err } for _, v2 := range kpcx { kpcxDelete = append(kpcxDelete, v2) } kx = append(kx, k) v.LastModified = time.Now() for _, v2 := range v.PageIDs { kp := new(datastore.Key) kp, err = datastore.DecodeKey(v2) if err != nil { return nil, err } kpc := datastore.NewIncompleteKey(ctx, "PageContext", kp) kpcxPut = append(kpcxPut, kpc) pc := new(pageContext.PageContext) pc.ContextKey = k pcx = append(pcx, pc) } } opts := new(datastore.TransactionOptions) opts.XG = true err = datastore.RunInTransaction(ctx, func(ctx context.Context) (err1 error) { if err1 = datastore.DeleteMulti(ctx, kpcxDelete); err1 != nil { return } if _, err1 = datastore.PutMulti(ctx, kpcxPut, pcx); err1 != nil { return } _, err1 = datastore.PutMulti(ctx, kx, cx) return }, opts) return nil, err } /* AddMulti creates and puts corresponding PageContexts and then puts newly created Contexts. Also, returns new Contexts and an error. */ func AddMulti(ctx context.Context, cx []*Context) (Contexts, error) { var kx []*datastore.Key var kpcx []*datastore.Key var pcx pageContext.PageContexts var err error for _, v := range cx { k := new(datastore.Key) // Max stringID lenght for a datastore key is 500 acording to link // https://stackoverflow.com/questions/2557632/how-long-max- // characters-can-a-datastore-entity-key-name-be-is-it-bad-to-haver var stringID string if len(v.Values["en-US"]) > 100 { h := md5.New() io.WriteString(h, v.Values["en-US"]) stringID = string(h.Sum(nil)) } else { stringID = v.Values["en-US"] } k = datastore.NewKey(ctx, "Context", stringID, 0, nil) kx = append(kx, k) v.Created = time.Now() v.LastModified = time.Now() for _, v2 := range v.PageIDs { kp := new(datastore.Key) kp, err = datastore.DecodeKey(v2) if err != nil { return nil, err } kpc := datastore.NewIncompleteKey(ctx, "PageContext", kp) kpcx = append(kpcx, kpc) pc := new(pageContext.PageContext) pc.ContextKey = k pcx = append(pcx, pc) } } opts := new(datastore.TransactionOptions) opts.XG = true err = datastore.RunInTransaction(ctx, func(ctx context.Context) (err1 error) { if _, err1 = datastore.PutMulti(ctx, kpcx, pcx); err1 != nil { return } _, err1 = datastore.PutMulti(ctx, kx, cx) return }, opts) if err != nil { return nil, err } cs := make(Contexts) for i, v := range cx { v.ID = kx[i].Encode() cs[v.ID] = v } return cs, err } /* AddMultiAndGetNextLimited is a transaction which puts the posted entities first and then gets entities from the reseted cursor by the given limit. Finally returnes received entities with posted entities added to them as a map. */ func AddMultiAndGetNextLimited(ctx context.Context, crsrAsString string, cx []*Context) ( Contexts, string, error) { csPut := make(Contexts) csGet := make(Contexts) err := datastore.RunInTransaction(ctx, func(ctx context.Context) (err1 error) { if csPut, err1 = AddMulti(ctx, cx); err1 != nil { return } csGet, crsrAsString, err1 = GetNextLimited(ctx, crsrAsString, 2222) return }, nil) if err == nil { for i, v := range csGet { csPut[i] = v } } return csPut, crsrAsString, err } /* DeleteMulti removes the entities and all the corresponding pageContext entities by the provided encoded keys also returns an error. */ func DeleteMulti(ctx context.Context, ekx []string) error { var kx []*datastore.Key var kpcx []*datastore.Key for _, v := range ekx { k, err := datastore.DecodeKey(v) if err != nil { return err } kx = append(kx, k) kpcx2, err := pageContext.GetKeys(ctx, k) if err != nil { return err } for _, v2 := range kpcx2 { kpcx = append(kpcx, v2) } } opts := new(datastore.TransactionOptions) opts.XG = true return datastore.RunInTransaction(ctx, func(ctx context.Context) (err1 error) { err1 = datastore.DeleteMulti(ctx, kpcx) if err1 != nil { return } err1 = datastore.DeleteMulti(ctx, kx) return }, opts) }
package service import ( "errors" "fmt" "github.com/13283339616/orm" "github.com/13283339616/util" "github.com/13283339616/vo" ) type HelloService struct { } func (h HelloService) Index(v vo.LoginRequestVo) (token string, err error) { u := orm.User{} user := u.GetUserByUserCode(v.Username) if user == nil { return "", errors.New("用户不存在") } if !user.Enabled { return "", errors.New("用户被禁止登陆") } password := util.Md5([]byte(v.Password)) fmt.Println(password) fmt.Println(user.Password) if user.Password != password { return "", errors.New("账号密码不正确") } return "abc", nil }
// Copyright (C) 2021 Cisco Systems 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 common import ( "fmt" log "github.com/sirupsen/logrus" ) type CalicoVppEventType string const ( ChanSize = 500 PeerNodeStateChanged CalicoVppEventType = "PeerNodeStateChanged" FelixConfChanged CalicoVppEventType = "FelixConfChanged" IpamConfChanged CalicoVppEventType = "IpamConfChanged" BGPConfChanged CalicoVppEventType = "BGPConfChanged" ConnectivityAdded CalicoVppEventType = "ConnectivityAdded" ConnectivityDeleted CalicoVppEventType = "ConnectivityDeleted" SRv6PolicyAdded CalicoVppEventType = "SRv6PolicyAdded" SRv6PolicyDeleted CalicoVppEventType = "SRv6PolicyDeleted" PodAdded CalicoVppEventType = "PodAdded" PodDeleted CalicoVppEventType = "PodDeleted" LocalPodAddressAdded CalicoVppEventType = "LocalPodAddressAdded" LocalPodAddressDeleted CalicoVppEventType = "LocalPodAddressDeleted" TunnelAdded CalicoVppEventType = "TunnelAdded" TunnelDeleted CalicoVppEventType = "TunnelDeleted" BGPPeerAdded CalicoVppEventType = "BGPPeerAdded" BGPPeerDeleted CalicoVppEventType = "BGPPeerDeleted" BGPPeerUpdated CalicoVppEventType = "BGPPeerUpdated" BGPSecretChanged CalicoVppEventType = "BGPSecretChanged" BGPFilterAddedOrUpdated CalicoVppEventType = "BGPFilterAddedOrUpdated" BGPFilterDeleted CalicoVppEventType = "BGPFilterDeleted" BGPDefinedSetAdded CalicoVppEventType = "BGPDefinedSetAdded" BGPDefinedSetDeleted CalicoVppEventType = "BGPDefinedSetDeleted" BGPPathAdded CalicoVppEventType = "BGPPathAdded" BGPPathDeleted CalicoVppEventType = "BGPPathDeleted" NetAddedOrUpdated CalicoVppEventType = "NetAddedOrUpdated" NetDeleted CalicoVppEventType = "NetDeleted" NetsSynced CalicoVppEventType = "NetsSynced" IpamPoolUpdate CalicoVppEventType = "IpamPoolUpdate" IpamPoolRemove CalicoVppEventType = "IpamPoolRemove" WireguardPublicKeyChanged CalicoVppEventType = "WireguardPublicKeyChanged" ) var ( ThePubSub *PubSub ) type CalicoVppEvent struct { Type CalicoVppEventType Old interface{} New interface{} } type PubSubHandlerRegistration struct { /* Name for the registration, for logging & debugging */ name string /* Channel where to send events */ channel chan CalicoVppEvent /* Receive only these events. If empty we'll receive all */ expectedEvents map[CalicoVppEventType]bool /* Receive all events */ expectAllEvents bool } func (reg *PubSubHandlerRegistration) ExpectEvents(eventTypes ...CalicoVppEventType) { for _, eventType := range eventTypes { reg.expectedEvents[eventType] = true } reg.expectAllEvents = false } type PubSub struct { log *log.Entry pubSubHandlerRegistrations []*PubSubHandlerRegistration } func RegisterHandler(channel chan CalicoVppEvent, name string) *PubSubHandlerRegistration { reg := &PubSubHandlerRegistration{ channel: channel, name: name, expectedEvents: make(map[CalicoVppEventType]bool), expectAllEvents: true, /* By default receive everything, unless we ask for a filter */ } ThePubSub.pubSubHandlerRegistrations = append(ThePubSub.pubSubHandlerRegistrations, reg) return reg } func redactPassword(event CalicoVppEvent) string { switch event.Type { case BGPPeerAdded: return string(event.Type) default: return fmt.Sprintf("%+v", event) } } func SendEvent(event CalicoVppEvent) { ThePubSub.log.Debugf("Broadcasting event %s", redactPassword(event)) for _, reg := range ThePubSub.pubSubHandlerRegistrations { if reg.expectAllEvents || reg.expectedEvents[event.Type] { reg.channel <- event } } } func NewPubSub(log *log.Entry) *PubSub { return &PubSub{ log: log, pubSubHandlerRegistrations: make([]*PubSubHandlerRegistration, 0), } }
// 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 types import ( "math" "strconv" "strings" "github.com/pingcap/errors" ) const ( // UnspecifiedFsp is the unspecified fractional seconds part. UnspecifiedFsp = -1 // MaxFsp is the maximum digit of fractional seconds part. MaxFsp = 6 // MinFsp is the minimum digit of fractional seconds part. MinFsp = 0 // DefaultFsp is the default digit of fractional seconds part. // MySQL use 0 as the default Fsp. DefaultFsp = 0 ) // CheckFsp checks whether fsp is in valid range. func CheckFsp(fsp int) (int, error) { if fsp == UnspecifiedFsp { return DefaultFsp, nil } if fsp < MinFsp { return DefaultFsp, errors.Errorf("Invalid fsp %d", fsp) } else if fsp > MaxFsp { return MaxFsp, nil } return fsp, nil } // ParseFrac parses the input string according to fsp, returns the microsecond, // and also a bool value to indice overflow. eg: // "999" fsp=2 will overflow. func ParseFrac(s string, fsp int) (v int, overflow bool, err error) { if len(s) == 0 { return 0, false, nil } fsp, err = CheckFsp(fsp) if err != nil { return 0, false, errors.Trace(err) } if fsp >= len(s) { tmp, e := strconv.ParseInt(s, 10, 64) if e != nil { return 0, false, errors.Trace(e) } v = int(float64(tmp) * math.Pow10(MaxFsp-len(s))) return } // Round when fsp < string length. tmp, e := strconv.ParseInt(s[:fsp+1], 10, 64) if e != nil { return 0, false, errors.Trace(e) } tmp = (tmp + 5) / 10 if float64(tmp) >= math.Pow10(fsp) { // overflow return 0, true, nil } // Get the final frac, with 6 digit number // 1236 round 3 -> 124 -> 124000 // 0312 round 2 -> 3 -> 30000 // 999 round 2 -> 100 -> overflow v = int(float64(tmp) * math.Pow10(MaxFsp-fsp)) return } // alignFrac is used to generate alignment frac, like `100` -> `100000` ,`-100` -> `-100000` func alignFrac(s string, fsp int) string { sl := len(s) if sl > 0 && s[0] == '-' { sl = sl - 1 } if sl < fsp { return s + strings.Repeat("0", fsp-sl) } return s }
package modules import ( "encoding/json" "fmt" "io/ioutil" "log" "strings" "github.com/interstellar/kelp/model" "github.com/interstellar/kelp/support/logger" "github.com/interstellar/kelp/support/utils" "github.com/stellar/go/build" "github.com/stellar/go/clients/horizon" ) // DexWatcher is an object that queries the DEX type DexWatcher struct { API *horizon.Client Network build.Network TradingAccount string l logger.Logger } // MakeDexWatcher is the factory method func MakeDexWatcher( api *horizon.Client, network build.Network, tradingAccount string, l logger.Logger) *DexWatcher { return &DexWatcher{ API: api, Network: network, TradingAccount: tradingAccount, l: l, } } // type pathResponse // GetTopBid returns the top bid's price and amount for a trading pair func (w *DexWatcher) GetTopBid(pair TradingPair) (*model.Number, *model.Number, error) { orderBook, e := w.GetOrderBook(w.API, pair) if e != nil { return nil, nil, fmt.Errorf("unable to get sdex price: %s", e) } bids := orderBook.Bids if len(bids) == 0 { //w.l.Infof("No bids for pair: %s - %s ", pair.Base.Code, pair.Quote.Code) return model.NumberConstants.Zero, model.NumberConstants.Zero, nil } topBidPrice, e := model.NumberFromString(bids[0].Price, utils.SdexPrecision) if e != nil { return nil, nil, fmt.Errorf("Error converting to model.Number: %s", e) } topBidAmount, e := model.NumberFromString(bids[0].Amount, utils.SdexPrecision) if e != nil { return nil, nil, fmt.Errorf("Error converting to model.Number: %s", e) } // now invert the bid amount because the network sends it upside down floatPrice := topBidPrice.AsFloat() topBidAmount = topBidAmount.Scale(1 / floatPrice) //w.l.Infof("topBidPrice for pair Base = %s Quote =%s was %v", pair.Base.Code, pair.Quote.Code, topBidPrice) return topBidPrice, topBidAmount, nil } // GetLowAsk returns the low ask's price and amount for a trading pair func (w *DexWatcher) GetLowAsk(pair TradingPair) (*model.Number, *model.Number, error) { orderBook, e := w.GetOrderBook(w.API, pair) if e != nil { return nil, nil, fmt.Errorf("unable to get sdex price: %s", e) } asks := orderBook.Asks if len(asks) == 0 { //w.l.Infof("No asks for pair: %s - %s ", pair.Base.Code, pair.Quote.Code) return model.NumberConstants.Zero, model.NumberConstants.Zero, nil } lowAskPrice, e := model.NumberFromString(asks[0].Price, utils.SdexPrecision) if e != nil { return nil, nil, fmt.Errorf("Error converting to model.Number: %s", e) } lowAskAmount, e := model.NumberFromString(asks[0].Amount, utils.SdexPrecision) if e != nil { return nil, nil, fmt.Errorf("Error converting to model.Number: %s", e) } //w.l.Infof("lowAskPrice for pair Base = %s Quote =%s was %v", pair.Base.Code, pair.Quote.Code, lowAskPrice) return lowAskPrice, lowAskAmount, nil } // GetOrderBook gets the SDEX order book func (w *DexWatcher) GetOrderBook(api *horizon.Client, pair TradingPair) (orderBook horizon.OrderBookSummary, e error) { baseAsset, quoteAsset := Pair2Assets(pair) b, e := api.LoadOrderBook(baseAsset, quoteAsset) if e != nil { log.Printf("Can't get SDEX orderbook: %s\n", e) return } return b, e } // GetPaths gets and parses the find-path data for an asset from horizon func (w *DexWatcher) GetPaths(endAsset horizon.Asset, amount *model.Number) (*FindPathResponse, error) { var s strings.Builder var paths FindPathResponse amountString := amount.AsString() s.WriteString(fmt.Sprintf("%s/paths?source_account=%s", w.API.URL, w.TradingAccount)) s.WriteString(fmt.Sprintf("&destination_account=%s", w.TradingAccount)) s.WriteString(fmt.Sprintf("&destination_asset_type=%s", endAsset.Type)) s.WriteString(fmt.Sprintf("&destination_asset_code=%s", endAsset.Code)) s.WriteString(fmt.Sprintf("&destination_asset_issuer=%s", endAsset.Issuer)) s.WriteString(fmt.Sprintf("&destination_amount=%s", amountString)) //w.l.Infof("GET string built as: %s", s.String()) resp, e := w.API.HTTP.Get(s.String()) //resp, e := w.API.HTTP.Get("https://horizon.stellar.org/paths?source_account=GDJQ7DGRBAPJMBMDNDZIBCW4SFZ55GWEHYEPGLRJQW46NGBUSYSCLSLV&destination_account=GDJQ7DGRBAPJMBMDNDZIBCW4SFZ55GWEHYEPGLRJQW46NGBUSYSCLSLV&destination_asset_type=credit_alphanum4&destination_asset_code=BTC&destination_asset_issuer=GBSTRH4QOTWNSVA6E4HFERETX4ZLSR3CIUBLK7AXYII277PFJC4BBYOG&destination_amount=.0000001") if e != nil { return nil, e } // w.l.Info("") // w.l.Infof("Raw horizon response was %s\n", resp.Body) // w.l.Info("") defer resp.Body.Close() byteResp, e := ioutil.ReadAll(resp.Body) if e != nil { return nil, e } json.Unmarshal([]byte(byteResp), &paths) // if len(paths.Embedded.Records) > 0 { // w.l.Info("") // w.l.Infof("Unmarshalled into: %+v\n", paths.Embedded.Records[0]) // w.l.Info("") // } return &paths, nil }
/* API - API functions. */ package main import ( "encoding/json" "net/http" ) /* Pool - the pool data for creating of the user. */ type Pool struct { Pool string `json:"pool"` User string `json:"user"` Password string `json:"password"` } /* API - API functions. */ type API struct{} /* ServeHTTP - web handler. */ func (a *API) ServeHTTP(w http.ResponseWriter, r *http.Request) { var err error err = nil u := r.URL w.Header().Set("Content-Type", "application/json") if u.Path == "/api/v1/users" && (r.Method == "POST" || r.Method == "PUT") { var p Pool decoder := json.NewDecoder(r.Body) err = decoder.Decode(&p) if err == nil { LogInfo("proxy : API request to add user with pool %s and credentials %s:%s", "", p.Pool, p.User, p.Password) var user *User user, err = db.GetUserByPool(p.Pool, p.User) if err == nil { if user == nil { LogInfo("proxy : user not found and will be added", "") user = new(User) err = user.Init(p.Pool, p.User, p.Password) } if err == nil { LogInfo("proxy : user successfully created with name %s", "", user.name) w.WriteHeader(http.StatusCreated) w.Write([]byte(`{"name": "` + user.name + `", "error": ""}`)) } } } } else if u.Path == "/api/v1/pools" && r.Method == "GET" { LogInfo("proxy : API request to get pools", "") w.WriteHeader(http.StatusOK) } else { w.WriteHeader(http.StatusNotFound) w.Write([]byte(`{"error": "command not found"}`)) } if err != nil { LogError("proxy : API error: %s", "", err.Error()) w.WriteHeader(http.StatusServiceUnavailable) w.Write([]byte(`{"error": "` + err.Error() + `"}`)) } }
package beans var MetricsInfluxdb = "" //性能统计influxdb地址 var MachineNo = "" //机器编码 var RunMode = "dev" //运行模式
package assert import ( "testing" ) func TestAssert(t *testing.T) { var i interface{} = "1" defer Catch(func(violation Violation) { t.Logf("Cacth Violation: %s", violation) }) _ = Int(i) t.Errorf("not panic") }
package main import ( "bufio" "bytes" "fmt" "math" "os" "strconv" "strings" ) func main() { s := bufio.NewScanner(os.Stdin) // file, _ := os.Open(os.Stdin) // s := bufio.NewScanner(file) buf := new(bytes.Buffer) buf.Grow(1024 * 1024) s.Buffer(buf.Bytes(), 1024*1024) s.Scan() n, err := strconv.Atoi(s.Text()) if err != nil { fmt.Println(err) return } // fmt.Println(n) scanned := s.Scan() if !scanned { fmt.Println("LongFile", s.Err()) return } temp := s.Text() var in = make([]int, n) // fmt.Println(temp) for i, sv := range strings.Split(temp, " ") { v, _ := strconv.Atoi(sv) in[i] = v } fmt.Println(minAbsDiff(in)) } func minAbsDiff(copy []int) int { // copy := make([]int, len(in)) // for i, v := range in { // copy[i] = int(math.Abs(float64(v))) // } // sort.Ints(copy) var min = math.MaxInt32 for i := 0; i < len(copy)-2; i++ { diff := copy[i] - copy[i+1] diff = int(math.Abs(float64(diff))) if diff == 0 { fmt.Println(i, copy[i+1], copy[i]) } if diff < min { min = diff } } return min }
package goauth import "time" // testClient implements the Client interface and is // intended for use only in testing. type testClient struct { ID string secret string username string redirectURI string scope []string } // AllowStrategy satisfies the Client interface, returning true if the client is approved for the // provided Strategy func (t *testClient) AllowStrategy(s Strategy) bool { return true } // AuthorizeScope satisfies the Client interface, returning an approved scope for the client. func (t *testClient) AuthorizeScope(scope []string) ([]string, error) { var approvedScope []string for _, requestedScope := range scope { for _, allowedScope := range t.scope { if allowedScope == requestedScope { approvedScope = append(approvedScope, requestedScope) } } } return approvedScope, nil } // AllowRedirectURI satisfies the Client interface, returning an bool indicating whether the // redirect uri is allowed. func (t *testClient) AllowRedirectURI(uri string) bool { if uri != t.redirectURI { return false } return true } // AuthorizeResourceOwner satisfies the Client interface, return an error if the provided resource owner // username is not allowed or is invalid. func (t *testClient) AuthorizeResourceOwner(username string) (bool, error) { if t.username != username { return false, nil } return true, nil } func (t *testClient) CreateGrant(scope []string) (Grant, error) { return Grant{ AccessToken: "testtoken", ExpiresIn: time.Second * 3600, TokenType: TokenTypeBearer, RefreshToken: "testtoken", Scope: scope, CreatedAt: time.Now(), }, nil }
package chunk import ( "encoding/binary" "io" "github.com/tombell/go-serato/internal/decode" ) // Vrsn is a chunk that contains the version of the Serato session file format. type Vrsn struct { header *Header data []byte } // Header returns the header for the chunk. func (v *Vrsn) Header() *Header { return v.header } // Type returns the type of the chunk. func (v *Vrsn) Type() string { return v.header.Type() } // Version returns the version string of the Serato session file format. func (v *Vrsn) Version() string { return decode.UTF16(v.data) } // NewVrsnChunk returns an initialised Vrsn chunk, using the header to read the // chunk data. func NewVrsnChunk(header *Header, r io.Reader) (*Vrsn, error) { if header.Type() != vrsnID { return nil, ErrUnexpectedIdentifier } data := make([]byte, header.Length) if err := binary.Read(r, binary.BigEndian, &data); err != nil { return nil, err } return &Vrsn{ header: header, data: data[:], }, nil }
package main type DataPoint interface { GetValue(attributeName string) Attribute //gets an attribute based on the name of the attribute given SetValue(attributeName string, valToSet Attribute) error //sets the attribute value, throws an error if they aren't the right types GetAttributeValues(targetName string) map[string]Attribute //a map of the name of the attribute to the attribute itself, excluding the target } type Attribute struct { Value interface{} Type string //the type can either be int or anything else. If its anything else we need to use its comparer, that is the method in which we can compare this value to others of the same class } func createFloatAttribute(input float64) Attribute { return createAttribute(input,FloatType) } func createBinaryAttribute(input string) Attribute { return createAttribute(input,BinaryType) } func createAttribute(input interface{}, inputType string) Attribute { a := new(Attribute) a.Value = input a.Type = inputType return *a }
package dbsrv import ( "github.com/empirefox/esecend/front" "github.com/empirefox/reform" ) func (dbs *DbService) ProductsFillResponse(products ...reform.Struct) (*front.ProductsResponse, error) { if len(products) == 0 { return nil, reform.ErrNoRows } var ids []interface{} for _, p := range products { ids = append(ids, p.(*front.Product).ID) } skus, err := dbs.GetDB().FindAllFrom(front.SkuTable, "$ProductID", ids...) if err != nil { return nil, err } var attrIds []reform.Struct if len(skus) != 0 { ids = nil for _, sku := range skus { ids = append(ids, sku.(*front.Sku).ID) } attrIds, err = dbs.GetDB().FindAllFrom(front.ProductAttrIdTable, "$SkuID", ids...) if err != nil { return nil, err } } return &front.ProductsResponse{ Products: products, Skus: skus, Attrs: attrIds, }, nil }
package Problem0461 import ( "fmt" "testing" "github.com/stretchr/testify/assert" ) // tcs is testcase slice var tcs = []struct { x int y int ans int }{ { 3, 1, 1, }, { 1, 4, 2, }, // 可以有多个 testcase } func Test_hammingDistance(t *testing.T) { ast := assert.New(t) for _, tc := range tcs { fmt.Printf("~~%v~~\n", tc) ast.Equal(tc.ans, hammingDistance(tc.x, tc.y), "输入:%v", tc) } } func Benchmark_hammingDistance(b *testing.B) { for i := 0; i < b.N; i++ { for _, tc := range tcs { hammingDistance(tc.x, tc.y) } } }
// Code generated from Cypher.g4 by ANTLR 4.7.2. DO NOT EDIT. package parser // Cypher import "github.com/antlr/antlr4/runtime/Go/antlr" // A complete Visitor for a parse tree produced by CypherParser. type CypherVisitor interface { antlr.ParseTreeVisitor // Visit a parse tree produced by CypherParser#oC_Cypher. VisitOC_Cypher(ctx *OC_CypherContext) interface{} // Visit a parse tree produced by CypherParser#oC_Statement. VisitOC_Statement(ctx *OC_StatementContext) interface{} // Visit a parse tree produced by CypherParser#oC_Query. VisitOC_Query(ctx *OC_QueryContext) interface{} // Visit a parse tree produced by CypherParser#oC_RegularQuery. VisitOC_RegularQuery(ctx *OC_RegularQueryContext) interface{} // Visit a parse tree produced by CypherParser#oC_Union. VisitOC_Union(ctx *OC_UnionContext) interface{} // Visit a parse tree produced by CypherParser#oC_SingleQuery. VisitOC_SingleQuery(ctx *OC_SingleQueryContext) interface{} // Visit a parse tree produced by CypherParser#oC_SinglePartQuery. VisitOC_SinglePartQuery(ctx *OC_SinglePartQueryContext) interface{} // Visit a parse tree produced by CypherParser#oC_MultiPartQuery. VisitOC_MultiPartQuery(ctx *OC_MultiPartQueryContext) interface{} // Visit a parse tree produced by CypherParser#oC_UpdatingClause. VisitOC_UpdatingClause(ctx *OC_UpdatingClauseContext) interface{} // Visit a parse tree produced by CypherParser#oC_ReadingClause. VisitOC_ReadingClause(ctx *OC_ReadingClauseContext) interface{} // Visit a parse tree produced by CypherParser#oC_Match. VisitOC_Match(ctx *OC_MatchContext) interface{} // Visit a parse tree produced by CypherParser#oC_Unwind. VisitOC_Unwind(ctx *OC_UnwindContext) interface{} // Visit a parse tree produced by CypherParser#oC_Merge. VisitOC_Merge(ctx *OC_MergeContext) interface{} // Visit a parse tree produced by CypherParser#oC_MergeAction. VisitOC_MergeAction(ctx *OC_MergeActionContext) interface{} // Visit a parse tree produced by CypherParser#oC_Create. VisitOC_Create(ctx *OC_CreateContext) interface{} // Visit a parse tree produced by CypherParser#oC_Set. VisitOC_Set(ctx *OC_SetContext) interface{} // Visit a parse tree produced by CypherParser#oC_SetItem. VisitOC_SetItem(ctx *OC_SetItemContext) interface{} // Visit a parse tree produced by CypherParser#oC_Delete. VisitOC_Delete(ctx *OC_DeleteContext) interface{} // Visit a parse tree produced by CypherParser#oC_Remove. VisitOC_Remove(ctx *OC_RemoveContext) interface{} // Visit a parse tree produced by CypherParser#oC_RemoveItem. VisitOC_RemoveItem(ctx *OC_RemoveItemContext) interface{} // Visit a parse tree produced by CypherParser#oC_InQueryCall. VisitOC_InQueryCall(ctx *OC_InQueryCallContext) interface{} // Visit a parse tree produced by CypherParser#oC_StandaloneCall. VisitOC_StandaloneCall(ctx *OC_StandaloneCallContext) interface{} // Visit a parse tree produced by CypherParser#oC_YieldItems. VisitOC_YieldItems(ctx *OC_YieldItemsContext) interface{} // Visit a parse tree produced by CypherParser#oC_YieldItem. VisitOC_YieldItem(ctx *OC_YieldItemContext) interface{} // Visit a parse tree produced by CypherParser#oC_With. VisitOC_With(ctx *OC_WithContext) interface{} // Visit a parse tree produced by CypherParser#oC_Return. VisitOC_Return(ctx *OC_ReturnContext) interface{} // Visit a parse tree produced by CypherParser#oC_ProjectionBody. VisitOC_ProjectionBody(ctx *OC_ProjectionBodyContext) interface{} // Visit a parse tree produced by CypherParser#oC_ProjectionItems. VisitOC_ProjectionItems(ctx *OC_ProjectionItemsContext) interface{} // Visit a parse tree produced by CypherParser#oC_ProjectionItem. VisitOC_ProjectionItem(ctx *OC_ProjectionItemContext) interface{} // Visit a parse tree produced by CypherParser#oC_Order. VisitOC_Order(ctx *OC_OrderContext) interface{} // Visit a parse tree produced by CypherParser#oC_Skip. VisitOC_Skip(ctx *OC_SkipContext) interface{} // Visit a parse tree produced by CypherParser#oC_Limit. VisitOC_Limit(ctx *OC_LimitContext) interface{} // Visit a parse tree produced by CypherParser#oC_SortItem. VisitOC_SortItem(ctx *OC_SortItemContext) interface{} // Visit a parse tree produced by CypherParser#oC_Where. VisitOC_Where(ctx *OC_WhereContext) interface{} // Visit a parse tree produced by CypherParser#oC_Pattern. VisitOC_Pattern(ctx *OC_PatternContext) interface{} // Visit a parse tree produced by CypherParser#oC_PatternPart. VisitOC_PatternPart(ctx *OC_PatternPartContext) interface{} // Visit a parse tree produced by CypherParser#oC_AnonymousPatternPart. VisitOC_AnonymousPatternPart(ctx *OC_AnonymousPatternPartContext) interface{} // Visit a parse tree produced by CypherParser#oC_PatternElement. VisitOC_PatternElement(ctx *OC_PatternElementContext) interface{} // Visit a parse tree produced by CypherParser#oC_NodePattern. VisitOC_NodePattern(ctx *OC_NodePatternContext) interface{} // Visit a parse tree produced by CypherParser#oC_PatternElementChain. VisitOC_PatternElementChain(ctx *OC_PatternElementChainContext) interface{} // Visit a parse tree produced by CypherParser#oC_RelationshipPattern. VisitOC_RelationshipPattern(ctx *OC_RelationshipPatternContext) interface{} // Visit a parse tree produced by CypherParser#oC_RelationshipDetail. VisitOC_RelationshipDetail(ctx *OC_RelationshipDetailContext) interface{} // Visit a parse tree produced by CypherParser#oC_Properties. VisitOC_Properties(ctx *OC_PropertiesContext) interface{} // Visit a parse tree produced by CypherParser#oC_RelationshipTypes. VisitOC_RelationshipTypes(ctx *OC_RelationshipTypesContext) interface{} // Visit a parse tree produced by CypherParser#oC_NodeLabels. VisitOC_NodeLabels(ctx *OC_NodeLabelsContext) interface{} // Visit a parse tree produced by CypherParser#oC_NodeLabel. VisitOC_NodeLabel(ctx *OC_NodeLabelContext) interface{} // Visit a parse tree produced by CypherParser#oC_RangeLiteral. VisitOC_RangeLiteral(ctx *OC_RangeLiteralContext) interface{} // Visit a parse tree produced by CypherParser#oC_LabelName. VisitOC_LabelName(ctx *OC_LabelNameContext) interface{} // Visit a parse tree produced by CypherParser#oC_RelTypeName. VisitOC_RelTypeName(ctx *OC_RelTypeNameContext) interface{} // Visit a parse tree produced by CypherParser#oC_Expression. VisitOC_Expression(ctx *OC_ExpressionContext) interface{} // Visit a parse tree produced by CypherParser#oC_OrExpression. VisitOC_OrExpression(ctx *OC_OrExpressionContext) interface{} // Visit a parse tree produced by CypherParser#oC_XorExpression. VisitOC_XorExpression(ctx *OC_XorExpressionContext) interface{} // Visit a parse tree produced by CypherParser#oC_AndExpression. VisitOC_AndExpression(ctx *OC_AndExpressionContext) interface{} // Visit a parse tree produced by CypherParser#oC_NotExpression. VisitOC_NotExpression(ctx *OC_NotExpressionContext) interface{} // Visit a parse tree produced by CypherParser#oC_ComparisonExpression. VisitOC_ComparisonExpression(ctx *OC_ComparisonExpressionContext) interface{} // Visit a parse tree produced by CypherParser#oC_AddOrSubtractExpression. VisitOC_AddOrSubtractExpression(ctx *OC_AddOrSubtractExpressionContext) interface{} // Visit a parse tree produced by CypherParser#oC_MultiplyDivideModuloExpression. VisitOC_MultiplyDivideModuloExpression(ctx *OC_MultiplyDivideModuloExpressionContext) interface{} // Visit a parse tree produced by CypherParser#oC_PowerOfExpression. VisitOC_PowerOfExpression(ctx *OC_PowerOfExpressionContext) interface{} // Visit a parse tree produced by CypherParser#oC_UnaryAddOrSubtractExpression. VisitOC_UnaryAddOrSubtractExpression(ctx *OC_UnaryAddOrSubtractExpressionContext) interface{} // Visit a parse tree produced by CypherParser#oC_StringListNullOperatorExpression. VisitOC_StringListNullOperatorExpression(ctx *OC_StringListNullOperatorExpressionContext) interface{} // Visit a parse tree produced by CypherParser#oC_ListOperatorExpression. VisitOC_ListOperatorExpression(ctx *OC_ListOperatorExpressionContext) interface{} // Visit a parse tree produced by CypherParser#oC_StringOperatorExpression. VisitOC_StringOperatorExpression(ctx *OC_StringOperatorExpressionContext) interface{} // Visit a parse tree produced by CypherParser#oC_NullOperatorExpression. VisitOC_NullOperatorExpression(ctx *OC_NullOperatorExpressionContext) interface{} // Visit a parse tree produced by CypherParser#oC_PropertyOrLabelsExpression. VisitOC_PropertyOrLabelsExpression(ctx *OC_PropertyOrLabelsExpressionContext) interface{} // Visit a parse tree produced by CypherParser#oC_Atom. VisitOC_Atom(ctx *OC_AtomContext) interface{} // Visit a parse tree produced by CypherParser#oC_Literal. VisitOC_Literal(ctx *OC_LiteralContext) interface{} // Visit a parse tree produced by CypherParser#oC_BooleanLiteral. VisitOC_BooleanLiteral(ctx *OC_BooleanLiteralContext) interface{} // Visit a parse tree produced by CypherParser#oC_ListLiteral. VisitOC_ListLiteral(ctx *OC_ListLiteralContext) interface{} // Visit a parse tree produced by CypherParser#oC_PartialComparisonExpression. VisitOC_PartialComparisonExpression(ctx *OC_PartialComparisonExpressionContext) interface{} // Visit a parse tree produced by CypherParser#oC_ParenthesizedExpression. VisitOC_ParenthesizedExpression(ctx *OC_ParenthesizedExpressionContext) interface{} // Visit a parse tree produced by CypherParser#oC_RelationshipsPattern. VisitOC_RelationshipsPattern(ctx *OC_RelationshipsPatternContext) interface{} // Visit a parse tree produced by CypherParser#oC_FilterExpression. VisitOC_FilterExpression(ctx *OC_FilterExpressionContext) interface{} // Visit a parse tree produced by CypherParser#oC_IdInColl. VisitOC_IdInColl(ctx *OC_IdInCollContext) interface{} // Visit a parse tree produced by CypherParser#oC_FunctionInvocation. VisitOC_FunctionInvocation(ctx *OC_FunctionInvocationContext) interface{} // Visit a parse tree produced by CypherParser#oC_FunctionName. VisitOC_FunctionName(ctx *OC_FunctionNameContext) interface{} // Visit a parse tree produced by CypherParser#oC_ExplicitProcedureInvocation. VisitOC_ExplicitProcedureInvocation(ctx *OC_ExplicitProcedureInvocationContext) interface{} // Visit a parse tree produced by CypherParser#oC_ImplicitProcedureInvocation. VisitOC_ImplicitProcedureInvocation(ctx *OC_ImplicitProcedureInvocationContext) interface{} // Visit a parse tree produced by CypherParser#oC_ProcedureResultField. VisitOC_ProcedureResultField(ctx *OC_ProcedureResultFieldContext) interface{} // Visit a parse tree produced by CypherParser#oC_ProcedureName. VisitOC_ProcedureName(ctx *OC_ProcedureNameContext) interface{} // Visit a parse tree produced by CypherParser#oC_Namespace. VisitOC_Namespace(ctx *OC_NamespaceContext) interface{} // Visit a parse tree produced by CypherParser#oC_ListComprehension. VisitOC_ListComprehension(ctx *OC_ListComprehensionContext) interface{} // Visit a parse tree produced by CypherParser#oC_PatternComprehension. VisitOC_PatternComprehension(ctx *OC_PatternComprehensionContext) interface{} // Visit a parse tree produced by CypherParser#oC_PropertyLookup. VisitOC_PropertyLookup(ctx *OC_PropertyLookupContext) interface{} // Visit a parse tree produced by CypherParser#oC_CaseExpression. VisitOC_CaseExpression(ctx *OC_CaseExpressionContext) interface{} // Visit a parse tree produced by CypherParser#oC_CaseAlternatives. VisitOC_CaseAlternatives(ctx *OC_CaseAlternativesContext) interface{} // Visit a parse tree produced by CypherParser#oC_Variable. VisitOC_Variable(ctx *OC_VariableContext) interface{} // Visit a parse tree produced by CypherParser#oC_NumberLiteral. VisitOC_NumberLiteral(ctx *OC_NumberLiteralContext) interface{} // Visit a parse tree produced by CypherParser#oC_MapLiteral. VisitOC_MapLiteral(ctx *OC_MapLiteralContext) interface{} // Visit a parse tree produced by CypherParser#oC_Parameter. VisitOC_Parameter(ctx *OC_ParameterContext) interface{} // Visit a parse tree produced by CypherParser#oC_PropertyExpression. VisitOC_PropertyExpression(ctx *OC_PropertyExpressionContext) interface{} // Visit a parse tree produced by CypherParser#oC_PropertyKeyName. VisitOC_PropertyKeyName(ctx *OC_PropertyKeyNameContext) interface{} // Visit a parse tree produced by CypherParser#oC_IntegerLiteral. VisitOC_IntegerLiteral(ctx *OC_IntegerLiteralContext) interface{} // Visit a parse tree produced by CypherParser#oC_DoubleLiteral. VisitOC_DoubleLiteral(ctx *OC_DoubleLiteralContext) interface{} // Visit a parse tree produced by CypherParser#oC_SchemaName. VisitOC_SchemaName(ctx *OC_SchemaNameContext) interface{} // Visit a parse tree produced by CypherParser#oC_ReservedWord. VisitOC_ReservedWord(ctx *OC_ReservedWordContext) interface{} // Visit a parse tree produced by CypherParser#oC_SymbolicName. VisitOC_SymbolicName(ctx *OC_SymbolicNameContext) interface{} // Visit a parse tree produced by CypherParser#oC_LeftArrowHead. VisitOC_LeftArrowHead(ctx *OC_LeftArrowHeadContext) interface{} // Visit a parse tree produced by CypherParser#oC_RightArrowHead. VisitOC_RightArrowHead(ctx *OC_RightArrowHeadContext) interface{} // Visit a parse tree produced by CypherParser#oC_Dash. VisitOC_Dash(ctx *OC_DashContext) interface{} }
package accountdb import( "stockdb" // "util" "fmt" ) const ( Truncate = "truncate table %s" ) type FinancialIndexDB struct{ stockdb.DBBase } func (s *FinancialIndexDB) Create(sqls []string) int { //db := s.Open() for _, sql := range sqls { s.ExecOnce(sql) } return 0 } func (s *FinancialIndexDB) Clear(tables []string) int { sqls := make([]string, 0) for _, table := range tables { sql := fmt.Sprintf(Truncate, table) sqls = append(sqls, sql) } for _, sql := range sqls { s.ExecOnce(sql) } return 0 } func NewFinancialIndexDB(dbname string) *FinancialIndexDB { db := new(FinancialIndexDB) db.Init(dbname) return db }
package tools /* //string到int int,err:=strconv.Atoi(string) //string到int64 int64, err := strconv.ParseInt(string, 10, 64) //int到string string:=strconv.Itoa(int) //int64到string string:=strconv.FormatInt(int64,10) //string到float32(float64) float,err := strconv.ParseFloat(string,32/64) //float到string string := strconv.FormatFloat(float32, 'E', -1, 32) string := strconv.FormatFloat(float64, 'E', -1, 64) // 'b' (-ddddp±ddd,二进制指数) // 'e' (-d.dddde±dd,十进制指数) // 'E' (-d.ddddE±dd,十进制指数) // 'f' (-ddd.dddd,没有指数) // 'g' ('e':大指数,'f':其它情况) // 'G' ('E':大指数,'f':其它情况) */
package main import ( "admigo/common" c "admigo/controllers" "admigo/controllers/api" "github.com/julienschmidt/httprouter" "net/http" ) func getRouter() (router *httprouter.Router) { router = httprouter.New() router.ServeFiles("/static/*filepath", http.Dir(common.Env().Static)) router.GET("/", c.Index) router.GET("/users", c.Users) router.GET("/items", c.Items) router.GET("/shopping", c.Shopping) router.GET("/ico", c.Ico) router.GET("/btc", c.ChartBTC) router.GET("/eth", c.ChartETH) router.GET("/person", c.Person) router.GET("/app", c.App) router.POST("/login", c.Login) router.POST("/logout", c.Logout) router.POST("/signup", c.SignupAccount) router.GET("/confirm/*filepath", c.ConfirmUser) router.POST("/users", api.UsersList) router.GET("/users/:id", api.User) router.DELETE("/users/:id", api.DeleteUser) router.POST("/users/update", api.EditUser) router.GET("/roles", api.RolesList) router.POST("/items", api.ItemsList) router.GET("/items/:id", api.Item) router.POST("/items/update", api.UserCanDo(api.EditItem)) router.DELETE("/items/:id", api.UserCanDo(api.DeleteItem)) router.GET("/eth-prices", api.EthPrices) return }
package _6_datatype_conversion import ( "fmt" "strconv" "testing" ) func TestIntToFloat(t *testing.T) { // 基本数据类型相互转换,不能自动转换,必须强制转换(显式转换) var i = 100 var f float64 = float64(i) t.Logf("i=(%d,%T),f=(%f,%T)\n", i, i, f, f) // i=(100,int),f=(100.000000,float64) } func TestFloatToInt(t *testing.T) { var f = 3.14 var i = int(f) t.Logf("i=(%d,%T),f=(%f,%T)\n", i, i, f, f) // i=(3,int),f=(3.140000,float64) } func TestInt64ToInt8(t *testing.T) { // 在转换中 int64 转成 int8,编译不会报错,只是转换的结果按溢出处理 var i64 int64 = 1234567 var i8 = int8(i64) t.Logf("i64=(%d,%T),i8=(%d,%T)\n", i64, i64, i8, i8) // i64=(1234567,int64),i8=(-121,int8) } func TestToString(t *testing.T) { //基本数据类型与 string 类型相互转换 var i = 100 var f = 3.14 var b = true var c = 'a' t.Log(fmt.Sprintf("%d", i), fmt.Sprintf("%f", f), fmt.Sprintf("%v", b), fmt.Sprintf("%c", c)) } func TestToStringByFunc(t *testing.T) { // 函数转换(基本数据类型转 string 类型) var str string str = strconv.Itoa(100) t.Logf("str type %T str=%q\n", str, str) str = strconv.FormatInt(int64(100), 10) t.Logf("str type %T str=%q\n", str, str) str = strconv.FormatFloat(3.14, 'f', 10, 64) t.Logf("str type %T str=%q\n", str, str) str = strconv.FormatBool(true) t.Logf("str type %T str=%q\n", str, str) } func TestStringToByFunc(t *testing.T) { // 函数转换(string 类型转换基本数据类型) var b bool b, _ = strconv.ParseBool("true") t.Logf("b type %T b=%v\n", b, b) var i64 int64 i64, _ = strconv.ParseInt("123456", 10, 64) t.Logf("i64 type %T i64=%v\n", i64, i64) var f64 float64 f64, _ = strconv.ParseFloat("123.456", 64) t.Logf("f64 type %T f64=%v\n", f64, f64) } func TestError(t *testing.T) { // go 对于不能转换成功的,会转换成零值 i64, err := strconv.ParseInt("hello", 10, 64) if err != nil { t.Log("ParseInt error:", err) // ParseInt error: strconv.ParseInt: parsing "hello": invalid syntax } t.Logf("i64 type %T i64=%v\n", i64, i64) // i64 type int64 i64=0 }
package handler import ( "context" "errors" "time" "github.com/golang/protobuf/ptypes" "github.com/google/uuid" crypto "github.com/jinmukeji/go-pkg/v2/crypto/encrypt/legacy" "github.com/jinmukeji/go-pkg/v2/crypto/rand" "github.com/jinmukeji/jiujiantang-services/jinmuid/mysqldb" bizcorepb "github.com/jinmukeji/proto/v3/gen/micro/idl/partner/xima/core/v1" subscriptionpb "github.com/jinmukeji/proto/v3/gen/micro/idl/partner/xima/subscription/v1" "fmt" jinmuidpb "github.com/jinmukeji/proto/v3/gen/micro/idl/partner/xima/user/v1" ) const ( defaultRegisterSource = "手机验证码注册" defaultRegisterType = "phone" organizationName = "喜马把脉科技有限公司" organizationStreet = "江苏常州天宁区关河东路66号九洲环宇大厦1501室" organizationPhone = "0519-81180075" organizationEmail = "[email protected]" organizationState = "江苏省" organizationCity = "常州市" organizationDistrict = "天宁区" organizationType = "养生" // initNotificationPreference 通知初始状态 initNotificationPreference = true ) // UserSignUpByPhone 手机号注册 func (j *JinmuIDService) UserSignUpByPhone(ctx context.Context, req *jinmuidpb.UserSignUpByPhoneRequest, resp *jinmuidpb.UserSignUpByPhoneResponse) error { // TODO: 注册用户和创建组织要在同一个事务 // 该手机是否注册过 exsit, err := j.datastore.ExistPhone(ctx, req.Phone, req.NationCode) if err != nil { return NewError(ErrDatabase, fmt.Errorf("failed to check the existence of phone %s%s", req.NationCode, req.Phone)) } if exsit { return NewError(ErrExistRegisteredPhone, fmt.Errorf("phone %s%s doesn't exist", req.NationCode, req.Phone)) } isValid, errVerifyVerificationNumberByPhone := j.datastore.VerifyVerificationNumberByPhone(ctx, req.VerificationNumber, req.Phone, req.NationCode) if errVerifyVerificationNumberByPhone != nil { return NewError(ErrDatabase, fmt.Errorf("failed to verify verification number by phone %s%s: %s", req.NationCode, req.Phone, errVerifyVerificationNumberByPhone.Error())) } if !isValid { return NewError(ErrInvalidVerificationNumber, fmt.Errorf("verification number is invalid")) } errSetVerificationNumberAsUsed := j.datastore.SetVerificationNumberAsUsed(ctx, mysqldb.VerificationPhone, req.VerificationNumber) if errSetVerificationNumberAsUsed != nil { return NewError(ErrDatabase, fmt.Errorf("failed to set verification number of email to the status of used %s: %s", req.VerificationNumber, errSetVerificationNumberAsUsed.Error())) } // 判断密码 if req.PlainPassword == "" { return NewError(ErrEmptyPassword, errors.New("password is empty")) } if !checkPasswordFormat(req.PlainPassword) { return NewError(ErrWrongFormatOfPassword, errors.New("password format is wrong")) } seed, _ := rand.RandomStringWithMask(rand.MaskLetterDigits, 4) helper := crypto.NewPasswordCipherHelper() encryptedPassword := helper.Encrypt(req.PlainPassword, seed, j.encryptKey) // 设置语言 language, errmapProtoLanguageToDB := mapProtoLanguageToDB(req.Language) if errmapProtoLanguageToDB != nil { return NewError(ErrInvalidLanguage, errmapProtoLanguageToDB) } mysqlLanguage, errmapLanguageToDB := mapLanguageToDB(language) if errmapLanguageToDB != nil { return NewError(ErrInvalidLanguage, errmapLanguageToDB) } now := time.Now() user := &mysqldb.User{ SigninPhone: req.Phone, HasSetPhone: true, RegisterType: defaultRegisterType, RegisterSource: defaultRegisterSource, NationCode: req.NationCode, RegisterTime: now, LatestUpdatedPhoneAt: &now, IsActivated: true, Language: mysqlLanguage, HasSetLanguage: true, HasSetUserProfile: true, IsProfileCompleted: true, EncryptedPassword: encryptedPassword, Seed: seed, HasSetPassword: true, LatestUpdatedPasswordAt: &now, ActivatedAt: &now, CreatedAt: now, UpdatedAt: now, } birthday, _ := ptypes.Timestamp(req.Profile.BirthdayTime) mysqlGender, errmapProtoGenderToDB := mapProtoGenderToDB(req.Profile.Gender) if errmapProtoGenderToDB != nil { return NewError(ErrInvalidGender, errmapProtoGenderToDB) } profile := &mysqldb.UserProfile{ Nickname: req.Profile.Nickname, NicknameInitial: getNicknameInitial(req.Profile.Nickname), Gender: mysqlGender, Weight: req.Profile.Weight, Height: req.Profile.Height, Birthday: birthday, } errCreateUserAndUserProfile := j.datastore.CreateUserAndUserProfile(ctx, user, profile) if errCreateUserAndUserProfile != nil { return NewError(ErrDatabase, errors.New("fail to create user and user profile")) } errCreateUserPreferences := j.datastore.CreateUserPreferences(ctx, user.UserID) if errCreateUserPreferences != nil { return NewError(ErrDatabase, fmt.Errorf("fail to create user and user preferences of user %d: %s", user.UserID, errCreateUserPreferences.Error())) } token := uuid.New().String() tk, err := j.datastore.CreateToken(ctx, token, user.UserID, TokenAvailableDuration) if err != nil { return NewError(ErrGetAccessTokenFailure, fmt.Errorf("failed to create the access token of user %d: %s", user.UserID, err.Error())) } notificationPreferences := &mysqldb.NotificationPreferences{ UserID: user.UserID, PhoneEnabled: initNotificationPreference, WechatEnabled: initNotificationPreference, WeiboEnabled: initNotificationPreference, PhoneEnabledUpdatedAt: now, WechatEnabledUpdatedAt: now, WeiboEnabledUpdatedAt: now, CreatedAt: now, UpdatedAt: now, } errCreateNotificationPreferences := j.datastore.CreateNotificationPreferences(ctx, notificationPreferences) if errCreateNotificationPreferences != nil { return NewError(ErrDatabase, fmt.Errorf("failed to create notification preferences of user %d: %s", user.UserID, errCreateNotificationPreferences.Error())) } resp.UserId = user.UserID resp.AccessToken = tk.Token // 创建组织 reqCreateOrganizationRequest := new(bizcorepb.OwnerCreateOrganizationRequest) reqCreateOrganizationRequest.Profile = &bizcorepb.OrganizationProfile{ Name: organizationName, Phone: organizationPhone, Type: organizationType, Email: organizationEmail, Address: &bizcorepb.Address{ State: organizationState, Street: organizationStreet, City: organizationCity, District: organizationDistrict, }, } ctx = AddContextToken(ctx, token) _, errOwnerCreateOrganization := j.bizSvc.OwnerCreateOrganization(ctx, reqCreateOrganizationRequest) if errOwnerCreateOrganization != nil { return NewError(ErrDatabase, fmt.Errorf("failed to create organization: %s", errOwnerCreateOrganization.Error())) } reqGetUserSubscriptions := new(subscriptionpb.GetUserSubscriptionsRequest) reqGetUserSubscriptions.UserId = user.UserID // 2.0迁移之前老用户,有没有激活的订阅,自动激活 respGetUserSubscriptions, errGetUserSubscriptions := j.subscriptionSvc.GetUserSubscriptions(ctx, reqGetUserSubscriptions) if errGetUserSubscriptions == nil { for _, item := range respGetUserSubscriptions.Subscriptions { if !item.IsMigratedActivated && !item.Activated { // 激活订阅 reqActivateSubscription := new(subscriptionpb.ActivateSubscriptionRequest) reqActivateSubscription.SubscriptionId = item.SubscriptionId _, errActivateSubscription := j.subscriptionSvc.ActivateSubscription(ctx, reqActivateSubscription) if errActivateSubscription != nil { return errActivateSubscription } } } } return nil } func mapLanguageToDB(language string) (mysqldb.Language, error) { switch language { case LanguageSimpleChinese: return mysqldb.LanguageSimpleChinese, nil case LanguageTraditionalChinese: return mysqldb.LanguageTraditionalChinese, nil case LanguageEnglish: return mysqldb.LanguageEnglish, nil } return mysqldb.LanguageInvalid, fmt.Errorf("invalid string language %s", language) }
package validate /* *********************************************** GlobalOption Struct *********************************************** */ // GlobalOption settings for validate type GlobalOption struct { // FilterTag name in the type tags. FilterTag string // ValidateTag in the type tags. ValidateTag string // StopOnError If true: An error occurs, it will cease to continue to verify StopOnError bool // SkipOnEmpty Skip check on field not exist or value is empty SkipOnEmpty bool // CheckDefault whether validate the default value CheckDefault bool }
// +build varlink,!remoteclient package main import ( "fmt" "net" "os" "path/filepath" "strings" "time" "github.com/containers/libpod/cmd/podman/cliconfig" "github.com/containers/libpod/cmd/podman/libpodruntime" "github.com/containers/libpod/libpod" "github.com/containers/libpod/pkg/adapter" api "github.com/containers/libpod/pkg/api/server" "github.com/containers/libpod/pkg/rootless" "github.com/containers/libpod/pkg/systemd" "github.com/containers/libpod/pkg/util" iopodman "github.com/containers/libpod/pkg/varlink" "github.com/containers/libpod/pkg/varlinkapi" "github.com/containers/libpod/version" "github.com/pkg/errors" "github.com/sirupsen/logrus" "github.com/spf13/cobra" "github.com/varlink/go/varlink" ) var ( serviceCommand cliconfig.ServiceValues serviceDescription = `Run an API service Enable a listening service for API access to Podman commands. ` _serviceCommand = &cobra.Command{ Use: "service [flags] [URI]", Short: "Run API service", Long: serviceDescription, RunE: func(cmd *cobra.Command, args []string) error { serviceCommand.InputArgs = args serviceCommand.GlobalFlags = MainGlobalOpts return serviceCmd(&serviceCommand) }, } ) func init() { serviceCommand.Command = _serviceCommand serviceCommand.SetHelpTemplate(HelpTemplate()) serviceCommand.SetUsageTemplate(UsageTemplate()) flags := serviceCommand.Flags() flags.Int64VarP(&serviceCommand.Timeout, "timeout", "t", 5, "Time until the service session expires in seconds. Use 0 to disable the timeout") flags.BoolVar(&serviceCommand.Varlink, "varlink", false, "Use legacy varlink service instead of REST") } func serviceCmd(c *cliconfig.ServiceValues) error { apiURI, err := resolveApiURI(c) if err != nil { return err } // Create a single runtime api consumption runtime, err := libpodruntime.GetRuntimeDisableFDs(getContext(), &c.PodmanCommand) if err != nil { return errors.Wrapf(err, "error creating libpod runtime") } defer func() { if err := runtime.Shutdown(false); err != nil { fmt.Fprintf(os.Stderr, "Failed to shutdown libpod runtime: %v", err) } }() timeout := time.Duration(c.Timeout) * time.Second if c.Varlink { return runVarlink(runtime, apiURI, timeout, c) } return runREST(runtime, apiURI, timeout) } func resolveApiURI(c *cliconfig.ServiceValues) (string, error) { var apiURI string // When determining _*THE*_ listening endpoint -- // 1) User input wins always // 2) systemd socket activation // 3) rootless honors XDG_RUNTIME_DIR // 4) if varlink -- adapter.DefaultVarlinkAddress // 5) lastly adapter.DefaultAPIAddress if len(c.InputArgs) > 0 { apiURI = c.InputArgs[0] } else if ok := systemd.SocketActivated(); ok { // nolint: gocritic apiURI = "" } else if rootless.IsRootless() { xdg, err := util.GetRuntimeDir() if err != nil { return "", err } socketName := "podman.sock" if c.Varlink { socketName = "io.podman" } socketDir := filepath.Join(xdg, "podman", socketName) if _, err := os.Stat(filepath.Dir(socketDir)); err != nil { if os.IsNotExist(err) { if err := os.Mkdir(filepath.Dir(socketDir), 0755); err != nil { return "", err } } else { return "", err } } apiURI = "unix:" + socketDir } else if c.Varlink { apiURI = adapter.DefaultVarlinkAddress } else { // For V2, default to the REST socket apiURI = adapter.DefaultAPIAddress } if "" == apiURI { logrus.Info("using systemd socket activation to determine API endpoint") } else { logrus.Infof("using API endpoint: %s", apiURI) } return apiURI, nil } func runREST(r *libpod.Runtime, uri string, timeout time.Duration) error { logrus.Warn("This function is EXPERIMENTAL") fmt.Println("This function is EXPERIMENTAL.") var listener *net.Listener if uri != "" { fields := strings.Split(uri, ":") if len(fields) == 1 { return errors.Errorf("%s is an invalid socket destination", uri) } address := strings.Join(fields[1:], ":") l, err := net.Listen(fields[0], address) if err != nil { return errors.Wrapf(err, "unable to create socket %s", uri) } listener = &l } server, err := api.NewServerWithSettings(r, timeout, listener) if err != nil { return err } defer func() { if err := server.Shutdown(); err != nil { fmt.Fprintf(os.Stderr, "Error when stopping service: %s", err) } }() return server.Serve() } func runVarlink(r *libpod.Runtime, uri string, timeout time.Duration, c *cliconfig.ServiceValues) error { var varlinkInterfaces = []*iopodman.VarlinkInterface{varlinkapi.New(c.PodmanCommand.Command, r)} service, err := varlink.NewService( "Atomic", "podman", version.Version, "https://github.com/containers/libpod", ) if err != nil { return errors.Wrapf(err, "unable to create new varlink service") } for _, i := range varlinkInterfaces { if err := service.RegisterInterface(i); err != nil { return errors.Errorf("unable to register varlink interface %v", i) } } // Run the varlink server at the given address if err = service.Listen(uri, timeout); err != nil { switch err.(type) { case varlink.ServiceTimeoutError: logrus.Infof("varlink service expired (use --timeout to increase session time beyond %s ms, 0 means never timeout)", timeout.String()) return nil default: return errors.Wrapf(err, "unable to start varlink service") } } return nil }
package main import ( "errors" "fmt" "github.com/hyperledger/fabric/core/chaincode/shim" ) // AssetsChaincode creates assets type AssetsChaincode struct { } func main() { err := shim.Start(new(AssetsChaincode)) if err != nil { fmt.Printf("Error starting AssetsChaincode chaincode: %s", err) } } // Init is where initialization and resets should happen func (t *AssetsChaincode) Init(stub shim.ChaincodeStubInterface, function string, args []string) ([]byte, error) { if len(args) != 1 { return nil, errors.New("Incorrect number of arguments. Expecting 1") } return nil, nil } // Constructs an asset name. Concantenates the asset name and the transaction id func (t *AssetsChaincode) newAssetName(assetName string, stub shim.ChaincodeStubInterface) string { return fmt.Sprintf("%s-%s", assetName, stub.GetTxID()) } // createAsset creates an asset on the ledger func (t *AssetsChaincode) createAsset(stub shim.ChaincodeStubInterface, args []string) ([]byte, error) { if len(args) != 2 { return nil, errors.New("invalid number of arguments. Expect asset name and asset data") } assetName := t.newAssetName(args[0], stub) err := stub.PutState(assetName, []byte(args[1])) if err != nil { return nil, errors.New("Failed to create asset -> " + args[0]) } return []byte(assetName), nil } // Invoke is our entry point to invoke a chaincode function func (t *AssetsChaincode) Invoke(stub shim.ChaincodeStubInterface, function string, args []string) ([]byte, error) { fmt.Println("invoke is running " + function) switch function { case "init": return t.Init(stub, "init", args) case "create": return t.createAsset(stub, args) } return nil, errors.New("Received unknown function invocation: " + function) } // Get an asset by it's name func (t *AssetsChaincode) getAsset(stub shim.ChaincodeStubInterface, args []string) ([]byte, error) { if len(args) != 1 { return nil, errors.New("invalid number of arguments. Expect asset name") } assetDataBytes, err := stub.GetState(args[0]) if err == nil && len(assetDataBytes) == 0 { return nil, errors.New("asset not found") } return assetDataBytes, err } // Query is our entry point for queries func (t *AssetsChaincode) Query(stub shim.ChaincodeStubInterface, function string, args []string) ([]byte, error) { fmt.Println("query is running " + function) switch function { case "asset": return t.getAsset(stub, args) default: fmt.Println("unhandled query func: " + function) } return nil, errors.New("Received unknown function query: " + function) }
// Copyright 2019-2023 The sakuracloud_exporter Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package platform import ( "context" "errors" "fmt" "sync" "github.com/sacloud/iaas-api-go" "github.com/sacloud/iaas-api-go/types" ) // BillClient calls SakuraCloud bill API type BillClient interface { Read(context.Context) (*iaas.Bill, error) } func getBillClient(caller iaas.APICaller) BillClient { return &billClient{caller: caller} } type billClient struct { caller iaas.APICaller accountID types.ID once sync.Once } func (c *billClient) Read(ctx context.Context) (*iaas.Bill, error) { var err error c.once.Do(func() { var auth *iaas.AuthStatus authStatusOp := iaas.NewAuthStatusOp(c.caller) auth, err = authStatusOp.Read(ctx) if err != nil { return } if !auth.ExternalPermission.PermittedBill() { err = fmt.Errorf("account doesn't have permissions to use the Billing API") } c.accountID = auth.AccountID }) if err != nil { return nil, err } if c.accountID.IsEmpty() { return nil, errors.New("getting AccountID is failed. please check your API Key settings") } billOp := iaas.NewBillOp(c.caller) searched, err := billOp.ByContract(ctx, c.accountID) if err != nil { return nil, err } var bill *iaas.Bill for i := range searched.Bills { b := searched.Bills[i] if i == 0 || bill.Date.Before(b.Date) { bill = b } } return bill, nil }
// Copyright (c) 2019-2020 Tigera, Inc. 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. // Copyright (C) 2022 Cisco Systems 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 watchers import ( "fmt" "os" "sync" "time" log "github.com/sirupsen/logrus" v1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/fields" "k8s.io/client-go/kubernetes" "k8s.io/client-go/tools/cache" ) type secretWatchData struct { // The channel that we should write to when we no longer want this watch stopCh chan struct{} // Secret value secret *v1.Secret } type SecretWatcherClient interface { // this function is invoked upon add|update|delete of a secret OnSecretUpdate(old, new *v1.Secret) } type secretWatcher struct { client SecretWatcherClient namespace string k8sClientset *kubernetes.Clientset mutex sync.Mutex watches map[string]*secretWatchData } func NewSecretWatcher(c SecretWatcherClient, k8sclient *kubernetes.Clientset) (*secretWatcher, error) { sw := &secretWatcher{ client: c, watches: make(map[string]*secretWatchData), k8sClientset: k8sclient, } // Find the namespace we're running in (for the unlikely case where we // are being run in a namespace other than calico-vpp-dataplane) sw.namespace = os.Getenv("NAMESPACE") if sw.namespace == "" { // Default to kube-system. sw.namespace = "calico-vpp-dataplane" } return sw, nil } func (sw *secretWatcher) ensureWatchingSecret(name string) { if _, ok := sw.watches[name]; ok { log.Debugf("Already watching secret '%v' (namespace %v)", name, sw.namespace) } else { log.Debugf("Start a watch for secret '%v' (namespace %v)", name, sw.namespace) // We're not watching this secret yet, so start a watch for it. watcher := cache.NewListWatchFromClient(sw.k8sClientset.CoreV1().RESTClient(), "secrets", sw.namespace, fields.OneTermEqualSelector("metadata.name", name)) _, controller := cache.NewInformer(watcher, &v1.Secret{}, 0, sw) sw.watches[name] = &secretWatchData{stopCh: make(chan struct{})} go controller.Run(sw.watches[name].stopCh) log.Debugf("Controller for secret '%v' is now running", name) // Block for up to 0.5s until the controller has synced. This is just an // optimization to avoid churning the emitted BGP peer config when the secret is // already available. If the secret takes a bit longer to appear, we will cope // with that too, but asynchronously and with some possible BIRD config churn. sw.allowTimeForControllerSync(name, controller, 500*time.Millisecond) } } func (sw *secretWatcher) allowTimeForControllerSync(name string, controller cache.Controller, timeAllowed time.Duration) { sw.mutex.Unlock() defer sw.mutex.Lock() log.Debug("Unlocked") startTime := time.Now() for { // Note: There is a lock associated with the controller's Queue, and HasSynced() // needs to take and release that lock. The same lock is held when the controller // calls our OnAdd, OnUpdate and OnDelete callbacks. if controller.HasSynced() { log.Debugf("Controller for secret '%v' has synced", name) break } else { log.Debugf("Controller for secret '%v' has not synced yet", name) } if time.Since(startTime) > timeAllowed { log.Warningf("Controller for secret '%v' did not sync within %v", name, timeAllowed) break } time.Sleep(100 * time.Millisecond) } log.Debug("Relock...") } func (sw *secretWatcher) GetSecret(name, key string) (string, error) { sw.mutex.Lock() defer sw.mutex.Unlock() log.Debugf("Get secret for name '%v' key '%v'", name, key) // Ensure that we're watching this secret. sw.ensureWatchingSecret(name) // Get and decode the key of interest. if sw.watches[name].secret == nil { return "", fmt.Errorf("No data available for secret %v", name) } if data, ok := sw.watches[name].secret.Data[key]; ok { return string(data), nil } else { return "", fmt.Errorf("Secret %v does not have key %v", name, key) } } func (sw *secretWatcher) OnAdd(obj interface{}) { log.Debug("Secret added") sw.updateSecret(obj.(*v1.Secret)) sw.client.OnSecretUpdate(nil, obj.(*v1.Secret)) } func (sw *secretWatcher) OnUpdate(oldObj, newObj interface{}) { log.Debug("Secret updated") sw.updateSecret(newObj.(*v1.Secret)) sw.client.OnSecretUpdate(oldObj.(*v1.Secret), newObj.(*v1.Secret)) } func (sw *secretWatcher) OnDelete(obj interface{}) { log.Debug("Secret deleted") sw.deleteSecret(obj.(*v1.Secret)) sw.client.OnSecretUpdate(obj.(*v1.Secret), nil) } func (sw *secretWatcher) updateSecret(secret *v1.Secret) { sw.mutex.Lock() defer sw.mutex.Unlock() sw.watches[secret.Name].secret = secret } func (sw *secretWatcher) deleteSecret(secret *v1.Secret) { sw.mutex.Lock() defer sw.mutex.Unlock() sw.watches[secret.Name].secret = nil } func (sw *secretWatcher) SweepStale(activeSecrets map[string]struct{}) { sw.mutex.Lock() defer sw.mutex.Unlock() for name, watchData := range sw.watches { if _, ok := activeSecrets[name]; !ok { log.Debugf("Deleting secret '%s'", name) close(watchData.stopCh) delete(sw.watches, name) } } }
package main import ( "bufio" "fmt" "io" "io/ioutil" "log" "net" "os" "path" "strings" ) func main() { listener, err := net.Listen("tcp", "localhost:2222") if err != nil { log.Fatal(err) } for { conn, err := listener.Accept() if err != nil { log.Print(err) continue } go handleConn(conn) } } func handleConn(c net.Conn) { defer c.Close() io.WriteString(c, "220 Hello\n") scanner := bufio.NewScanner(c) cwd := "." for scanner.Scan() { text := scanner.Text() fmt.Println("Received ", text) command := strings.SplitN(text, " ", 2)[0] command = strings.ToLower(command) switch command { case "close": break case "ls": fileList := getFileList(cwd) for _, filename := range fileList { io.WriteString(c, filename+"\n") } case "get": res := strings.Split(text, " ") if len(res) != 2 { io.WriteString(c, "Invalid input for get") } filename := res[1] file, err := os.Open(path.Join(cwd, filename)) if err != nil { io.WriteString(c, "File not found") } io.Copy(c, file) case "cd": res := strings.Split(text, " ") if len(res) != 2 { io.WriteString(c, "Invalid input for cd") } newPath := res[1] cwd = path.Join(cwd, newPath) case "user": io.WriteString(c, "331 Anonymous login ok") case "pass": io.WriteString(c, "230 Anonymous access granted") case "pwd": io.WriteString(c, "250 CWD command successful") case "epsv": case "pasv": io.WriteString(c, "227 Entering Passive Mode") case "syst": io.WriteString(c, "215 UNIX Type: L8") default: io.WriteString(c, "502 Command not implemented") fmt.Fprintf(os.Stderr, "Invalid command: %s\n", command) } io.WriteString(c, "\n") } } func getFileList(cwd string) []string { var fileList []string files, err := ioutil.ReadDir(cwd) if err != nil { return fileList } for _, file := range files { name := file.Name() if file.IsDir() { name = name + "/" } fileList = append(fileList, name) } return fileList }
package mut import ( "time" ) const defaultMaxRetryTime = time.Second * 60 type retry struct { maxRetryTime time.Duration tempDelay time.Duration retryTime int } func newValidRetry(maxRetryTime time.Duration) *retry { return &retry{ maxRetryTime: maxRetryTime, tempDelay: 0, retryTime: 0, } } func newRetry() *retry { return newValidRetry(defaultMaxRetryTime) } func (r *retry) retryAfter(info interface{}) { if r.tempDelay == 0 { r.tempDelay = 60 * time.Millisecond } else { r.tempDelay *= 2 } if max := r.maxRetryTime; r.tempDelay > max { r.tempDelay = max } logger.Warn("mut# %v retry after %+v ,has retried %d times", info, r.tempDelay, r.retryTime) time.Sleep(r.tempDelay) r.retryTime++ } func (r *retry) reset() { r.tempDelay = 0 }
package scanner import "go/token" // compatible enums const ( eIllegal = int(token.ILLEGAL) tEOF = int(token.EOF) tComment = int(token.COMMENT) tIdentifier = int(token.IDENT) tInt = int(token.INT) tFloat = int(token.FLOAT) tImag = int(token.IMAG) tRune = int(token.CHAR) tString = int(token.STRING) firstOp = tAdd tAdd = int(token.ADD) tSub = int(token.SUB) tMul = int(token.MUL) tQuo = int(token.QUO) tRem = int(token.REM) tAnd = int(token.AND) tOr = int(token.OR) tXor = int(token.XOR) tShl = int(token.SHL) tShr = int(token.SHR) tAndNot = int(token.AND_NOT) tAddAssign = int(token.ADD_ASSIGN) tSubAssign = int(token.SUB_ASSIGN) tMulAssign = int(token.MUL_ASSIGN) tQuoAssign = int(token.QUO_ASSIGN) tRemAssign = int(token.REM_ASSIGN) tAndAssign = int(token.AND_ASSIGN) tOrAssign = int(token.OR_ASSIGN) tXorAssign = int(token.XOR_ASSIGN) tShlAssign = int(token.SHL_ASSIGN) tShrAssign = int(token.SHR_ASSIGN) tAndNotAssign = int(token.AND_NOT_ASSIGN) tLogicAnd = int(token.LAND) tLogicOr = int(token.LOR) tArrow = int(token.ARROW) tInc = int(token.INC) tDec = int(token.DEC) tEqual = int(token.EQL) tLess = int(token.LSS) tGreater = int(token.GTR) tAssign = int(token.ASSIGN) tNot = int(token.NOT) tNotEqual = int(token.NEQ) tLessEqual = int(token.LEQ) tGreaterEqual = int(token.GEQ) tDefine = int(token.DEFINE) tEllipsis = int(token.ELLIPSIS) tLeftParen = int(token.LPAREN) tLeftBrack = int(token.LBRACK) tLeftBrace = int(token.LBRACE) tComma = int(token.COMMA) tPeriod = int(token.PERIOD) tRightParen = int(token.RPAREN) tRightBrack = int(token.RBRACK) tRightBrace = int(token.RBRACE) tSemiColon = int(token.SEMICOLON) tColon = int(token.COLON) lastOp = tColon tBreak = int(token.BREAK) tCase = int(token.CASE) tChan = int(token.CHAN) tConst = int(token.CONST) tContinue = int(token.CONTINUE) tDefault = int(token.DEFAULT) tDefer = int(token.DEFER) tElse = int(token.ELSE) tFallthrough = int(token.FALLTHROUGH) tFor = int(token.FOR) tFunc = int(token.FUNC) tGo = int(token.GO) tGoto = int(token.GOTO) tIf = int(token.IF) tImport = int(token.IMPORT) tInterface = int(token.INTERFACE) tMap = int(token.MAP) tPackage = int(token.PACKAGE) tRange = int(token.RANGE) tReturn = int(token.RETURN) tSelect = int(token.SELECT) tStruct = int(token.STRUCT) tSwitch = int(token.SWITCH) tType = int(token.TYPE) tVar = int(token.VAR) lastGoToken = tVar ) // additional enums const ( // token start tNewline = (lastGoToken + 1) + iota tWhitespace tLineComment tLineCommentEOF tLineCommentInfo tGeneralCommentSL tGeneralCommentML tRawStringLit tInterpretedStringLit // token end // error start // 95 eErrorIllegal eErrorEOF eBOM eBOMInComment eBOMInRune // 100 eBOMInStr eNUL eNULInStr eEscape eBigU eEscapeUnknown eHexLit eIncompleteComment eIncompleteRune eIncompleteEscape // 110 eIncompleteStr eIncompleteRawStr eOctalLit eRune eUTF8 eUTF8Rune eUTF8Str // error end )
// Package testkit provides tools for testing Go code. package testkit
package persistence import ( "context" "database/sql" "strings" "github.com/dollarshaveclub/acyl/pkg/models" "github.com/lib/pq" "github.com/pkg/errors" ) var _ HelmDataLayer = &PGLayer{} func (pg *PGLayer) GetHelmReleasesForEnv(ctx context.Context, name string) ([]models.HelmRelease, error) { if isCancelled(ctx) { return nil, errors.Wrap(ctx.Err(), "error getting helm releases for env") } q := `SELECT ` + models.HelmRelease{}.Columns() + ` FROM helm_releases WHERE env_name = $1;` return collectHelmRows(pg.db.QueryContext(ctx, q, name)) } func (pg *PGLayer) UpdateHelmReleaseRevision(ctx context.Context, envname, release, revision string) error { if isCancelled(ctx) { return errors.Wrap(ctx.Err(), "error updating helm relese revision") } q := `UPDATE helm_releases SET revision_sha = $1 WHERE env_name = $2 AND release = $3;` _, err := pg.db.ExecContext(ctx, q, revision, envname, release) return errors.Wrap(err, "error updating helm release") } func (pg *PGLayer) CreateHelmReleasesForEnv(ctx context.Context, releases []models.HelmRelease) error { if isCancelled(ctx) { return errors.Wrap(ctx.Err(), "error creating helm releases for env") } tx, err := pg.db.Begin() if err != nil { return errors.Wrap(err, "error opening txn") } defer tx.Rollback() stmt, err := tx.Prepare(pq.CopyIn("helm_releases", strings.Split(models.HelmRelease{}.InsertColumns(), ",")...)) if err != nil { return errors.Wrap(err, "error preparing statement") } for _, r := range releases { if _, err := stmt.Exec(r.InsertValues()...); err != nil { return errors.Wrap(err, "error executing insert") } } if _, err := stmt.Exec(); err != nil { return errors.Wrap(err, "error doing bulk insert exec") } if err := tx.Commit(); err != nil { return errors.Wrap(err, "error committing txn") } return nil } func (pg *PGLayer) DeleteHelmReleasesForEnv(ctx context.Context, name string) (uint, error) { if isCancelled(ctx) { return 0, errors.Wrap(ctx.Err(), "error deleting helm releases for env") } q := `DELETE FROM helm_releases WHERE env_name = $1;` res, err := pg.db.ExecContext(ctx, q, name) n, _ := res.RowsAffected() return uint(n), err } func collectHelmRows(rows *sql.Rows, err error) ([]models.HelmRelease, error) { var releases []models.HelmRelease if err != nil { if err == sql.ErrNoRows { return nil, nil } return nil, errors.Wrapf(err, "error querying") } defer rows.Close() for rows.Next() { r := models.HelmRelease{} if err := rows.Scan(r.ScanValues()...); err != nil { return nil, errors.Wrap(err, "error scanning row") } releases = append(releases, r) } return releases, nil }
package main // 配置 type Config struct { Debug bool `json:"debug"` //Debug模式 ServerUrl string `json:"serverUrl"` //服务端地址包含端口 Version string `json:"version"` //当前版本 }
package core import ( "context" "github.com/jybbang/go-core-architecture/core" ) type testModel struct { core.Entity Expect int `bson:"expect,omitempty"` } type okCommand struct { Expect int } type errCommand struct { Expect int } func okCommandHandler(ctx context.Context, request interface{}) core.Result { return core.Result{V: request.(*okCommand).Expect} } func errCommandHandler(ctx context.Context, request interface{}) core.Result { return core.Result{E: core.ErrForbiddenAcccess} } type okNotification struct { core.DomainEvent } type errNotification struct { core.DomainEvent } func okNotificationHandler(ctx context.Context, notification interface{}) error { return nil } func errNotificationHandler(ctx context.Context, notification interface{}) error { return core.ErrForbiddenAcccess }
package db import ( "fmt" "math/rand" "reflect" "sort" "testing" "time" "github.com/davecgh/go-spew/spew" "github.com/stretchr/testify/assert" ) func TestMachine(t *testing.T) { conn := New() var m Machine err := conn.Txn(AllTables...).Run(func(db Database) error { m = db.InsertMachine() return nil }) if err != nil { t.FailNow() } if m.ID != 1 || m.Role != None || m.CloudID != "" || m.PublicIP != "" || m.PrivateIP != "" { t.Errorf("Invalid Machine: %s", spew.Sdump(m)) return } old := m m.Role = Worker m.CloudID = "something" m.PublicIP = "1.2.3.4" m.PrivateIP = "5.6.7.8" err = conn.Txn(AllTables...).Run(func(db Database) error { if err := SelectMachineCheck(db, nil, []Machine{old}); err != nil { return err } db.Commit(m) if err := SelectMachineCheck(db, nil, []Machine{m}); err != nil { return err } db.Remove(m) if err := SelectMachineCheck(db, nil, []Machine{}); err != nil { return err } return nil }) if err != nil { t.Error(err.Error()) return } } func TestMachineSelect(t *testing.T) { conn := New() regions := []string{"here", "there", "anywhere", "everywhere"} var machines []Machine conn.Txn(AllTables...).Run(func(db Database) error { for i := 0; i < 4; i++ { m := db.InsertMachine() m.Region = regions[i] db.Commit(m) machines = append(machines, m) } return nil }) err := conn.Txn(AllTables...).Run(func(db Database) error { err := SelectMachineCheck(db, func(m Machine) bool { return m.Region == "there" }, []Machine{machines[1]}) if err != nil { return err } err = SelectMachineCheck(db, func(m Machine) bool { return m.Region != "there" }, []Machine{machines[0], machines[2], machines[3]}) if err != nil { return err } return nil }) if err != nil { t.Error(err.Error()) return } } func TestMachineString(t *testing.T) { m := Machine{} got := m.String() exp := "Machine-0{ }" if got != exp { t.Errorf("\nGot: %s\nExp: %s", got, exp) } m = Machine{ ID: 1, CloudID: "CloudID1234", Provider: "Amazon", Region: "us-west-1", Size: "m4.large", PublicIP: "1.2.3.4", PrivateIP: "5.6.7.8", DiskSize: 56, Connected: true, } got = m.String() exp = "Machine-1{Amazon us-west-1 m4.large, CloudID1234, PublicIP=1.2.3.4," + " PrivateIP=5.6.7.8, Disk=56GB, Connected}" if got != exp { t.Errorf("\nGot: %s\nExp: %s", got, exp) } } func TestContainerString(t *testing.T) { c := Container{} got := c.String() exp := "Container-0{run }" assert.Equal(t, got, exp) fakeMap := make(map[string]string) fakeMap["test"] = "tester" fakeTime := time.Now() fakeTimeString := fakeTime.String() c = Container{ ID: 1, IP: "1.2.3.4", Minion: "Test", EndpointID: "TestEndpoint", StitchID: "1", DockerID: "DockerID", Image: "test/test", Status: "testing", Command: []string{"run", "/bin/sh"}, Labels: []string{"label1"}, Env: fakeMap, Created: fakeTime, } exp = "Container-1{run test/test run /bin/sh, DockerID: DockerID, " + "Minion: Test, StitchID: 1, IP: 1.2.3.4, Labels: [label1], " + "Env: map[test:tester], Status: testing, Created: " + fakeTimeString + "}" assert.Equal(t, exp, c.String()) } func TestTxnBasic(t *testing.T) { conn := New() conn.Txn(AllTables...).Run(func(view Database) error { m := view.InsertMachine() m.Provider = "Amazon" view.Commit(m) return nil }) conn.Txn(MachineTable).Run(func(view Database) error { machines := view.SelectFromMachine(func(m Machine) bool { return true }) if len(machines) != 1 { t.Fatal("No machines in DB, should be 1") } if machines[0].Provider != "Amazon" { t.Fatal("Machine provider is not Amazon") } return nil }) } func TestAllTablesNoPanic(t *testing.T) { defer func() { if r := recover(); r != nil { t.Fatal("Transaction panicked on valid transaction") } }() conn := New() conn.Txn(AllTables...).Run(func(view Database) error { view.InsertEtcd() view.InsertLabel() view.InsertMinion() view.InsertMachine() view.InsertCluster() view.InsertPlacement() view.InsertContainer() view.InsertConnection() view.InsertACL() return nil }) } // Transactions should not panic when accessing tables in their allowed set. func TestTxnNoPanic(t *testing.T) { defer func() { if r := recover(); r != nil { t.Fatal("Transaction panicked on valid tables") } }() tr := New().Txn(MachineTable, ClusterTable) tr.Run(func(view Database) error { view.InsertMachine() view.InsertCluster() return nil }) } // Transactions should panic when accessing tables not in their allowed set. func TestTxnPanic(t *testing.T) { defer func() { if r := recover(); r == nil { t.Fatal("Transaction didn't panic on invalid tables") } }() tr := New().Txn(MachineTable, ClusterTable) tr.Run(func(view Database) error { view.InsertEtcd() return nil }) } // Transactions should be able to run concurrently if their table sets do not overlap. // This test is not comprehensive; it is merely a basic check to see is anything // is obviously wrong. func TestTxnConcurrent(t *testing.T) { // Run the deadlock test multiple times to increase the odds of detecting a race // condition for i := 0; i < 10; i++ { checkIndependentTransacts(t) } } // Fails the test when the transactions deadlock. func checkIndependentTransacts(t *testing.T) { transactOneStart := make(chan struct{}) transactTwoDone := make(chan struct{}) done := make(chan struct{}) doneRoutines := make(chan struct{}) defer close(doneRoutines) subTxnOne, subTxnTwo := getRandomTransactions(New()) one := func() { subTxnOne.Run(func(view Database) error { close(transactOneStart) select { case <-transactTwoDone: break case <-doneRoutines: return nil // break out of this if it times out } return nil }) close(done) } two := func() { // Wait for either the first transact to start or for timeout select { case <-transactOneStart: break case <-doneRoutines: return // break out of this if it times out } subTxnTwo.Run(func(view Database) error { return nil }) close(transactTwoDone) } go one() go two() timeout := time.After(time.Second) select { case <-timeout: t.Fatal("Transactions deadlocked") case <-done: return } } // Test that Transactions with overlapping table sets run sequentially. // This test is not comprehensive; it is merely a basic check to see is anything // is obviously wrong. func TestTxnSequential(t *testing.T) { // Run the sequential test multiple times to increase the odds of detecting a // race condition for i := 0; i < 10; i++ { checkTxnSequential(t) } } // Fails the test when the transactions run out of order. func checkTxnSequential(t *testing.T) { subTxnOne, subTxnTwo := getRandomTransactions(New(), pickTwoTables(map[TableType]struct{}{})...) done := make(chan struct{}) defer close(done) results := make(chan int) defer close(results) oneStarted := make(chan struct{}) one := func() { subTxnOne.Run(func(view Database) error { close(oneStarted) time.Sleep(100 * time.Millisecond) select { case results <- 1: return nil case <-done: return nil } }) } two := func() { subTxnTwo.Run(func(view Database) error { select { case results <- 2: return nil case <-done: return nil } }) } check := make(chan bool) defer close(check) go func() { first := <-results second := <-results check <- (first == 1 && second == 2) }() go one() <-oneStarted go two() timeout := time.After(time.Second) select { case <-timeout: t.Fatal("Transactions timed out") case success := <-check: if !success { t.Fatal("Transactions ran concurrently") } } } func getRandomTransactions(conn Conn, tables ...TableType) (Transaction, Transaction) { taken := map[TableType]struct{}{} firstTables := pickTwoTables(taken) secondTables := pickTwoTables(taken) firstTables = append(firstTables, tables...) secondTables = append(secondTables, tables...) return conn.Txn(firstTables...), conn.Txn(secondTables...) } func pickTwoTables(taken map[TableType]struct{}) []TableType { tableCount := int32(len(AllTables)) chosen := []TableType{} for len(chosen) < 2 { tt := AllTables[rand.Int31n(tableCount)] if _, ok := taken[tt]; ok { continue } taken[tt] = struct{}{} chosen = append(chosen, tt) } return chosen } func TestTrigger(t *testing.T) { conn := New() mt := conn.Trigger(MachineTable) mt2 := conn.Trigger(MachineTable) ct := conn.Trigger(ClusterTable) ct2 := conn.Trigger(ClusterTable) triggerNoRecv(t, mt) triggerNoRecv(t, mt2) triggerNoRecv(t, ct) triggerNoRecv(t, ct2) err := conn.Txn(AllTables...).Run(func(db Database) error { db.InsertMachine() return nil }) if err != nil { t.Fail() return } triggerRecv(t, mt) triggerRecv(t, mt2) triggerNoRecv(t, ct) triggerNoRecv(t, ct2) mt2.Stop() err = conn.Txn(AllTables...).Run(func(db Database) error { db.InsertMachine() return nil }) if err != nil { t.Fail() return } triggerRecv(t, mt) triggerNoRecv(t, mt2) mt.Stop() ct.Stop() ct2.Stop() fast := conn.TriggerTick(1, MachineTable) triggerRecv(t, fast) triggerRecv(t, fast) triggerRecv(t, fast) } func TestTriggerTickStop(t *testing.T) { conn := New() mt := conn.TriggerTick(100, MachineTable) // The initial tick. triggerRecv(t, mt) triggerNoRecv(t, mt) err := conn.Txn(AllTables...).Run(func(db Database) error { db.InsertMachine() return nil }) if err != nil { t.Fail() return } triggerRecv(t, mt) mt.Stop() err = conn.Txn(AllTables...).Run(func(db Database) error { db.InsertMachine() return nil }) if err != nil { t.Fail() return } triggerNoRecv(t, mt) } func triggerRecv(t *testing.T, trig Trigger) { select { case <-trig.C: case <-time.Tick(5 * time.Second): t.Error("Expected Receive") } } func triggerNoRecv(t *testing.T, trig Trigger) { select { case <-trig.C: t.Error("Unexpected Receive") case <-time.Tick(25 * time.Millisecond): } } func SelectMachineCheck(db Database, do func(Machine) bool, expected []Machine) error { query := db.SelectFromMachine(do) sort.Sort(mSort(expected)) sort.Sort(mSort(query)) if !reflect.DeepEqual(expected, query) { return fmt.Errorf("unexpected query result: %s\nExpected %s", spew.Sdump(query), spew.Sdump(expected)) } return nil } type prefixedString struct { prefix string str string } func (ps prefixedString) String() string { return ps.prefix + ps.str } type testStringerRow struct { ID int FieldOne string FieldTwo int `rowStringer:"omit"` FieldThree int `rowStringer:"three: %s"` FieldFour prefixedString FieldFive int } func (r testStringerRow) String() string { return "" } func (r testStringerRow) getID() int { return -1 } func (r testStringerRow) less(arg row) bool { return true } func TestStringer(t *testing.T) { testRow := testStringerRow{ ID: 5, FieldOne: "one", FieldThree: 3, // Should always omit. FieldTwo: 2, // Should evaluate String() method. FieldFour: prefixedString{"pre", "foo"}, // Should omit because value is zero value. FieldFive: 0, } exp := "testStringerRow-5{FieldOne=one, three: 3, FieldFour=prefoo}" actual := defaultString(testRow) if exp != actual { t.Errorf("Bad defaultStringer output: expected %q, got %q.", exp, actual) } } func TestSliceHelpers(t *testing.T) { containers := []Container{ {StitchID: "3"}, {StitchID: "5"}, {StitchID: "5"}, {StitchID: "1"}, } expected := []Container{ {StitchID: "1"}, {StitchID: "3"}, {StitchID: "5"}, {StitchID: "5"}, } sort.Sort(ContainerSlice(containers)) assert.Equal(t, expected, containers) assert.Equal(t, containers[0], ContainerSlice(containers).Get(0)) labels := []Label{{Label: "b"}, {Label: "a"}} expLabels := []Label{{Label: "a"}, {Label: "b"}} sort.Sort(LabelSlice(labels)) assert.Equal(t, expLabels, labels) assert.Equal(t, labels[0], LabelSlice(labels).Get(0)) conns := []Connection{{ID: 2}, {ID: 1}} expConns := []Connection{{ID: 1}, {ID: 2}} sort.Sort(ConnectionSlice(conns)) assert.Equal(t, expConns, conns) assert.Equal(t, conns[0], ConnectionSlice(conns).Get(0)) } func TestGetClusterNamespace(t *testing.T) { conn := New() ns, err := conn.GetClusterNamespace() assert.NotNil(t, err) assert.Exactly(t, ns, "") conn.Txn(AllTables...).Run(func(view Database) error { clst := view.InsertCluster() clst.Namespace = "test" view.Commit(clst) return nil }) ns, err = conn.GetClusterNamespace() assert.NoError(t, err) assert.Exactly(t, ns, "test") } type mSort []Machine func (machines mSort) sort() { sort.Stable(machines) } func (machines mSort) Len() int { return len(machines) } func (machines mSort) Swap(i, j int) { machines[i], machines[j] = machines[j], machines[i] } func (machines mSort) Less(i, j int) bool { return machines[i].ID < machines[j].ID }
package entity import ( "reflect" "time" ) type ArticleTagEntity struct { Id int64 `mysql:"id" redis:"id" json:"Id"` ArticleId int64 `mysql:"article_id" redis:"article_id" json:"ArticleId"` TagId int64 `mysql:"tag_id" redis:"tag_id" json:"TagId"` CreatedTime time.Time `mysql:"created_time" redis:"created_time" json:"CreatedTime"` UpdatedTime time.Time `mysql:"updated_time" redis:"updated_time" json:"UpdatedTime"` } var ArticleTagEntityType = reflect.TypeOf(ArticleTagEntity{})
package main import ( "fmt" "gee" "net/http" ) func indexHandler(c *gee.Context) { fmt.Fprintf(c.Writer, "URL.Path = %q\n", c.Req.URL.Path) } func helloHandler(c *gee.Context) { for k, v := range c.Req.Header { fmt.Fprintf(c.Writer, "Header[%q] = %q\n", k, v) } } func main() { r := gee.New() r.Use(gee.Recovery()) r.Use(gee.Logger()) r.GET("/", indexHandler) r.GET("/hello", helloHandler) r.GET("/hello/:name", func(c *gee.Context) { c.String(http.StatusOK, "hello %s, you are at %s\n", c.Params["name"], c.Path) }) r.GET("/assets/*filepath", func(c *gee.Context) { c.Json(http.StatusOK, gee.H{"filepath": c.Params["filepath"]}) }) r.GET("/panic", func(c *gee.Context) { names := []string{"aaa", "bbb", "cccc"} c.String(http.StatusOK, names[101]) }) r.Run(":9999") }
package main import ( "encoding/json" "io" "log" "net/http" "os" "strings" "sync" "github.com/PuerkitoBio/goquery" "github.com/syndtr/goleveldb/leveldb" ) func getHTMLPage(url string) *goquery.Document { // Request the HTML page. res, err := http.Get(url) if err != nil { println("ERROR GET") return nil } defer res.Body.Close() if res.StatusCode != 200 { println("ERORR RES STATUS") return nil } // Load the HTML document doc, err := goquery.NewDocumentFromReader(res.Body) if err != nil { return nil } return doc } func (users *Users) getNexURL(doc *goquery.Document) string { nextPageLink, _ := doc.Find("#next-link").Attr("href") print("NEXTPAGE: ") println(nextPageLink) // Trường hợp không có url if nextPageLink == "" { println("End of Category") return "" } return nextPageLink } func (users *Users) getAllUserInformation(doc *goquery.Document, category string, f *os.File, db *leveldb.DB) { var wg sync.WaitGroup doc.Find("a.list-item__link").Each(func(i int, s *goquery.Selection) { userLink, _ := s.Attr("href") wg.Add(1) go users.getUserInformation(userLink, category, &wg, f, db) }) wg.Wait() } func (users *Users) getUserInformation(url string, category string, wg *sync.WaitGroup, f *os.File, db *leveldb.DB) { defer wg.Done() res := getHTMLPage(url) if res == nil { return } userName := res.Find(".user-info__fullname").Text() title := res.Find(".title").Text() time := res.Find(".location-clock__clock").Text() location := res.Find(".location-clock__location").Text() price := res.Find(".price-container__value").Text() phoneNum, _ := res.Find("span[mobile]").Attr("mobile") itemType := res.Find("li.breadcrumb__left-item:last-child").Find("a span").Text() userName = strings.TrimSpace(userName) phoneNum = strings.TrimSpace(phoneNum) title = strings.TrimSpace(title) time = strings.TrimSpace(time) location = strings.TrimSpace(location) price = strings.TrimSpace(price) itemType = strings.TrimSpace(itemType) if len(phoneNum) == 0 { return } splitResult := strings.Split(url, "-") id := splitResult[len(splitResult)-1] // check if id is exist in db or not checkExist := getData(db, id) if len(checkExist) != 0 { println("Exist: " + id) return } println("None_exist: " + id) user := User{ ID: id, PhoneNumber: phoneNum, UserName: userName, Title: title, Time: time, Location: location, Price: price, Type: itemType, } _ = putData(db, id, phoneNum) // convert User to JSON userJSON, err := json.Marshal(user) checkError(err) io.WriteString(f, string(userJSON)+"\n") users.TotalUsers++ users.List = append(users.List, user) } func checkError(err error) { if err != nil { print("Error: ") log.Println(err) } }
package model import "time" type Humidity struct { Id int64 `json:"id"` Value float32 `json:"value"` Timestamp time.Time `json:"timestamp"` } type Humidities []Humidity func (this Humidity) GetId() (int64) { return this.Id } func (this Humidity) GetValue() (float32) { return this.Value } func (this Humidity) GetTimestamp() (time.Time) { return this.Timestamp }
/* Copyright (C) 2021 The Falco Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ /////////////////////////////////////////////////////////////////////////////// // This plugin is a general json parser. It can be used to extract arbitrary // fields from a buffer containing json data. /////////////////////////////////////////////////////////////////////////////// package main import ( "bytes" "encoding/json" "fmt" "io" "io/ioutil" "log" "strings" "github.com/falcosecurity/plugin-sdk-go/pkg/sdk" "github.com/falcosecurity/plugin-sdk-go/pkg/sdk/plugins" "github.com/falcosecurity/plugin-sdk-go/pkg/sdk/plugins/extractor" "github.com/valyala/fastjson" ) // Plugin info const ( PluginRequiredApiVersion = "0.2.0" PluginName = "json" PluginDescription = "implements extracting arbitrary fields from inputs formatted as JSON" PluginContact = "github.com/falcosecurity/plugins/" PluginVersion = "0.1.0" ) const verbose bool = false type MyPlugin struct { plugins.BasePlugin jparser fastjson.Parser jdata *fastjson.Value jdataEvtnum uint64 // The event number jdata refers to. Used to know when we can skip the unmarshaling. } func init() { p := &MyPlugin{} extractor.Register(p) } func (m *MyPlugin) Info() *plugins.Info { return &plugins.Info{ Name: PluginName, Description: PluginDescription, Contact: PluginContact, Version: PluginVersion, RequiredAPIVersion: PluginRequiredApiVersion, } } func (m *MyPlugin) Init(config string) error { if !verbose { log.SetOutput(ioutil.Discard) } log.Printf("[%s] Init, config=%s\n", PluginName, config) return nil } func (m *MyPlugin) Destroy() { log.Printf("[%s] Destroy\n", PluginName) } func (m *MyPlugin) Fields() []sdk.FieldEntry { log.Printf("[%s] Fields\n", PluginName) return []sdk.FieldEntry{ {Type: "string", Name: "json.value", ArgRequired: true, Desc: "Extracts a value from a JSON-encoded input. Syntax is json.value[<json pointer>], where <json pointer> is a json pointer (see https://datatracker.ietf.org/doc/html/rfc6901)"}, {Type: "string", Name: "json.obj", Desc: "The full json message as a text string."}, {Type: "string", Name: "json.rawtime", Desc: "The time of the event, identical to evt.rawtime."}, {Type: "string", Name: "jevt.value", ArgRequired: true, Desc: "Alias for json.value, provided for backwards compatibility."}, {Type: "string", Name: "jevt.obj", Desc: "Alias for json.obj, provided for backwards compatibility."}, {Type: "string", Name: "jevt.rawtime", Desc: "Alias for json.rawtime, provided for backwards compatibility."}, } } func (m *MyPlugin) Extract(req sdk.ExtractRequest, evt sdk.EventReader) error { log.Printf("[%s] Extract\n", PluginName) reader := evt.Reader() // As a very quick sanity check, only try to extract all if // the first character is '{' or '[' data := []byte{0} _, err := reader.Read(data) if err != nil { return err } if !(data[0] == '{' || data[0] == '[') { return fmt.Errorf("invalid json format") } // Decode the json, but only if we haven't done it yet for this event if evt.EventNum() != m.jdataEvtnum { _, err := reader.Seek(0, io.SeekStart) if err != nil { return err } data, err = ioutil.ReadAll(reader) if err != nil { return err } // Try to parse the data as json m.jdata, err = m.jparser.ParseBytes(data) if err != nil { return err } m.jdataEvtnum = evt.EventNum() } switch req.FieldID() { case 3: // jevt.value fallthrough case 0: // json.value arg := req.Arg() if len(arg) == 0 { return fmt.Errorf("value argument is required") } if arg[0] == '/' { arg = arg[1:] } hc := strings.Split(arg, "/") val := m.jdata.Get(hc...) if val == nil { return fmt.Errorf("json key not found: %s", arg) } req.SetValue(string(val.MarshalTo(nil))) case 4: // jevt.obj fallthrough case 1: // json.obj // If we skipped the deserialization, we have to read // the event data. if len(data) == 1 { _, err := reader.Seek(0, io.SeekStart) if err != nil { return err } data, err = ioutil.ReadAll(reader) if err != nil { return err } } var out bytes.Buffer err = json.Indent(&out, data, "", " ") if err != nil { return err } req.SetValue(out.String()) case 5: // jevt.rawtime fallthrough case 2: // json.rawtime req.SetValue(fmt.Sprintf("%d", evt.Timestamp())) default: return fmt.Errorf("no known field: %s", req.Field()) } return nil } func main() { }
package libs import ( "net/http" "github.com/labstack/echo/v4" ) type Api struct{} // 实例化 func NewApi() *Api { return &Api{} } // 接口响应成功 // 200 业务返回成功调用 func (a *Api) Ok(c echo.Context, data interface{}) error { return c.JSON(http.StatusOK, map[string]interface{}{ "code": 0, "msg": "ok", "data": data, }) } // 接口响应失败 // 200 业务返回失败调用,比如参数验证失败 func (a *Api) Fail(c echo.Context, msg string) error { return c.JSON(http.StatusOK, map[string]interface{}{ "code": 10000, "msg": msg, "data": "", }) } // 接口响应异常 // 500 服务器未知错误,比如未知的 error 错误,未知的 panic 错误,这种就需要记录日志报警了 func (a *Api) Error(c echo.Context, err error, code int, message interface{}) error { if err != nil { // 发送报警记录日志 // e.Logger.Error(err) } return c.JSON(code, map[string]interface{}{ "code": 50000, "msg": message.(echo.Map)["message"].(string), "data": message.(echo.Map)["error"].(string), }) }
package model import ( "gopkg.in/mgo.v2/bson" ) type ( Pokemons struct { ID bson.ObjectId `json:"id" bson:"_id,omitempty"` Name string `json:"name" bson:"name"` Element string `json:"element" bson:"element"` Weight string `json:"weight" bson:"weight"` } )
package models import ( "container/list" ) type EventType int const ( EVENT_MESSAGE = iota EVENT_JOIN EVENT_LEAVE ) type Event struct { Type EventType Uid string Timestamp int Content string } const archiveSize = 20 var archive = list.New() // NewEvent add a New Event to archive list func NewEvent(e Event) { if archive.Len() > archiveSize { archive.Remove(archive.Front()) } archive.PushBack(e) } // GetEvent return all event func GetEvent() (events []Event) { //events := make([]Event, 0, archive.Len()) for e := archive.Front(); e != nil; e = e.Next() { v := e.Value.(Event) events = append(events, v) } return }
package main import ( "errors" "fmt" "strconv" ) func numberInput() (int, error) { fmt.Print("Select Number (1 ~ ) : ") var nstr string fmt.Scanf("%s", &nstr) num, err := strconv.ParseUint(nstr, 10, 64) if err != nil { return -1, errors.New("Wrong Number") } return int(num), nil } func Menu(data []string, f func(string) error) error { for i, v := range data { fmt.Println(i+1, ":", v) } var num int var err error num, err = numberInput() if err != nil { return err } else if num == 0 { return nil } else if len(data) <= num-1 { return errors.New("Overwhelm Number") } err = f(data[num-1]) if err != nil { return nil } return nil }
package osbuild2 import ( "bytes" "encoding/json" "reflect" "testing" ) func TestSource_UnmarshalJSON(t *testing.T) { type fields struct { Type string Source Source } type args struct { data []byte } tests := []struct { name string fields fields args args wantErr bool }{ { name: "invalid json", args: args{ data: []byte(`{"name":"org.osbuild.foo","options":{"bar":null}`), }, wantErr: true, }, { name: "unknown source", args: args{ data: []byte(`{"name":"org.osbuild.foo","options":{"bar":null}}`), }, wantErr: true, }, { name: "missing options", args: args{ data: []byte(`{"name":"org.osbuild.curl"}`), }, wantErr: true, }, { name: "missing name", args: args{ data: []byte(`{"foo":null,"options":{"bar":null}}`), }, wantErr: true, }, { name: "curl-empty", fields: fields{ Type: "org.osbuild.curl", Source: &CurlSource{Items: map[string]CurlSourceItem{}}, }, args: args{ data: []byte(`{"org.osbuild.curl":{"items":{}}}`), }, }, { name: "curl-with-secrets", fields: fields{ Type: "org.osbuild.curl", Source: &CurlSource{ Items: map[string]CurlSourceItem{ "checksum1": URLWithSecrets{URL: "url1", Secrets: &URLSecrets{Name: "org.osbuild.rhsm"}}, "checksum2": URLWithSecrets{URL: "url2", Secrets: &URLSecrets{Name: "whatever"}}, }}, }, args: args{ data: []byte(`{"org.osbuild.curl":{"items":{"checksum1":{"url":"url1","secrets":{"name":"org.osbuild.rhsm"}},"checksum2":{"url":"url2","secrets":{"name":"whatever"}}}}}`), }, }, { name: "curl-url-only", fields: fields{ Type: "org.osbuild.curl", Source: &CurlSource{ Items: map[string]CurlSourceItem{ "checksum1": URL("url1"), "checksum2": URL("url2"), }}, }, args: args{ data: []byte(`{"org.osbuild.curl":{"items":{"checksum1":"url1","checksum2":"url2"}}}`), }, }, } for idx, tt := range tests { t.Run(tt.name, func(t *testing.T) { sources := &Sources{ tt.fields.Type: tt.fields.Source, } var gotSources Sources if err := gotSources.UnmarshalJSON(tt.args.data); (err != nil) != tt.wantErr { t.Errorf("Sources.UnmarshalJSON() error = %v, wantErr %v [idx: %d]", err, tt.wantErr, idx) } if tt.wantErr { return } gotBytes, err := json.Marshal(sources) if err != nil { t.Errorf("Could not marshal source: %v [idx: %d]", err, idx) } if !bytes.Equal(gotBytes, tt.args.data) { t.Errorf("Expected '%v', got '%v' [idx: %d]", string(tt.args.data), string(gotBytes), idx) } if !reflect.DeepEqual(&gotSources, sources) { t.Errorf("got '%v', expected '%v' [idx:%d]", &gotSources, sources, idx) } }) } }
package model import ( "database/sql" "fmt" ) type Action struct { ID int `json:"id"` UUID string `json:"uuid"` User string `json:"user"` Device string `json:"device"` Active bool `json:"active"` } func (action *Action) CreateAction(db *sql.DB) error { var active int if action.Active { active = 1 } else { active = 0 } statement := fmt.Sprintf("INSERT INTO Action(uuid, user, device, active) VALUES('%s', '%s', '%s', b'%d')", action.UUID, action.User, action.Device, active) _, err := db.Exec(statement) if err != nil { return err } err = db.QueryRow("SELECT LAST_INSERT_ID()").Scan(&action.ID) if err != nil { return err } return nil }
package AlgoeDB import ( "errors" "regexp" ) func MoreThan(value float64) QueryFunc { return func(target interface{}) bool { number, err := getNumber(target) if err != nil { return false } return number > value } } func MoreThanOrEqual(value float64) QueryFunc { return func(target interface{}) bool { number, err := getNumber(target) if err != nil { return false } return number >= value } } func LessThan(value float64) QueryFunc { return func(target interface{}) bool { number, err := getNumber(target) if err != nil { return false } return number < value } } func LessThanOrEqual(value float64) QueryFunc { return func(target interface{}) bool { number, err := getNumber(target) if err != nil { return false } return number <= value } } func Between(lowValue float64, highValue float64) QueryFunc { return func(target interface{}) bool { number, err := getNumber(target) if err != nil { return false } return number < highValue && number > lowValue } } func BetweenOrEqual(lowValue float64, highValue float64) QueryFunc { return func(target interface{}) bool { number, err := getNumber(target) if err != nil { return false } return number <= highValue && number >= lowValue } } func Exists() QueryFunc { return func(target interface{}) bool { return target != nil } } func Matches(pattern string) QueryFunc { return func(target interface{}) bool { switch x := target.(type) { case string: ok, _ := regexp.MatchString(pattern, x) if ok { return true } return false default: return false } } } func SliceContainsString(item string) QueryFunc { return func(target interface{}) bool { switch x := target.(type) { case []string: for _, value := range x { if item == value { return true } } return false default: return false } } } func And(queryValues ...QueryFunc) QueryFunc { return func(target interface{}) bool { for _, queryValue := range queryValues { if !matchValues(queryValue, target) { return false } } return true } } func Or(queryValues ...QueryFunc) QueryFunc { return func(target interface{}) bool { for _, queryValue := range queryValues { if matchValues(queryValue, target) { return true } } return false } } func Not(queryValue QueryFunc) QueryFunc { return func(target interface{}) bool { return !matchValues(queryValue, target) } } func getNumber(value interface{}) (float64, error) { switch x := value.(type) { case uint8: return float64(x), nil case int8: return float64(x), nil case uint16: return float64(x), nil case int16: return float64(x), nil case uint32: return float64(x), nil case int32: return float64(x), nil case uint64: return float64(x), nil case int64: return float64(x), nil case int: return float64(x), nil case float32: return float64(x), nil case float64: return float64(x), nil default: return 0, errors.New("could not convert number") } }
package parsecsv import ( "bufio" "errors" "fmt" "github.com/IhorBondartsov/csvReader/entity" "os" "sync" ) type Reader interface { StartRead() } type ReaderCfg struct { Result chan entity.PersonData Path string Parser Parser Workers int BufferSize int } func NewReader(cfg ReaderCfg) (Reader, error) { if cfg.Workers == 0 { fmt.Println("Count workers equal 0, no sence to create struct") return nil, errors.New("WORKERS EQUAL 0") } return &reader{ result: cfg.Result, path: cfg.Path, parser: cfg.Parser, workerResp: make(chan string, cfg.BufferSize), }, nil } type reader struct { result chan entity.PersonData path string parser Parser countWorkers int workerResp chan string } func (r *reader) startWorkers(wg *sync.WaitGroup) { for i := 0; i < r.countWorkers; i++ { go r.worker(wg) } } func (r *reader) worker(wg *sync.WaitGroup) { for msg := range r.workerResp { d, e := r.parser.Parse(msg) if e != nil { fmt.Println(e.Error()) } r.result <- d wg.Done() } } func (r *reader) StartRead() { wg := sync.WaitGroup{} r.startWorkers(&wg) file, err := os.Open(r.path) if err != nil { fmt.Println(err.Error()) return } defer file.Close() scanner := bufio.NewScanner(file) for scanner.Scan() { wg.Add(1) x := scanner.Text() r.workerResp <- x } wg.Wait() close(r.result) if err := scanner.Err(); err != nil { fmt.Println(err.Error()) return } }
package _1_合并两个有序链表 type ListNode struct { Next *ListNode Val int } // 21. 合并两个有序链表 https://leetcode-cn.com/problems/merge-two-sorted-lists/ // 输入:l1 = [1,2,4], l2 = [1,3,4] // 输出:[1,1,2,3,4,4] func mergeTwoLists(l1 *ListNode, l2 *ListNode) *ListNode { head := &ListNode{Val: 0, Next: nil} curr := head for l1 != nil && l2 != nil { if l1.Val < l2.Val { curr.Next = &ListNode{ Val: l1.Val, Next: nil, } l1 = l1.Next } else { curr.Next = &ListNode{ Val: l2.Val, Next: nil, } l2 = l2.Next } curr = curr.Next } if l1 != nil { curr.Next = l1 } if l2 != nil { curr.Next = l2 } return head.Next }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. package armhelpers import ( "context" "time" "github.com/Azure/aks-engine/pkg/kubernetes" "github.com/Azure/azure-sdk-for-go/services/authorization/mgmt/2015-07-01/authorization" "github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2019-12-01/compute" "github.com/Azure/azure-sdk-for-go/services/graphrbac/1.6/graphrbac" "github.com/Azure/azure-sdk-for-go/services/preview/msi/mgmt/2015-08-31-preview/msi" "github.com/Azure/azure-sdk-for-go/services/resources/mgmt/2016-06-01/subscriptions" "github.com/Azure/azure-sdk-for-go/services/resources/mgmt/2018-05-01/resources" azStorage "github.com/Azure/azure-sdk-for-go/storage" "github.com/Azure/go-autorest/autorest" ) // ResourceSkusResultPage type ResourceSkusResultPage interface { Next() error NextWithContext(ctx context.Context) (err error) NotDone() bool Response() compute.ResourceSkusResult Values() []compute.ResourceSku } // VirtualMachineListResultPage is an interface for compute.VirtualMachineListResultPage to aid in mocking type VirtualMachineListResultPage interface { Next() error NotDone() bool Response() compute.VirtualMachineListResult Values() []compute.VirtualMachine } // VirtualMachineScaleSetListResultPage is an interface for compute.VirtualMachineScaleSetListResultPage to aid in mocking type VirtualMachineScaleSetListResultPage interface { Next() error NextWithContext(ctx context.Context) (err error) NotDone() bool Response() compute.VirtualMachineScaleSetListResult Values() []compute.VirtualMachineScaleSet } // VirtualMachineScaleSetVMListResultPage is an interface for compute.VirtualMachineScaleSetListResultPage to aid in mocking type VirtualMachineScaleSetVMListResultPage interface { Next() error NextWithContext(ctx context.Context) (err error) NotDone() bool Response() compute.VirtualMachineScaleSetVMListResult Values() []compute.VirtualMachineScaleSetVM } // ProviderListResultPage is an interface for resources.ProviderListResultPage to aid in mocking type ProviderListResultPage interface { Next() error NextWithContext(ctx context.Context) (err error) NotDone() bool Response() resources.ProviderListResult Values() []resources.Provider } // DeploymentOperationsListResultPage is an interface for resources.DeploymentOperationsListResultPage to aid in mocking type DeploymentOperationsListResultPage interface { Next() error NotDone() bool Response() resources.DeploymentOperationsListResult Values() []resources.DeploymentOperation } // RoleAssignmentListResultPage is an interface for authorization.RoleAssignmentListResultPage to aid in mocking type RoleAssignmentListResultPage interface { Next() error NotDone() bool Response() authorization.RoleAssignmentListResult Values() []authorization.RoleAssignment } // DiskListPage is an interface for compute.DiskListPage to aid in mocking type DiskListPage interface { Next() error NextWithContext(ctx context.Context) (err error) NotDone() bool Response() compute.DiskList Values() []compute.Disk } // VMImageFetcher is an extension of AKSEngine client allows us to operate on the virtual machine images in the environment type VMImageFetcher interface { // ListVirtualMachineImages return a list of images ListVirtualMachineImages(ctx context.Context, location, publisherName, offer, skus string) (compute.ListVirtualMachineImageResource, error) // GetVirtualMachineImage return a virtual machine image GetVirtualMachineImage(ctx context.Context, location, publisherName, offer, skus, version string) (compute.VirtualMachineImage, error) } // AKSEngineClient is the interface used to talk to an Azure environment. // This interface exposes just the subset of Azure APIs and clients needed for // AKS Engine. type AKSEngineClient interface { //AddAcceptLanguages sets the list of languages to accept on this request AddAcceptLanguages(languages []string) // AddAuxiliaryTokens sets the list of aux tokens to accept on this request AddAuxiliaryTokens(tokens []string) // RESOURCES // DeployTemplate can deploy a template into Azure ARM DeployTemplate(ctx context.Context, resourceGroup, name string, template, parameters map[string]interface{}) (resources.DeploymentExtended, error) // EnsureResourceGroup ensures the specified resource group exists in the specified location EnsureResourceGroup(ctx context.Context, resourceGroup, location string, managedBy *string) (*resources.Group, error) // ListLocations returns all the Azure locations to which AKS Engine can deploy ListLocations(ctx context.Context) (*[]subscriptions.Location, error) // // COMPUTE // ListResourceSkus lists Microsoft.Compute SKUs available for a subscription ListResourceSkus(ctx context.Context, filter string) (ResourceSkusResultPage, error) // ListVirtualMachines lists VM resources ListVirtualMachines(ctx context.Context, resourceGroup string) (VirtualMachineListResultPage, error) // GetVirtualMachine retrieves the specified virtual machine. GetVirtualMachine(ctx context.Context, resourceGroup, name string) (compute.VirtualMachine, error) // RestartVirtualMachine restarts the specified virtual machine. RestartVirtualMachine(ctx context.Context, resourceGroup, name string) error // DeleteVirtualMachine deletes the specified virtual machine. DeleteVirtualMachine(ctx context.Context, resourceGroup, name string) error // ListVirtualMachineScaleSets lists the VMSS resources in the resource group ListVirtualMachineScaleSets(ctx context.Context, resourceGroup string) (VirtualMachineScaleSetListResultPage, error) // RestartVirtualMachineScaleSets restarts the specified VMSS RestartVirtualMachineScaleSets(ctx context.Context, resourceGroup, virtualMachineScaleSet string, instanceIDs *compute.VirtualMachineScaleSetVMInstanceIDs) error // ListVirtualMachineScaleSetVMs lists the virtual machines contained in a VMSS ListVirtualMachineScaleSetVMs(ctx context.Context, resourceGroup, virtualMachineScaleSet string) (VirtualMachineScaleSetVMListResultPage, error) // DeleteVirtualMachineScaleSetVM deletes a VM in a VMSS DeleteVirtualMachineScaleSetVM(ctx context.Context, resourceGroup, virtualMachineScaleSet, instanceID string) error // SetVirtualMachineScaleSetCapacity sets the VMSS capacity SetVirtualMachineScaleSetCapacity(ctx context.Context, resourceGroup, virtualMachineScaleSet string, sku compute.Sku, location string) error // GetAvailabilitySet retrieves the specified VM availability set. GetAvailabilitySet(ctx context.Context, resourceGroup, availabilitySet string) (compute.AvailabilitySet, error) // GetAvailabilitySetFaultDomainCount returns the first platform fault domain count it finds from the // VM availability set IDs provided. GetAvailabilitySetFaultDomainCount(ctx context.Context, resourceGroup string, vmasIDs []string) (int, error) // GetVirtualMachinePowerState returns the virtual machine's PowerState status code GetVirtualMachinePowerState(ctx context.Context, resourceGroup, name string) (string, error) // GetVirtualMachineScaleSetInstancePowerState returns the virtual machine's PowerState status code GetVirtualMachineScaleSetInstancePowerState(ctx context.Context, resourceGroup, name, instanceID string) (string, error) // // STORAGE // GetStorageClient uses SRP to retrieve keys, and then an authenticated client for talking to the specified storage // account. GetStorageClient(ctx context.Context, resourceGroup, accountName string) (AKSStorageClient, error) // // NETWORK // DeleteNetworkInterface deletes the specified network interface. DeleteNetworkInterface(ctx context.Context, resourceGroup, nicName string) error // // GRAPH // CreateGraphAppliction creates an application via the graphrbac client CreateGraphApplication(ctx context.Context, applicationCreateParameters graphrbac.ApplicationCreateParameters) (graphrbac.Application, error) // CreateGraphPrincipal creates a service principal via the graphrbac client CreateGraphPrincipal(ctx context.Context, servicePrincipalCreateParameters graphrbac.ServicePrincipalCreateParameters) (graphrbac.ServicePrincipal, error) CreateApp(ctx context.Context, applicationName, applicationURL string, replyURLs *[]string, requiredResourceAccess *[]graphrbac.RequiredResourceAccess) (result graphrbac.Application, servicePrincipalObjectID, secret string, err error) DeleteApp(ctx context.Context, applicationName, applicationObjectID string) (autorest.Response, error) // User Assigned MSI //CreateUserAssignedID - Creates a user assigned msi. CreateUserAssignedID(location string, resourceGroup string, userAssignedID string) (*msi.Identity, error) // RBAC CreateRoleAssignment(ctx context.Context, scope string, roleAssignmentName string, parameters authorization.RoleAssignmentCreateParameters) (authorization.RoleAssignment, error) CreateRoleAssignmentSimple(ctx context.Context, applicationID, roleID string) error DeleteRoleAssignmentByID(ctx context.Context, roleAssignmentNameID string) (authorization.RoleAssignment, error) ListRoleAssignmentsForPrincipal(ctx context.Context, scope string, principalID string) (RoleAssignmentListResultPage, error) // MANAGED DISKS DeleteManagedDisk(ctx context.Context, resourceGroupName string, diskName string) error ListManagedDisksByResourceGroup(ctx context.Context, resourceGroupName string) (result DiskListPage, err error) GetKubernetesClient(apiserverURL, kubeConfig string, interval, timeout time.Duration) (kubernetes.Client, error) ListProviders(ctx context.Context) (ProviderListResultPage, error) // DEPLOYMENTS // ListDeploymentOperations gets all deployments operations for a deployment. ListDeploymentOperations(ctx context.Context, resourceGroupName string, deploymentName string, top *int32) (result DeploymentOperationsListResultPage, err error) // Log Analytics // EnsureDefaultLogAnalyticsWorkspace ensures the default log analytics exists corresponding to specified location in current subscription EnsureDefaultLogAnalyticsWorkspace(ctx context.Context, resourceGroup, location string) (workspaceResourceID string, err error) // GetLogAnalyticsWorkspaceInfo gets the details about the workspace GetLogAnalyticsWorkspaceInfo(ctx context.Context, workspaceSubscriptionID, workspaceResourceGroup, workspaceName string) (workspaceID string, workspaceKey, workspaceLocation string, err error) // AddContainerInsightsSolution adds container insights solution for the specified log analytics workspace AddContainerInsightsSolution(ctx context.Context, workspaceSubscriptionID, workspaceResourceGroup, workspaceName, workspaceLocation string) (result bool, err error) } // AKSStorageClient interface models the azure storage client type AKSStorageClient interface { // DeleteBlob deletes the specified blob in the specified container. DeleteBlob(containerName, blobName string, options *azStorage.DeleteBlobOptions) error // CreateContainer creates the CloudBlobContainer if it does not exist CreateContainer(containerName string, options *azStorage.CreateContainerOptions) (bool, error) // SaveBlockBlob initializes a block blob by taking the byte SaveBlockBlob(containerName, blobName string, b []byte, options *azStorage.PutBlobOptions) error }
package main import ( "bytes" "encoding/json" "fmt" "io/ioutil" "net/http" "os" "path/filepath" "text/template" "filippo.io/age" "github.com/glassechidna/actions2aws" "github.com/pkg/errors" ) func main() { //exitEarlyOnForks() switch os.Args[1] { case "keygen": keygen() case "request": request() default: panic("unexpected subcmd") } } func exitEarlyOnForks() { body, err := ioutil.ReadFile(os.Getenv("GITHUB_EVENT_PATH")) if err != nil { panic(err) } event := struct { PR struct { Head struct { Repo struct { ID int `json:"id"` } `json:"repo"` } `json:"head"` Base struct { Repo struct { ID int `json:"id"` } `json:"repo"` } `json:"base"` } `json:"pull_request"` }{} err = json.Unmarshal(body, &event) if err != nil { panic(err) } } func request() { payload := actions2aws.RequestPayload{ Repo: os.Getenv("GITHUB_REPOSITORY"), RunId: os.Getenv("GITHUB_RUN_ID"), JobName: os.Getenv("GITHUB_JOB"), RoleARN: os.Getenv("ACTIONS2AWS_ROLE"), StepName: os.Getenv("ACTIONS2AWS_STEP_NAME"), } j, _ := json.Marshal(payload) req, err := http.NewRequest("POST", os.Getenv("ACTIONS2AWS_URL"), bytes.NewReader(j)) if err != nil { panic(err) } req.Header.Set("Content-Type", "application/json") resp, err := http.DefaultClient.Do(req) if err != nil { panic(err) } if resp.StatusCode != 200 { panic(errors.New("unexpected status code")) } identity := decryptor() r, err := age.Decrypt(resp.Body, identity) if err != nil { panic(err) } decrypted, err := ioutil.ReadAll(r) if err != nil { panic(err) } apiResp := actions2aws.ResponsePayload{} err = json.Unmarshal(decrypted, &apiResp) if err != nil { panic(err) } fmt.Printf(` ::add-mask::%s ::add-mask::%s ::add-mask::%s `, apiResp.AccessKeyId, apiResp.SecretAccessKey, apiResp.SessionToken) tmpl, err := template.New("").Parse(` AWS_ACCESS_KEY_ID={{.AccessKeyId}} AWS_SECRET_ACCESS_KEY={{.SecretAccessKey}} AWS_SESSION_TOKEN={{.SessionToken}} `) if err != nil { panic(err) } f, err := os.OpenFile(os.Getenv("GITHUB_ENV"), os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644) if err != nil { panic(err) } err = tmpl.Execute(f, apiResp) if err != nil { panic(err) } } func decryptor() *age.X25519Identity { key, err := ioutil.ReadFile(privateKeyPath()) if err != nil { panic(err) } identity, err := age.ParseX25519Identity(string(key)) if err != nil { panic(err) } return identity } func privateKeyPath() string { path := filepath.Join(os.Getenv("HOME"), ".actions2aws", "key") err := os.MkdirAll(filepath.Dir(path), 0700) if err != nil { panic(err) } return path } func keygen() { k, err := age.GenerateX25519Identity() if err != nil { panic(err) } fmt.Printf("ACTIONS2AWS PUBKEY: %s\n", k.Recipient()) err = ioutil.WriteFile(privateKeyPath(), []byte(k.String()), 0600) if err != nil { panic(err) } }
package main import ( "fmt" "time" ) func main() { fmt.Println("Igual =", "x" == "y") fmt.Println("Igual =", 5 == 5.0) fmt.Println("Diferente =", 5 != 4) fmt.Println("Maior =", 5 > 4) fmt.Println("Menor =", 2 < 4) fmt.Println("Maior ou igual =", 5 > 4) fmt.Println("Menor ou igual =", 2 < 4) data1 := time.Unix(0, 0) data2 := time.Unix(0, 0) fmt.Println("Igualdade entre datas =", data1 == data2) fmt.Println("Igualdade entre datas =", data1.Equal(data2)) type Pessoa struct { Nome string Sobrenome string } p1 := Pessoa{"João", "Batista"} p2 := Pessoa{"João", "Batista"} fmt.Println("Igualdade entre struct =", p1 == p2) }
package baremetal import ( "fmt" "net" "strings" "github.com/openshift/installer/pkg/types" "github.com/openshift/installer/pkg/types/baremetal" ) // TemplateData holds data specific to templates used for the baremetal platform. type TemplateData struct { // ProvisioningInterfaceMAC holds the interface's MAC address that the bootstrap node will use to host the ProvisioningIP below. // When the provisioning network is disabled, this is the external baremetal network MAC address. ProvisioningInterfaceMAC string // ProvisioningIP holds the IP the bootstrap node will use to service Ironic, TFTP, etc. ProvisioningIP string // ProvisioningIPv6 determines if we are using IPv6 or not. ProvisioningIPv6 bool // ProvisioningCIDR has the integer CIDR notation, e.g. 255.255.255.0 should be "24" ProvisioningCIDR int // ProvisioningDNSMasq determines if we start the dnsmasq service on the bootstrap node. ProvisioningDNSMasq bool // ProvisioningDHCPRange has the DHCP range, if DHCP is not external. Otherwise it // should be blank. ProvisioningDHCPRange string // ProvisioningDHCPAllowList contains a space-separated list of all of the control plane's boot // MAC addresses. Requests to bootstrap DHCP from other hosts will be ignored. ProvisioningDHCPAllowList string // IronicUsername contains the username for authentication to Ironic IronicUsername string // IronicUsername contains the password for authentication to Ironic IronicPassword string // BaremetalEndpointOverride contains the url for the baremetal endpoint BaremetalEndpointOverride string // BaremetalIntrospectionEndpointOverride contains the url for the baremetal introspection endpoint BaremetalIntrospectionEndpointOverride string // ClusterOSImage contains 4 URLs to download RHCOS live iso, kernel, rootfs and initramfs ClusterOSImage string // API VIP for use by ironic during bootstrap. APIVIP string // Hosts is the information needed to create the objects in Ironic. Hosts []*baremetal.Host // ProvisioningNetwork displays the type of provisioning network being used ProvisioningNetwork string // ExternalStaticIP is the static IP of the bootstrap node ExternalStaticIP string // ExternalStaticIP is the static gateway of the bootstrap node ExternalStaticGateway string // ExternalStaticDNS is the static DNS of the bootstrap node ExternalStaticDNS string ExternalSubnetCIDR int ExternalMACAddress string } // GetTemplateData returns platform-specific data for bootstrap templates. func GetTemplateData(config *baremetal.Platform, networks []types.MachineNetworkEntry, ironicUsername, ironicPassword string) *TemplateData { var templateData TemplateData templateData.Hosts = config.Hosts templateData.ProvisioningIP = config.BootstrapProvisioningIP templateData.ProvisioningNetwork = string(config.ProvisioningNetwork) templateData.ExternalStaticIP = config.BootstrapExternalStaticIP templateData.ExternalStaticGateway = config.BootstrapExternalStaticGateway templateData.ExternalStaticDNS = config.BootstrapExternalStaticDNS templateData.ExternalMACAddress = config.ExternalMACAddress if len(config.APIVIPs) > 0 { templateData.APIVIP = config.APIVIPs[0] templateData.BaremetalEndpointOverride = fmt.Sprintf("http://%s/v1", net.JoinHostPort(config.APIVIPs[0], "6385")) templateData.BaremetalIntrospectionEndpointOverride = fmt.Sprintf("http://%s/v1", net.JoinHostPort(config.APIVIPs[0], "5050")) } if config.BootstrapExternalStaticIP != "" { for _, network := range networks { cidr, _ := network.CIDR.Mask.Size() templateData.ExternalSubnetCIDR = cidr break } } if config.ProvisioningNetwork != baremetal.DisabledProvisioningNetwork { cidr, _ := config.ProvisioningNetworkCIDR.Mask.Size() templateData.ProvisioningCIDR = cidr templateData.ProvisioningIPv6 = config.ProvisioningNetworkCIDR.IP.To4() == nil templateData.ProvisioningInterfaceMAC = config.ProvisioningMACAddress templateData.ProvisioningDNSMasq = true } switch config.ProvisioningNetwork { case baremetal.ManagedProvisioningNetwork: cidr, _ := config.ProvisioningNetworkCIDR.Mask.Size() // When provisioning network is managed, we set a DHCP range including // netmask for dnsmasq. templateData.ProvisioningDHCPRange = fmt.Sprintf("%s,%d", config.ProvisioningDHCPRange, cidr) var dhcpAllowList []string for _, host := range config.Hosts { if host.IsMaster() { dhcpAllowList = append(dhcpAllowList, host.BootMACAddress) } } templateData.ProvisioningDHCPAllowList = strings.Join(dhcpAllowList, " ") case baremetal.DisabledProvisioningNetwork: templateData.ProvisioningInterfaceMAC = config.ExternalMACAddress templateData.ProvisioningDNSMasq = false if templateData.ProvisioningIP != "" { for _, network := range networks { if network.CIDR.Contains(net.ParseIP(templateData.ProvisioningIP)) { templateData.ProvisioningIPv6 = network.CIDR.IP.To4() == nil cidr, _ := network.CIDR.Mask.Size() templateData.ProvisioningCIDR = cidr } } } } templateData.IronicUsername = ironicUsername templateData.IronicPassword = ironicPassword templateData.ClusterOSImage = config.ClusterOSImage return &templateData }
package mock import ( "context" "payment/internal/dto" "payment/internal/models" "github.com/stretchr/testify/mock" ) //AccountRepositoryMock ... type AccountRepositoryMock struct { mock.Mock } //IsExist ... func (a AccountRepositoryMock) IsExist(ctx context.Context, id int) error { args := a.Called(ctx, id) return args.Error(0) } //Create ... func (a AccountRepositoryMock) Create(ctx context.Context, account dto.Account) (models.AccountAttributes, error) { args := a.Called(ctx, account) return args.Get(0).(models.AccountAttributes), args.Error(1) } //UpdateAmount ... func (a AccountRepositoryMock) UpdateAmount(ctx context.Context, accountID int, payload dto.Payload) (models.AccountAttributes, error) { args := a.Called(ctx, accountID, payload) return args.Get(0).(models.AccountAttributes), args.Error(1) } //RollbackTransaction ... func (a AccountRepositoryMock) RollbackTransaction(ctx context.Context, rollback dto.RollBack) error { args := a.Called(ctx, rollback) return args.Error(0) }
package lt349 // 两个数组的交集 //给定两个数组,编写一个函数来计算它们的交集。 // //示例 1: // //输入: nums1 = [1,2,2,1], nums2 = [2,2] //输出: [2] //示例 2: // //输入: nums1 = [4,9,5], nums2 = [9,4,9,8,4] //输出: [9,4] //说明: // //输出结果中的每个元素一定是唯一的。 //我们可以不考虑输出结果的顺序。 // //来源:力扣(LeetCode) //链接:https://leetcode-cn.com/problems/intersection-of-two-arrays //著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 // 一个set 使用哈希集合 题解区MrHuang的解法,错误答案,因为nums2[]元素没有去重避重 func intersection(nums1 []int, nums2 []int) []int { m := make(map[int]bool) ans := make([]int, 0) // 将nums1存入哈希集合m for _, v := range nums1 { m[v] = true } // 遍历nums2 for _, v := range nums2 { if !m[v] { ans = append(ans, v) delete(m, v) } } return ans } // 参考官方题解 // 1. 暴力解法 // 遍历nums1迭代,检查每个值是否存在于nums2中,如果存在则将 // 值添加到输出数组中 // 但是由于要求输出的结果中元素唯一,也就是要去重,所以要么是只用数组 // 获得的结果再进行去重,要么还是用一个哈希表记录已经使用过的元素 // 时间O(n*m);空间O(max(m,n)) //60/60 cases passed (72 ms) //Your runtime beats 7.06 % of golang submissions //Your memory usage beats 100 % of golang submissions (2.9 MB) func intersection1(nums1 []int, nums2 []int) []int { ans :=make([]int, 0) used := make(map[int]bool) // 初值为false,表示元素没使用过 for _, v1 := range nums1 { for _, v2 := range nums2 { if !used[v1] && !used[v2] && v1 == v2 { ans = append(ans, v1) used[v1] = true // 表示已使用过这一项,nums1和nums2[]下次就不能用这个数 break } } } return ans } // 2. 两个set // 两遍遍历两个数组得到两个集合,再用一遍循环判断交集 // O(m+n)/O(n+m) //60/60 cases passed (4 ms) //Your runtime beats 90.2 % of golang submissions //Your memory usage beats 100 % of golang submissions (3.2 MB) func intersection2(nums1 []int, nums2 []int) []int { set1, set2 := make(map[int]bool), make(map[int]bool) ans := make([]int, 0) // 将nums1存入哈希集合set1 for _, v := range nums1 { set1[v] = true } // 将nums2存入哈希集合set2 for _, v := range nums2 { set2[v] = true } // 遍历set1 for num1 := range set1 { if set2[num1] { ans = append(ans, num1) delete(set2, num1) } } return ans }
package github import ( "encoding/json" "errors" "fmt" "os" "github.com/nkprince007/igitt-go/lib" ) var gitHubBaseURL string func init() { gitHubBaseURL = func() string { url, exists := os.LookupEnv("GITHUB_BASE_URL") if !exists { return "https://api.github.com" } return url }() } type repository struct { ID int `json:"id"` FullName string `json:"full_name"` Description string `json:"description"` Private bool `json:"private"` URL string `json:"url"` WebURL string `json:"html_url"` Homepage string `json:"homepage"` HasIssues bool `json:"has_issues"` IsFork bool `json:"fork"` Parent *repository `json:"parent,omitempty"` } type label struct { Name string `json:"name"` Color string `json:"color,omitempty"` Description string `json:"description,omitempty"` } type labelArr struct { Labels []label } // Repository represents a repository on GitHub type Repository struct { r *repository id int fullName string token string data []byte fetched bool decoded bool } func (repo *Repository) url() (string, error) { if repo.id != 0 { return fmt.Sprintf("%s/repositories/%d", gitHubBaseURL, repo.id), nil } if repo.fullName != "" { return fmt.Sprintf("%s/repos/%s", gitHubBaseURL, repo.fullName), nil } return "", errors.New("URL couldn't be formed as neither Identifier nor" + " FullName were specified") } func (repo *Repository) decode() error { if repo.decoded { return nil } repo.decoded = true return json.Unmarshal(repo.data, &repo.r) } func (repo *Repository) refresh() error { if repo.fetched { repo.decode() return nil } url := repo.APIURL() data, e := make(chan []byte), make(chan error) go lib.Get(repo.token, url, data, e) if err := <-e; err != nil { return err } repo.data = <-data repo.decode() repo.id, repo.fullName, repo.fetched = repo.r.ID, repo.r.FullName, true return nil } // NewRepository returns a new GitHub Repository object func NewRepository(id int, token string) (*Repository, error) { if id == 0 { return nil, errors.New("Repository: ID cannot be zero") } return &Repository{&repository{}, id, "", token, nil, false, false}, nil } // NewRepositoryFromName returns a new GitHub Repository object func NewRepositoryFromName(name, token string) (*Repository, error) { if name == "" { return nil, errors.New("Repository: FullName cannot be an empty string") } return &Repository{&repository{}, 0, name, token, nil, false, false}, nil } // APIURL returns the API URL for the GitHub repository func (repo *Repository) APIURL() string { if repo.fetched { return repo.r.URL } url, _ := repo.url() return url } // FullName gives the fullname of GitHub repository func (repo *Repository) FullName() string { if repo.fullName == "" { repo.refresh() } return repo.fullName } // ID returns the unique identifier of GitHub repository func (repo *Repository) ID() int { if repo.id == 0 { repo.refresh() } return repo.id } // Description returns the description of the repository func (repo *Repository) Description() string { repo.refresh() return repo.r.Description } // IsPrivate tells whether the GitHub repository is private or not func (repo *Repository) IsPrivate() bool { repo.refresh() return repo.r.Private } // WebURL returns the URL for the webpage to GitHub repository func (repo *Repository) WebURL() string { repo.refresh() return repo.r.WebURL } // Homepage returns the URL for homepage of GitHub repository func (repo *Repository) Homepage() string { repo.refresh() return repo.r.Homepage } // HasIssues tells whether GitHub repository has an issue tracker or not func (repo *Repository) HasIssues() bool { repo.refresh() return repo.r.HasIssues } // IsFork tells whether the GitHub repository is a fork or not func (repo *Repository) IsFork() bool { repo.refresh() return repo.r.IsFork } // Parent returns the parent repository if it is a fork func (repo *Repository) Parent() *Repository { if !repo.IsFork() { return nil } parent := repo.r.Parent return &Repository{ parent, 0, parent.FullName, repo.token, nil, false, false} } // GetAllLabels returns all the labels associated with this repository func (repo *Repository) GetAllLabels() ([]string, error) { labelArr := []label{} labels := []string{} data, e := make(chan []byte), make(chan error) go lib.Get(repo.token, repo.APIURL()+"/labels", data, e) if err := <-e; err != nil { return nil, err } if err := json.Unmarshal(<-data, &labelArr); err != nil { return nil, err } for _, l := range labelArr { labels = append(labels, l.Name) } return labels, nil } // CreateLabel creates a new label in this GitHub repository func (repo *Repository) CreateLabel( name, color, description, labelType string) error { l := &label{name, color, description} data, e := make(chan []byte), make(chan error) go lib.Post(repo.token, repo.APIURL()+"/labels", data, e) encoded, err := json.Marshal(l) if err != nil { return err } data <- encoded err = <-e repo.decoded = false repo.data = <-data repo.decode() return err } // DeleteLabel deletes an existing label in the repository func (repo *Repository) DeleteLabel(name string) error { data, e := make(chan []byte), make(chan error) go lib.Delete(repo.token, repo.APIURL()+"/labels/"+name, data, e) data <- nil return <-e } func (repo *Repository) String() string { return fmt.Sprintf("Repository(id=%d, fullName=%s, url=%s)", repo.id, repo.fullName, repo.APIURL()) }
/* Copyright 2022 The KubeVela Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package schema import ( "testing" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" ) var _ = Describe("Test ui schema utils", func() { It("Test GetDefaultUIType function", func() { testCase := []map[string]interface{}{{ "apiType": "string", "haveOptions": true, "subType": "", "haveSub": true, "result": "Select", }, { "apiType": "string", "haveOptions": false, "subType": "", "haveSub": true, "result": "Input", }, { "apiType": "number", "haveOptions": false, "subType": "", "haveSub": true, "result": "Number", }, { "apiType": "integer", "haveOptions": false, "subType": "", "haveSub": true, "result": "Number", }, { "apiType": "boolean", "haveOptions": false, "subType": "", "haveSub": true, "result": "Switch", }, { "apiType": "array", "haveOptions": false, "subType": "string", "haveSub": true, "result": "Strings", }, { "apiType": "array", "haveOptions": false, "subType": "", "haveSub": true, "result": "Structs", }, { "apiType": "object", "haveOptions": false, "subType": "", "haveSub": true, "result": "Group", }, { "apiType": "object", "haveOptions": false, "subType": "", "haveSub": false, "result": "KV", }, } for _, tc := range testCase { uiType := GetDefaultUIType(tc["apiType"].(string), tc["haveOptions"].(bool), tc["subType"].(string), tc["haveSub"].(bool)) Expect(uiType).Should(Equal(tc["result"])) } }) }) func TestUISchema_Validate(t *testing.T) { tests := []struct { name string u UISchema wantErr bool }{ { name: "test validate ui schema error", u: UISchema{ { Conditions: []Condition{ { JSONKey: "", }, }, }, }, wantErr: true, }, { name: "test validate ui schema success", u: UISchema{ { Conditions: []Condition{ { JSONKey: "key", Op: "==", Action: "enable", }, }, }, }, wantErr: false, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { if err := tt.u.Validate(); (err != nil) != tt.wantErr { t.Errorf("Validate() error = %v, wantErr %v", err, tt.wantErr) } }) } }
/* * @lc app=leetcode.cn id=147 lang=golang * * [147] 对链表进行插入排序 */ // @lc code=start /** * Definition for singly-linked list. * type ListNode struct { * Val int * Next *ListNode * } */ package main import "fmt" type ListNode struct { Val int Next *ListNode } func insertionSortList(head *ListNode) *ListNode { if head == nil || head.Next == nil { return head } // 新建链表哨兵 OrderedHead := &ListNode{Next: head} cur := head.Next head.Next = nil // 封闭上, 以防插入到已排序链表时,带上了后面的未排序链表 // 遍历未排序链表 for cur != nil { tmp := cur.Next // 先记住下一个要遍历的链点 // 遍历已排序列表,寻找插入位置, 即第一个比待插入链点值大的位置 pre := OrderedHead orderedNode := OrderedHead.Next for orderedNode != nil && orderedNode.Val <= cur.Val { pre = orderedNode orderedNode = orderedNode.Next } // 待插入位置是最后节点 if orderedNode == nil { // 到了OrderedList的末尾节点 // fmt.Printf("else loginc, pre val is %d\n", pre.Val) pre.Next = cur cur.Next = nil // 要封闭上 } else { //待插入位置不是最后节点,而是中间节点 pre.Next = cur cur.Next = orderedNode } // 遍历下一个待插入节点 cur = tmp } return OrderedHead.Next } // @lc code=end func print(head *ListNode) { fmt.Println("print the list") for head != nil { fmt.Printf("%d ", head.Val) head = head.Next } fmt.Println() } func main() { l11 := ListNode{Val: -1} l12 := ListNode{Val: 5} l13 := ListNode{Val: 3} l14 := ListNode{Val: 4} l15 := ListNode{Val: 0} l11.Next = &l12 l12.Next = &l13 l13.Next = &l14 l14.Next = &l15 print(&l11) a := insertionSortList(&l11) print(a) l21 := ListNode{Val: 3} l22 := ListNode{Val: 4} l23 := ListNode{Val: 1} l21.Next = &l22 l22.Next = &l23 print(&l21) b := insertionSortList(&l21) print(b) }
package main import( "log" "os" "context" "google.golang.org/grpc" "google.golang.org/grpc/credentials" "grpc-demo/api" ) const ( //address ="127.0.0.1:22222" //defaultName = "world" // TLS认证选项 OpenTLS = true ) // customCredential 自定义认证 type customCredential struct {} func (c customCredential) GetRequestMetadata(ctx context.Context, uri ... string) (map[string]string, error){ return map[string]string { "appid":"110", "appkey": "key", },nil } func (c customCredential) RequireTransportSecurity() bool{ if OpenTLS{ return true } return false; } func main() { var opts []grpc.DialOption if OpenTLS{ // 添加证书 creds, err := credentials.NewClientTLSFromFile("../keys/server.pem","test") if err !=nil { log.Fatalf("Failed to create TLS credentials %v", err) } opts = append(opts, grpc.WithTransportCredentials(creds)) }else{ opts = append(opts, grpc.WithInsecure()) } // 添加自定义token认证 //opts = append(opts, grpc.WithPerRPCCredentials(new(customCredential))) // 构建connect conn, err := grpc.Dial(address, opts...) if err != nil{ log.Fatalf("did not connect: %v", err) } // 延时函数 在return之前进行 defer conn.Close() // 初始化客户端 c := api.NewGreeterClient(conn) // 获取客户名称 name := defaultName if len(os.Args) >1{ name = os.Args[1] } // 构造请求 req := api.HelloRequest{ Name:name, } // 远程SayHello函数 reps, err := c.SayHello(context.Background(), &req) if err != nil{ log.Fatalf("could not greet: %v", err) } // 结果 log.Printf("get server Greeting response: %s", reps.Message) }
package main import ( "crypto/aes" "crypto/cipher" "crypto/md5" "crypto/rand" "encoding/hex" "fmt" "io" "io/ioutil" "log" "os" "time" rand1"math/rand" "github.com/Binject/debug/pe" ) // DetectDotNet - returns true if a .NET assembly. 2nd return value is detected version string. func DetectDotNet(filename string) (bool, string) { // auto-detect .NET assemblies and version pefile, err := pe.Open(filename) if err != nil { return false, "" } defer pefile.Close() return pefile.IsManaged(), pefile.NetCLRVersion() } //生成随机字符串 func GetRandomString(length int) string{ str := "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" bytes := []byte(str) result := []byte{} r := rand1.New(rand1.NewSource(time.Now().UnixNano())) for i := 0; i < length; i++ { result = append(result, bytes[r.Intn(len(bytes))]) } return string(result) } // 生成32位MD5 func MD5(text string) string { ctx := md5.New() ctx.Write([]byte(text)) return hex.EncodeToString(ctx.Sum(nil)) } func wr(str string) { f, err := os.Create("aeskey.txt") if err != nil { fmt.Println(err) return } _, err = f.WriteString(str) if err != nil { fmt.Println(err) f.Close() return } } func main() { if len(os.Args) != 2{ fmt.Println(os.Args[0]+" filename") } filename := os.Args[1] log.Print("File encryption example") plaintext, err := ioutil.ReadFile(filename) if err != nil { log.Fatal(err) } _, NetCLRVersion := DetectDotNet(filename) f0, err := os.Create("version.txt") if err != nil { fmt.Println(err) return } _, err = f0.WriteString(NetCLRVersion) if err != nil { fmt.Println(err) f0.Close() return } key0 := MD5(GetRandomString(16)) wr(key0) // The key should be 16 bytes (AES-128), 24 bytes (AES-192) or // 32 bytes (AES-256) key, err := ioutil.ReadFile("aeskey.txt") block, err := aes.NewCipher(key) if err != nil { log.Panic(err) } gcm, err := cipher.NewGCM(block) if err != nil { log.Panic(err) } // Never use more than 2^32 random nonces with a given key // because of the risk of repeat. nonce := make([]byte, gcm.NonceSize()) if _, err := io.ReadFull(rand.Reader, nonce); err != nil { log.Fatal(err) } ciphertext := gcm.Seal(nonce, nonce, plaintext, nil) // Save back to file err = ioutil.WriteFile(filename+".cipher", ciphertext, 0777) if err != nil { log.Panic(err) } }
package main import ( "context" "flag" "fmt" "github.com/sfomuseum/go-flags/multi" "github.com/whosonfirst/go-reader" "github.com/whosonfirst/go-whosonfirst-travel-image/util" "log" ) func main() { var sources multi.MultiString flag.Var(&sources, "source", "One or more filesystem based sources to use to read WOF ID data, which may or may not be part of the sources to graph. This is work in progress.") flag.Parse() ctx := context.Background() r, err := reader.NewMultiReaderFromURIs(ctx, sources...) if err != nil { log.Fatal(err) } for _, str_id := range flag.Args() { f, err := utils.LoadFeatureFromString(r, str_id) if err != nil { log.Fatal(err) } fname := util.Filename(f) fmt.Println(fname) } }
End of preview. Expand in Data Studio
README.md exists but content is empty.
Downloads last month
4