blob_id
stringlengths
40
40
language
stringclasses
1 value
repo_name
stringlengths
4
108
path
stringlengths
2
210
src_encoding
stringclasses
12 values
length_bytes
int64
13
5.82M
score
float64
2.52
5.22
int_score
int64
3
5
detected_licenses
listlengths
0
161
license_type
stringclasses
2 values
detected_licenses_right
listlengths
0
161
license_type_right
stringclasses
2 values
text
stringlengths
13
6.48M
download_success
bool
1 class
2cb0aa2c849ada1b8185a2a1e4ea6c811d9d76f3
Go
gernest/gforms
/examples/select_input.go
UTF-8
1,241
2.96875
3
[ "MIT" ]
permissive
[ "MIT" ]
permissive
package main import ( "fmt" "github.com/bluele/gforms" "net/http" "path" "runtime" "text/template" ) type Lang struct { Name string `gforms:"name"` } func main() { tpl := template.Must(template.ParseFiles(path.Join(getTemplatePath(), "post_form.html"))) langForm := gforms.DefineModelForm(Lang{}, gforms.NewFields( gforms.NewTextField( "name", gforms.Validators{ gforms.Required(), }, gforms.SelectWidget( map[string]string{}, func() gforms.SelectOptions { return gforms.StringSelectOptions([][]string{ {"Select...", "", "true", "false"}, {"Golang", "golang", "false", "false"}, {"Python", "python", "false", "false"}, {"C", "c", "false", "true"}, }) }, ), ), )) http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "text/html") form := langForm(r) if r.Method != "POST" { tpl.Execute(w, form) return } if !form.IsValid() { tpl.Execute(w, form) return } lang := form.GetModel().(Lang) fmt.Fprintf(w, "ok: %v", lang) }) http.ListenAndServe(":9000", nil) } func getTemplatePath() string { _, filename, _, _ := runtime.Caller(1) return path.Join(path.Dir(filename), "templates") }
true
b913b73175d8aa3cd17a51648589a6b06182f799
Go
cloudfstrife/inverted-index
/inverted/index_test.go
UTF-8
2,569
3.015625
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
package inverted import ( "math/rand" "testing" "time" "github.com/google/go-cmp/cmp" ) func TestContainer(t *testing.T) { TestCases := map[string]struct { push []int64 pop []int64 expect []int64 }{ "normal": { push: []int64{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, pop: []int64{0, 2, 4, 6, 9}, expect: []int64{1, 3, 5, 7, 8}, }, "repetitive": { push: []int64{0, 0, 1, 2, 1, 4, 4, 5, 4, 4, 3, 5, 6, 7, 3, 2, 3, 5, 6, 0}, pop: []int64{0, 4, 2, 2, 10, 7, 12}, expect: []int64{1, 5, 3, 6}, }, } for name, tcase := range TestCases { t.Run(name, func(t *testing.T) { c := NewIDContainer() for _, v := range tcase.push { c.Push(v) } for _, v := range tcase.pop { c.Pop(v) } got := c.Array() if !cmp.Equal(tcase.expect, got) { t.Errorf("unintended : %s", cmp.Diff(tcase.expect, got)) } }) } } func TestIndexIndex(t *testing.T) { type cases struct { key string push []int64 pop []int64 expect []int64 } TestCases := map[string][]cases{ "normal": { cases{ key: "first", push: []int64{1, 2, 3, 4, 5, 6, 7, 8, 9, 0}, pop: []int64{1, 2, 3, 4, 0}, expect: []int64{5, 6, 7, 8, 9}, }, cases{ key: "second", push: []int64{1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3}, pop: []int64{0, 2, 4}, expect: []int64{1, 3}, }, }, } for name, tcases := range TestCases { t.Run(name, func(t *testing.T) { index := NewIndex() for _, tce := range tcases { for _, v := range tce.push { index.Push(tce.key, v) } } for _, tce := range tcases { for _, v := range tce.pop { index.Pop(tce.key, v) } } for _, tce := range tcases { got := index.GetAllID(tce.key) if !cmp.Equal(tce.expect, got) { t.Errorf("unintended : %s", cmp.Diff(tce.expect, got)) } } got := index.GetAllID(name) if got != nil { t.Errorf("unintended : %s", cmp.Diff(nil, got)) } }) } } func BenchmarkContainer(b *testing.B) { r := rand.New(rand.NewSource(time.Now().UnixNano())) c := NewIDContainer() // 重置计时器 b.ResetTimer() b.RunParallel(func(pb *testing.PB) { for pb.Next() { c.Push(r.Int63()) } }) } func BenchmarkIndex(b *testing.B) { keywords := []string{"a", "b", "c", "d", "e", "f", "g", "h"} l := len(keywords) r := rand.New(rand.NewSource(time.Now().UnixNano())) i := NewIndex() // 重置计时器 b.ResetTimer() b.RunParallel(func(pb *testing.PB) { for pb.Next() { v := r.Int63() i.Push(keywords[int(v)%l], v) } }) }
true
94af7d2538e8aa6c10329d29a0b81bee39142ece
Go
yodo-io/goreg
/main.go
UTF-8
1,732
2.859375
3
[ "MIT" ]
permissive
[ "MIT" ]
permissive
package main import ( "fmt" "os" "strings" "github.com/urfave/cli" ) func main() { app := cli.NewApp() app.Name = "Go reg" app.Usage = "Simple docker registry client" loginFlags := []cli.Flag{ cli.StringFlag{ Name: "registry-url, r", Usage: "registry url to query", EnvVar: "REGISTRY_URL", }, cli.StringFlag{ Name: "username, u", Usage: "registry login user", EnvVar: "REGISTRY_USERNAME", }, cli.StringFlag{ Name: "password, p", Usage: "registry password", EnvVar: "REGISTRY_PASSWORD", }, } app.Commands = []cli.Command{ { Name: "list", Aliases: []string{"ls"}, Usage: "list repositories", Action: actionListRepos, Flags: append(loginFlags, []cli.Flag{}...), }, { Name: "tags", Usage: "list tags for a repo", Action: actionListTags, Flags: append(loginFlags, []cli.Flag{ cli.StringFlag{ Name: "repository, repo", Usage: "repository name", EnvVar: "REPOSITORY_NAME", }, }...), }, } if err := app.Run(os.Args); err != nil { fmt.Fprintln(os.Stderr, err) os.Exit(1) } } func actionListRepos(c *cli.Context) error { login := loginOpts(c) return ListRepos(login) } func actionListTags(c *cli.Context) error { login := loginOpts(c) repo := c.String("repository") return ListTags(login, repo) } func loginOpts(c *cli.Context) RegistryLogin { return RegistryLogin{ url: addProto(c.String("registry-url")), username: c.String("username"), password: c.String("password"), } } func addProto(repositoryURL string) string { if len(repositoryURL) == 0 || strings.HasPrefix(repositoryURL, "http") { return repositoryURL } return fmt.Sprintf("https://%s", repositoryURL) }
true
43fd855bc1ed7ab2715416ed054feb12128f9bc9
Go
d11wtq/bijou
/src/github.com/d11wtq/bijou/test/runtime/args_test.go
UTF-8
797
2.671875
3
[]
no_license
[]
no_license
package runtime_test import ( . "github.com/d11wtq/bijou/runtime" "github.com/d11wtq/bijou/test" "testing" ) func TestReadArgsWithCorrectArity(t *testing.T) { var a, b Value args := test.NewList(Int(42), Int(7)) if err := ReadArgs(args, &a, &b); err != nil { t.Fatalf(`expected err == nil, got %s`, err) } if a != Int(42) { t.Fatalf(`expected a == Int(42), got %s`, a) } if b != Int(7) { t.Fatalf(`expected b == Int(7), got %s`, b) } } func TestReadArgsWithBadArity(t *testing.T) { var a, b Value args1 := test.NewList(Int(13), Int(42), Int(7)) args2 := test.NewList(Int(7)) if err := ReadArgs(args1, &a, &b); err == nil { t.Fatalf(`expected err != nil, got nil`) } if err := ReadArgs(args2, &a, &b); err == nil { t.Fatalf(`expected err != nil, got nil`) } }
true
133239e55e49426cc681cac3b19819fb939eb408
Go
soldatigabriele/caesar
/main.go
UTF-8
2,611
3.546875
4
[]
no_license
[]
no_license
package main import ( "bufio" "fmt" "os" "sort" "strings" caesar "github.com/soldatigabriele/caesar/caesar" ) // This app will translate a sentence using the Caesar Cipher. // https://en.wikipedia.org/wiki/Caesar_cipher func main() { reader := bufio.NewReader(os.Stdin) fmt.Print("Enter encoded text: ") // Read the encoded string and convert it to upper case enc, _ := reader.ReadString('\n') enc = strings.ToUpper(enc) // Get the list of possible solutions solutions := caesar.Decode(enc) // Now we want to count the english words in // every sentence, so we can guess the correct one solutionsCount := make(map[string]int) for _, solution := range solutions { solutionsCount[solution] = 0 words := strings.Split(solution, string(32)) for _, word := range words { val, err := checkWord(word) if err != nil { fmt.Println(err) break } if val == true { solutionsCount[solution]++ } } } for k, v := range solutionsCount { if v == 0 { delete(solutionsCount, k) } } s := sortedKeys(solutionsCount) if len(s) == 0 { fmt.Println("Could not find any solution to this encryption") return } fmt.Printf("The solution is likely to be: \n\n %s \n\n", s[0]) if len(s) > 1 { fmt.Printf("but it could also be one of the following: \n\n") for i := 1; i < len(s); i++ { fmt.Printf("%s \n", s[i]) } } } // checkWord checks if a word is a valid English word by // looking at a dictionary of 3000 popular English words func checkWord(w string) (bool, error) { // format the word to be lower case w = strings.ToLower(w) // open the dictionary of popular English words f, err := os.Open("dictionary.txt") if err != nil { return false, err } defer f.Close() // Splits on newlines by default. scanner := bufio.NewScanner(f) line := 1 for scanner.Scan() { if scanner.Text() == w { return true, nil } line++ } if err := scanner.Err(); err != nil { return false, err } // could not find any match, but no error is provided return false, nil } // Define a sorted Map to get the string with the // highest possibility of being an english sentence type sortedMap struct { m map[string]int s []string } func (sm *sortedMap) Len() int { return len(sm.m) } func (sm *sortedMap) Less(i, j int) bool { return sm.m[sm.s[i]] > sm.m[sm.s[j]] } func (sm *sortedMap) Swap(i, j int) { sm.s[i], sm.s[j] = sm.s[j], sm.s[i] } func sortedKeys(m map[string]int) []string { sm := new(sortedMap) sm.m = m sm.s = make([]string, len(m)) i := 0 for key, _ := range m { sm.s[i] = key i++ } sort.Sort(sm) return sm.s }
true
1c3d08a046ae502022d9780b409b337dedf21207
Go
pfayle/proji
/pkg/remote/remote_test.go
UTF-8
1,559
3.21875
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
package remote import ( "net/url" "testing" "github.com/stretchr/testify/assert" ) func TestParseURL(t *testing.T) { type args struct { URL string } tests := []struct { name string args args want *url.URL wantErr bool }{ { name: "Test ParseURL 1", args: args{URL: "https://github.com/nikoksr/proji"}, want: &url.URL{ Scheme: "https", Host: "github.com", Path: "/nikoksr/proji", }, wantErr: false, }, { name: "Test ParseURL 2", args: args{URL: "https://github.com/nikoksr/proji.git"}, want: &url.URL{ Scheme: "https", Host: "github.com", Path: "/nikoksr/proji", }, wantErr: false, }, { name: "Test ParseURL 3", args: args{URL: "gh:/nikoksr/proji/configs/test.conf"}, want: &url.URL{ Scheme: "https", Host: "github.com", Path: "/nikoksr/proji/configs/test.conf", }, wantErr: false, }, { name: "Test ParseURL 4", args: args{URL: "gl:/nikoksr/proji-test.git"}, want: &url.URL{ Scheme: "https", Host: "gitlab.com", Path: "/nikoksr/proji-test", }, wantErr: false, }, { name: "Test ParseURL 5", args: args{URL: ""}, want: nil, wantErr: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { got, err := ParseURL(tt.args.URL) assert.Equal(t, err != nil, tt.wantErr, "ParseURL() error = %v, wantErr %v", err, tt.wantErr) if got == nil { return } assert.Equal(t, tt.want, got, "ParseURL() got = %v, want %v", got, tt.want) }) } }
true
df5e11593be1f3d89538c6e99cc5787b932d15e5
Go
amitbet/codewar2021
/server/types.go
UTF-8
1,166
3.34375
3
[ "MIT" ]
permissive
[ "MIT" ]
permissive
package main import "strconv" type Player struct { Role string `json:"role"` Score int `json:"score"` Name string `json:"name"` Wins int `json:"wins"` } func (p Player) String() string { return p.Role + ": " + p.Name + "(" + strconv.Itoa(p.Wins) + ")\n" + strconv.Itoa(p.Score) + "\n" } type Match struct { Player1 Player `json:"player1"` Player2 Player `json:"player2"` } func (m Match) String() string { return "----------------------------\n" + m.Player1.String() + m.Player2.String() + "----------------------------\n" } func (m Match) Csv() string { return "\"" + m.Player1.Name + "\",\"" + m.Player1.Role + "\",\"" + strconv.Itoa(m.Player1.Wins) + "\"," + strconv.Itoa(m.Player1.Score) + ",\"" + m.Player2.Name + "\",\"" + m.Player2.Role + "\",\"" + strconv.Itoa(m.Player2.Wins) + "\"," + strconv.Itoa(m.Player2.Score) } type GameRecord struct { MatchArr []*Match } func (g *GameRecord) AddMatch(m *Match) { g.MatchArr = append(g.MatchArr, m) } func (g *GameRecord) Csv() string { csvStr := "Player1,Role,Wins,Score,Player2,Role,Wins,Score\n" for _, m := range g.MatchArr { csvStr += m.Csv() + "\n" } return csvStr }
true
be76978aa424eadeeaef90719ac3bab3bcfb4fbb
Go
hujimori/atcoder
/arihon/2-92/solve.go
UTF-8
416
3.6875
4
[]
no_license
[]
no_license
package main import "fmt" type Edge struct { to int cost int } type Graph []*Edge func NewGraph(n int) Graph { g := make(Graph, n) return g } func (g Graph) PushBack(i int, e *Edge) { g[i] = e } func main() { g := NewGraph(3) g.PushBack(0, &Edge{to: 1, cost: 10}) g.PushBack(1, &Edge{to: 2, cost: 5}) g.PushBack(2, &Edge{to: 0, cost: 3}) fmt.Println(g[0]) fmt.Println(g[1]) fmt.Println(g[2]) }
true
d547907ba4900b83675e781552cb51f9a3e426a6
Go
Miniand/brdg.me
/game/cathedral/game_test.go
UTF-8
3,915
3
3
[]
no_license
[]
no_license
package cathedral import ( "bytes" "errors" "strconv" "strings" "testing" "github.com/Miniand/brdg.me/game/helper" "github.com/stretchr/testify/assert" ) func parseGame(input string) (*Game, error) { board, err := parseBoard(input) if err != nil { return nil, err } g := &Game{} if err := g.Start(helper.Players[:2]); err != nil { return nil, err } g.Board = board for _, t := range g.Board { if t.Player != NoPlayer { player := t.Player if player == PlayerCathedral { player = 1 } g.PlayedPieces[player][t.Type-1] = true } } return g, nil } func parseBoard(input string) (board Board, err error) { lines := strings.Split(input, "\n") board = Board{} i := 0 for _, l := range lines { if l == "" { continue } if i >= 10 { err = errors.New("out of range") return } if len(l) != 20 { err = errors.New("expected row to be 20 chars long") } for j := 0; j < 10; j++ { board[Loc{j, i}], err = parseTile(l[j*2 : (j+1)*2]) if err != nil { return } } i++ } if i != 10 { err = errors.New("there wasn't 10 rows") } return } func parseTile(input string) (t Tile, err error) { t = EmptyTile if len(input) != 2 { err = errors.New("input should be len 2") return } if input == ".." { t.Player = NoPlayer return } switch input[0] { case 'G': t.Player = 0 case 'R': t.Player = 1 case 'C': t.Player = PlayerCathedral default: err = errors.New("tile should start with '.', 'R', 'G' or 'C'") return } switch input[1] { case '.': t.Owner, t.Player = t.Player, NoPlayer default: t.Type, err = strconv.Atoi(string(input[1])) } return } func outputBoard(b Board) string { rowStrs := []string{} for _, row := range LocsByRow { rowStr := bytes.NewBuffer([]byte{}) for _, l := range row { t := b[l] player := t.Player if player == NoPlayer { player = t.Owner } b := byte('.') switch player { case 0: b = 'G' case 1: b = 'R' case 2: b = 'C' } rowStr.WriteByte(b) b = '.' if t.Player != NoPlayer { b = '0' + byte(t.Type) } rowStr.WriteByte(b) } rowStrs = append(rowStrs, rowStr.String()) } return strings.Join(rowStrs, "\n") } func assertBoardOutputsEqual(t *testing.T, expected, actual string) bool { trimmedExpected := strings.TrimSpace(expected) trimmedActual := strings.TrimSpace(actual) t.Logf( "Expected:\n%s\n\nActual:\n%s", trimmedExpected, trimmedActual, ) return assert.Equal(t, trimmedExpected, trimmedActual) } func assertBoardsEqual(t *testing.T, expected, actual Board) bool { return assertBoardOutputsEqual(t, outputBoard(expected), outputBoard(actual)) } func assertBoard(t *testing.T, expected string, actual Board) bool { return assertBoardOutputsEqual(t, expected, outputBoard(actual)) } func TestGame_Encode(t *testing.T) { g := &Game{} assert.NoError(t, g.Start(helper.Players[:2])) data, err := g.Encode() assert.NoError(t, err) assert.NotEmpty(t, data) } func TestParseBoard(t *testing.T) { board, err := parseBoard(` G.G3................ G.G3................ G.G3................ G3G3................ .................... .................... .................... .................... .................... ....................`) assert.NoError(t, err) assert.Equal(t, Tile{ PlayerType: PlayerType{ Player: NoPlayer, }, Owner: 0, }, board[Loc{0, 0}]) assert.Equal(t, Tile{ PlayerType: PlayerType{ Player: 0, Type: 3, }, Owner: NoPlayer, }, board[Loc{1, 0}]) } func TestOutputBoard(t *testing.T) { b1, err := parseBoard(` G.G3................ G.G3................ G.G3....C1.......... G3G3..C1C1C1........ ........C1.......... ........C1.......... .................... ..........R5R5...... ............R5...... ....................`) assert.NoError(t, err) b2, err := parseBoard(outputBoard(b1)) assert.NoError(t, err) assertBoardsEqual(t, b1, b2) }
true
203c0e9bb7e38ae7776bb475c6661a782bbfed2e
Go
f4814/iscraper
/database.go
UTF-8
10,324
2.671875
3
[ "MIT" ]
permissive
[ "MIT" ]
permissive
package main import ( "fmt" driver "github.com/arangodb/go-driver" "github.com/f4814/iscraper/models" log "github.com/sirupsen/logrus" ) type DBHelper struct { Client driver.Client DB driver.Database GraphOptions driver.CreateGraphOptions Graph driver.Graph Users driver.Collection Items driver.Collection Comments driver.Collection EdgeLikes driver.Collection EdgeTags driver.Collection EdgeChild driver.Collection EdgeFollows driver.Collection EdgePosts driver.Collection } func NewDBHelper(client driver.Client, dbName string) DBHelper { h := DBHelper{Client: client} var ( err error exists bool ) // Initialize Database var db driver.Database if exists, err = client.DatabaseExists(nil, dbName); err != nil { log.Fatal(err) } if !exists { log.WithFields(log.Fields{"database": dbName}).Debug("Creating new Database") db, err = client.CreateDatabase(nil, dbName, nil) } else { log.WithFields(log.Fields{"database": dbName}).Debug("Loading existing Database") db, err = client.Database(nil, dbName) } if err != nil { log.Fatal(err) } h.DB = db // Initialize Graph var graph driver.Graph if exists, err = h.DB.GraphExists(nil, "instagram"); err != nil { log.Fatal(err) } if !exists { log.WithFields(log.Fields{ "database": dbName, "graph": "instagram", }).Debug("Creating new Graph") graph, err = h.DB.CreateGraph(nil, "instagram", nil) // TODO Opts } else { log.WithFields(log.Fields{ "database": dbName, "graph": "instagram", }).Debug("Loading Existing graph") graph, err = h.DB.Graph(nil, "instagram") } if err != nil { log.Fatal(err) } h.Graph = graph // Get Edge and vertex collections h.Users = h.initVertex("users") h.Items = h.initVertex("items") h.Comments = h.initVertex("comments") h.EdgeLikes = h.initEdge("edge_likes") h.EdgeTags = h.initEdge("edge_tags") h.EdgeChild = h.initEdge("edge_child") h.EdgeFollows = h.initEdge("edge_follows") h.EdgePosts = h.initEdge("edge_posts") // Initialize Indexes uniqueOpts := driver.EnsureHashIndexOptions{Unique: true} h.initHashIndex(h.Users, []string{"id", "username"}, &uniqueOpts) h.initHashIndex(h.Items, []string{"id"}, &uniqueOpts) h.initHashIndex(h.Comments, []string{"id", "pk"}, &uniqueOpts) h.initHashIndex(h.EdgeLikes, []string{"_from", "_to"}, &uniqueOpts) h.initHashIndex(h.EdgePosts, []string{"_from", "_to"}, &uniqueOpts) h.initHashIndex(h.EdgeFollows, []string{"_from", "_to"}, &uniqueOpts) h.initHashIndex(h.EdgeTags, []string{"_from", "_to"}, &uniqueOpts) h.initHashIndex(h.EdgeChild, []string{"_from", "_to"}, &uniqueOpts) return h } func (h *DBHelper) initVertex(name string) driver.Collection { var ( c driver.Collection err error exists bool ) if exists, err = h.Graph.VertexCollectionExists(nil, name); err != nil { log.Fatal(err) } if !exists { log.WithFields(log.Fields{ "database": h.DB.Name(), "graph": h.Graph.Name(), "collection": name, }).Debug("Creating new Vertex Collection") c, err = h.Graph.CreateVertexCollection(nil, name) } else { log.WithFields(log.Fields{ "database": h.DB.Name(), "graph": h.Graph.Name(), "collection": name, }).Debug("Loading existing Vertex Collection") c, err = h.Graph.VertexCollection(nil, name) } if err != nil { log.Fatal(err) } return c } func (h *DBHelper) initEdge(name string) driver.Collection { defs := []driver.EdgeDefinition{ driver.EdgeDefinition{ Collection: "edge_likes", From: []string{"users"}, To: []string{"users"}, }, driver.EdgeDefinition{ Collection: "edge_tags", From: []string{"items"}, To: []string{"users"}, }, driver.EdgeDefinition{ Collection: "edge_child", From: []string{"items", "comments"}, To: []string{"comments"}, }, driver.EdgeDefinition{ Collection: "edge_follows", From: []string{"users"}, To: []string{"users"}, }, driver.EdgeDefinition{ Collection: "edge_posts", From: []string{"users"}, To: []string{"items"}, }, } var constraints driver.VertexConstraints for _, d := range defs { if d.Collection == name { constraints.From = d.From constraints.To = d.To break } } var ( err error c driver.Collection exists bool ) if exists, err = h.Graph.EdgeCollectionExists(nil, name); err != nil { log.Fatal(err) } if !exists { log.WithFields(log.Fields{ "database": h.DB.Name(), "graph": h.Graph.Name(), "collection": name, }).Debug("Creating new Edge Collection") c, err = h.Graph.CreateEdgeCollection(nil, name, constraints) } else { log.WithFields(log.Fields{ "database": h.DB.Name(), "graph": h.Graph.Name(), "collection": name, }).Debug("Loading existing Edge Collection") c, _, err = h.Graph.EdgeCollection(nil, name) } if err != nil { log.Fatal(err) } return c } func (h *DBHelper) initHashIndex(coll driver.Collection, fields []string, opts *driver.EnsureHashIndexOptions) { _, n, err := coll.EnsureHashIndex(nil, fields, opts) if err != nil { log.Fatal(err) } else if n { log.WithFields(log.Fields{ "database": h.DB.Name(), "collection": coll.Name(), "fields": fields, "opts": opts, }).Debug("Created new Hash Index") } else { log.WithFields(log.Fields{ "database": h.DB.Name(), "collection": coll.Name(), "fields": fields, "opts": opts, }).Debug("Loaded existing Hash Index") } } func (h *DBHelper) SaveUser(user *models.User) { query := "FOR u IN users FILTER u.id == @id RETURN u" cur, err := h.DB.Query(nil, query, map[string]interface{}{ "id": user.ID, }, ) defer cur.Close() if err != nil { log.Fatal(err) } var ( meta driver.DocumentMeta msg string ) if cur.HasMore() { var oldUser models.User if meta, err = cur.ReadDocument(nil, &oldUser); err != nil { log.Fatal(err) } else { if oldUser.ScrapedAt.After(user.ScrapedAt) { user.ScrapedAt = oldUser.ScrapedAt } meta, err = h.Users.UpdateDocument(nil, meta.Key, *user) msg = "Loaded Item Metadata" } } else { meta, err = h.Users.CreateDocument(nil, *user) msg = "Saved user" } if err != nil { log.Fatal(err) } user.SetMeta(meta) log.WithFields(log.Fields{ "username": user.Username, }).Trace(msg) } func (h *DBHelper) SaveItem(item *models.Item) { query := fmt.Sprintf("FOR i IN items FILTER i.id == '%s' RETURN i", item.ID) cur, err := h.DB.Query(nil, query, nil) if err != nil { log.Fatal(err) } defer cur.Close() var ( meta driver.DocumentMeta msg string ) if cur.HasMore() { var oldItem models.Item if meta, err = cur.ReadDocument(nil, &oldItem); err != nil { log.Fatal(err) } else { if oldItem.ScrapedAt.After(item.ScrapedAt) { item.ScrapedAt = oldItem.ScrapedAt } msg = "Loaded Item Metadata" meta, err = h.Items.UpdateDocument(nil, meta.Key, *item) } } else { meta, err = h.Items.CreateDocument(nil, *item) msg = "Saved Item" } if err != nil { log.Fatal(err) } item.SetMeta(meta) log.WithFields(log.Fields{ "id": item.ID, }).Trace(msg) } func (h *DBHelper) UserFollows(user *models.User, follows *models.User) { query := "FOR e IN edge_follows FILTER e._from == @from && e._to == @to RETURN e" cur, err := h.DB.Query(nil, query, map[string]interface{}{ "from": user.GetMeta().ID, "to": follows.GetMeta().ID, }, ) defer cur.Close() if err != nil { log.Fatal(err) } if !cur.HasMore() { edge := models.Follows{ From: string(user.GetMeta().ID), To: string(follows.GetMeta().ID), } if _, err := h.EdgeFollows.CreateDocument(nil, edge); err != nil { log.Fatal(err) } log.WithFields(log.Fields{ "username": user.Username, "follows": follows.Username, "edge": edge, }).Trace("Add Follow Edge") } } func (h *DBHelper) UserFollowed(user *models.User, followed *models.User) { h.UserFollows(followed, user) } func (h *DBHelper) UserPosts(user *models.User, item *models.Item) { query := "FOR e IN edge_posts FILTER e._from == @from && e._to == @to RETURN e" cur, err := h.DB.Query(nil, query, map[string]interface{}{ "from": user.GetMeta().ID, "to": item.GetMeta().ID, }, ) defer cur.Close() if err != nil { log.Fatal(err) } if !cur.HasMore() { edge := models.Posts{ From: string(user.GetMeta().ID), To: string(item.GetMeta().ID), } if _, err := h.EdgePosts.CreateDocument(nil, edge); err != nil { log.Fatal(err) } log.WithFields(log.Fields{ "username": user.Username, "item": item.ID, "edge": edge, }).Trace("Add Posts edge") } } func (h *DBHelper) UserLikes(user *models.User, item *models.Item) { query := "FOR e IN edge_likes FILTER e._from == @from && e._to == @to RETURN e" cur, err := h.DB.Query(nil, query, map[string]interface{}{ "from": user.GetMeta().ID, "to": item.GetMeta().ID, }, ) defer cur.Close() if err != nil { log.Fatal(err) } if !cur.HasMore() { edge := models.Likes{ From: string(user.GetMeta().ID), To: string(item.GetMeta().ID), IsTopliker: false, } if _, err := h.EdgeLikes.CreateDocument(nil, edge); err != nil { log.Fatal(err) } log.WithFields(log.Fields{ "username": user.Username, "item": item.ID, "edge": edge, }).Trace("Add Likes edge") } } // Convenience Frontent for DBHelper.ItemTags so it can be used as relation func (h *DBHelper) UserTagged(user *models.User, item *models.Item) { h.ItemTags(item, user, models.Tags{}) } func (h *DBHelper) ItemTags(item *models.Item, user *models.User, edge models.Tags) { query := "FOR e IN edge_tags FILTER e._from == @from && e._to == @to RETURN e" cur, err := h.DB.Query(nil, query, map[string]interface{}{ "from": item.GetMeta().ID, "to": user.GetMeta().ID, }, ) defer cur.Close() if err != nil { log.Fatal(err) } if !cur.HasMore() { edge.From = string(item.GetMeta().ID) edge.To = string(user.GetMeta().ID) if _, err := h.EdgeTags.CreateDocument(nil, edge); err != nil { log.Fatal(err) } log.WithFields(log.Fields{ "username": user.Username, "item": item.ID, "edge": edge, }).Trace("Add Tags edge") } }
true
f1e22d5c5da7bb58738812cb157b06cc5e965c27
Go
happray/fastproxy
/http/startline_test.go
UTF-8
1,727
3.109375
3
[]
no_license
[]
no_license
package http import ( "bufio" "bytes" "errors" "io" "strings" "testing" ) func TestRespLine(t *testing.T) { testRespLineParse(t, "", io.EOF, "", 0, "") testRespLineParse(t, "HTTP/1.1 200 OK\r\n", nil, "HTTP/1.1", 200, "OK") testRespLineParse(t, "HTTP/1.1 200 OK\n", nil, "HTTP/1.1", 200, "OK") testRespLineParse(t, "HTTP/1.1 200 OK", io.EOF, "", 0, "") testRespLineParse(t, "HTTP/1.1\r\n", errRespLineNOProtocol, "", 0, "") testRespLineParse(t, "HTTP/1.1 \r\n", errRespLineNOStatusCode, "HTTP/1.1", 0, "") testRespLineParse(t, "HTTP/1.1 200\r\n", errRespLineNOStatusCode, "HTTP/1.1", 0, "") testRespLineParse(t, "HTTP/1.1 200 \r\n", nil, "HTTP/1.1", 200, "") testRespLineParse(t, "HTTP/1.1 OK \r\n", errors.New("fail to parse status status code"), "HTTP/1.1", 0, "") } func testRespLineParse(t *testing.T, line string, expErr error, expProtocol string, expCode int, expMsg string) { resp := &ResponseLine{} err := resp.Parse(bufio.NewReader(strings.NewReader(line))) if err != nil { if expErr == nil { t.Fatalf("unexpected error %s, expecting nil", err) } if !strings.Contains(err.Error(), expErr.Error()) { t.Fatalf("unexpected error %s, expecting %s", err, expErr) } } else if expErr != nil { t.Fatalf("unexpected nil error, expecting error %s,", expErr) } if !bytes.Equal(resp.GetProtocol(), []byte(expProtocol)) { t.Fatalf("unexpected protocol %s, expecting %s,", resp.GetProtocol(), expProtocol) } if resp.GetStatusCode() != expCode { t.Fatalf("unexpected status code %d, expecting %d,", resp.GetStatusCode(), expCode) } if !bytes.Equal(resp.GetStatusMessage(), []byte(expMsg)) { t.Fatalf("unexpected status msg %s, expecting %s,", resp.GetStatusMessage(), expMsg) } }
true
9642259849a52c4646389f76cf3b332c4a686553
Go
balwaninitu/learngo
/exercises/001-beginners/25-average/min-max/min-max-each-class/main.go
UTF-8
558
3.390625
3
[]
no_license
[]
no_license
package main import "fmt" func main() { s2 := [][]int{ {86, 80, 75, 82, 80, 70}, {40, 55, 60, 48, 50}, {90, 85, 30, 86, 78, 75, 54}, } var eachMax, eachMin int for i := 0; i < len(s2); i++ { max := s2[i][0] min := s2[i][0] for j := 0; j < len(s2[i]); j++ { if s2[i][j] > max { max = s2[i][j] } if s2[i][j] < min { min = s2[i][j] } eachMax = max eachMin = min } fmt.Printf("The highest mark of class %d is %d\n", i, eachMax) fmt.Printf("The lowest mark of class is %d %d\n", i, eachMin) } }
true
5ee3fc20fa2a46068c3d67af31742ce0efc99af9
Go
noomz/pg
/example_soft_delete_test.go
UTF-8
893
3.265625
3
[ "BSD-2-Clause" ]
permissive
[ "BSD-2-Clause" ]
permissive
package pg_test import ( "fmt" "time" ) type Flight struct { Id int Name string DeletedAt time.Time `pg:",soft_delete"` } func ExampleDB_Model_softDelete() { flight1 := &Flight{ Id: 1, } err := pgdb.Insert(flight1) panicIf(err) // Soft delete. err = pgdb.Delete(flight1) panicIf(err) // Count visible flights. count, err := pgdb.Model((*Flight)(nil)).Count() panicIf(err) fmt.Println("count", count) // Count soft deleted flights. deletedCount, err := pgdb.Model((*Flight)(nil)).Deleted().Count() panicIf(err) fmt.Println("deleted count", deletedCount) // Actually delete the flight. err = pgdb.ForceDelete(flight1) panicIf(err) // Count soft deleted flights. deletedCount, err = pgdb.Model((*Flight)(nil)).Deleted().Count() panicIf(err) fmt.Println("deleted count", deletedCount) // Output: count 0 // deleted count 1 // deleted count 0 }
true
3c9ceceef687325f8679514e62170f70d373512f
Go
jasonmimick/mongodb-atlas-kubernetes
/pkg/util/set/identifiable_test.go
UTF-8
4,643
3.453125
3
[ "Apache-2.0" ]
permissive
[ "Apache-2.0" ]
permissive
package set import ( "testing" "github.com/stretchr/testify/assert" ) type someID struct { // name is a "key" field used for merging name string // some other property. Indicates which exactly object was returned by an aggregation operation property string } func newSome(name, property string) someID { return someID{ name: name, property: property, } } func (s someID) Identifier() interface{} { return s.name } func Test_SetDifference(t *testing.T) { oneLeft := newSome("1", "left") twoLeft := newSome("2", "left") twoRight := newSome("2", "right") threeRight := newSome("3", "right") fourRight := newSome("4", "right") testCases := []struct { left []Identifiable right []Identifiable out []Identifiable }{ {left: []Identifiable{oneLeft, twoLeft}, right: []Identifiable{twoRight, threeRight}, out: []Identifiable{oneLeft}}, {left: []Identifiable{twoRight, threeRight}, right: []Identifiable{oneLeft, twoLeft}, out: []Identifiable{threeRight}}, {left: []Identifiable{oneLeft, twoLeft}, right: []Identifiable{threeRight, fourRight}, out: []Identifiable{oneLeft, twoLeft}}, // Empty {left: []Identifiable{}, right: []Identifiable{threeRight, fourRight}, out: []Identifiable{}}, {left: []Identifiable{threeRight, fourRight}, right: []Identifiable{}, out: []Identifiable{threeRight, fourRight}}, // Nil {left: nil, right: []Identifiable{threeRight, fourRight}, out: []Identifiable{}}, {left: []Identifiable{threeRight, fourRight}, right: nil, out: []Identifiable{threeRight, fourRight}}, } for _, testCase := range testCases { t.Run("", func(t *testing.T) { assert.Equal(t, testCase.out, differenceIdentifiable(testCase.left, testCase.right)) }) } } func Test_SetDifferenceCovariant(t *testing.T) { // check reflection magic to solve lack of covariance in go. The arrays are declared as '[]someId' instead of // '[]Identifiable' oneLeft := newSome("1", "left") twoLeft := newSome("2", "left") twoRight := newSome("2", "right") threeRight := newSome("3", "right") leftNotIdentifiable := []someID{oneLeft, twoLeft} rightNotIdentifiable := []someID{twoRight, threeRight} assert.Equal(t, []Identifiable{oneLeft}, Difference(leftNotIdentifiable, rightNotIdentifiable)) assert.Equal(t, []Identifiable{threeRight}, Difference(rightNotIdentifiable, leftNotIdentifiable)) } func Test_SetIntersection(t *testing.T) { oneLeft := newSome("1", "left") twoLeft := newSome("2", "left") twoRight := newSome("2", "right") threeRight := newSome("3", "right") fourRight := newSome("4", "right") testCases := []struct { left []Identifiable right []Identifiable out [][]Identifiable }{ // intersectionIdentifiable on "2" {left: []Identifiable{oneLeft, twoLeft}, right: []Identifiable{twoRight, threeRight}, out: [][]Identifiable{pair(twoLeft, twoRight)}}, {left: []Identifiable{twoRight, threeRight}, right: []Identifiable{oneLeft, twoLeft}, out: [][]Identifiable{pair(twoRight, twoLeft)}}, // No intersection {left: []Identifiable{oneLeft, twoLeft}, right: []Identifiable{threeRight, fourRight}, out: [][]Identifiable{}}, {left: []Identifiable{threeRight, fourRight}, right: []Identifiable{oneLeft, twoLeft}, out: [][]Identifiable{}}, // Empty {left: []Identifiable{}, right: []Identifiable{threeRight, fourRight}, out: [][]Identifiable{}}, {left: []Identifiable{threeRight, fourRight}, right: []Identifiable{}, out: [][]Identifiable{}}, // Nil {left: nil, right: []Identifiable{threeRight, fourRight}, out: [][]Identifiable{}}, {left: []Identifiable{threeRight, fourRight}, right: nil, out: [][]Identifiable{}}, } for _, testCase := range testCases { t.Run("", func(t *testing.T) { assert.Equal(t, testCase.out, intersectionIdentifiable(testCase.left, testCase.right)) }) } } func Test_SetIntersectionCovariant(t *testing.T) { oneLeft := newSome("1", "left") oneRight := newSome("1", "right") twoLeft := newSome("2", "left") twoRight := newSome("2", "right") threeRight := newSome("3", "right") // check reflection magic to solve lack of covariance in go. The arrays are declared as '[]someId' instead of // '[]Identifiable' leftNotIdentifiable := []someID{oneLeft, twoLeft} rightNotIdentifiable := []someID{oneRight, twoRight, threeRight} assert.Equal(t, [][]Identifiable{pair(oneLeft, oneRight), pair(twoLeft, twoRight)}, Intersection(leftNotIdentifiable, rightNotIdentifiable)) assert.Equal(t, [][]Identifiable{pair(oneRight, oneLeft), pair(twoRight, twoLeft)}, Intersection(rightNotIdentifiable, leftNotIdentifiable)) } func pair(left, right Identifiable) []Identifiable { return []Identifiable{left, right} }
true
c9fe3bedc6d551b82ad5581d9b93faa768f526f4
Go
BRBussy/goback
/pkg/exception/errors.go
UTF-8
506
2.578125
3
[]
no_license
[]
no_license
package exception import "fmt" type ErrUnexpected struct { Err error } func NewErrUnexpected(err error) *ErrUnexpected { return &ErrUnexpected{Err: err} } func (e *ErrUnexpected) Error() string { return fmt.Sprintf("unexpected backend error: %v", e.Err) } func (e *ErrUnexpected) Unwrap() error { return e.Err } type ErrNoChangesMade struct { } func NewErrNoChangesMade() *ErrNoChangesMade { return &ErrNoChangesMade{} } func (e *ErrNoChangesMade) Error() string { return "no changes made" }
true
85a234877d3384b8cddd85f21e3fdb99c7724e5b
Go
jnst/x-go
/grpcapp/binary.go
UTF-8
483
2.53125
3
[ "MIT" ]
permissive
[ "MIT" ]
permissive
package grpcapp import ( "bytes" "encoding/gob" bytefmt "github.com/labstack/gommon/bytes" "google.golang.org/protobuf/proto" ) func binarySize(val interface{}) string { if message, ok := val.(proto.Message); ok { if b, err := proto.Marshal(message); err == nil { return bytefmt.Format(int64(len(b))) } } var buff bytes.Buffer enc := gob.NewEncoder(&buff) err := enc.Encode(val) if err != nil { return "0B" } return bytefmt.Format(int64(len(buff.Bytes()))) }
true
7b2aab5b4ed87d45b34dafcd04bdec563adca219
Go
ChristopherRabotin/goknock
/actions.go
UTF-8
288
3.09375
3
[]
no_license
[]
no_license
package main import "fmt" import "net" // Action is a polymorphic interface. Sequences and their actions must be // defined in main.go. type Action interface { launch(conn net.Conn) } type Echo struct{} func (act Echo) launch(conn net.Conn) { fmt.Println("Action Echo launched.") }
true
757de610085b8f97f6844d593f569e14d5e6ae78
Go
sineto/data-structs
/lifo/lifo_test.go
UTF-8
572
3.484375
3
[]
no_license
[]
no_license
package lifo import ( "reflect" "testing" ) func TestLifo(t *testing.T) { got := NewStack() got.Push(&Item{1}) got.Push(&Item{2}) assertEqual := func(t *testing.T, got, want []*Item) { t.Helper() if !reflect.DeepEqual(got, want) { t.Errorf("got %v, want %v", got, want) } } t.Run("push an item into stack", func(t *testing.T) { want := []*Item{{1}, {2}} assertEqual(t, got.Items, want) }) t.Run("pop an item from stack", func(t *testing.T) { got.Push(&Item{3}) want := []*Item{{1}, {2}} got.Pop() assertEqual(t, got.Items, want) }) }
true
1bfecc8a5b0b4f0f05753f82163064ea99bd7aaf
Go
treydock/tsm_exporter
/config/config.go
UTF-8
2,315
2.515625
3
[ "Apache-2.0" ]
permissive
[ "Apache-2.0" ]
permissive
// Copyright 2020 Trey Dockendorf // 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 config import ( "fmt" "os" "sync" yaml "gopkg.in/yaml.v3" ) type Config struct { Targets map[string]*Target `yaml:"targets"` } type SafeConfig struct { sync.RWMutex C *Config } type Target struct { sync.Mutex Name string Servername string `yaml:"servername"` Id string `yaml:"id"` Password string `yaml:"password"` Timezone string `yaml:"timezone"` LibraryName string `yaml:"library_name"` Schedules []string `yaml:"schedules"` ReplicationNodeNames []string `yaml:"replication_node_names"` Collectors []string `yaml:"collectors,omitempty"` VolumeUsageMap map[string]string `yaml:"volumeusage_map,omitempty"` SummaryActivities []string `yaml:"summary_activities,omitempty"` } func (sc *SafeConfig) ReloadConfig(configFile string) error { var c = &Config{} yamlReader, err := os.Open(configFile) if err != nil { return fmt.Errorf("Error reading config file %s: %s", configFile, err) } defer yamlReader.Close() decoder := yaml.NewDecoder(yamlReader) decoder.KnownFields(true) if err := decoder.Decode(c); err != nil { return fmt.Errorf("Error parsing config file %s: %s", configFile, err) } for key := range c.Targets { target := c.Targets[key] target.Name = key if target.Servername == "" { target.Servername = key } if target.Id == "" { return fmt.Errorf("Target %s must define 'id' value", key) } if target.Password == "" { return fmt.Errorf("Target %s must define 'password' value", key) } c.Targets[key] = target } sc.Lock() sc.C = c sc.Unlock() return nil }
true
615e1b06f5c9a9d2c9916dc0c100bcc89c6711ff
Go
normegil/dionysos
/internal/model/number.go
UTF-8
420
3.421875
3
[]
no_license
[]
no_license
package model import "fmt" type Natural struct { number int } func NewNatural(number int) (*Natural, error) { if number < 0 { return nil, fmt.Errorf("%d is not a natural number", number) } return &Natural{number: number}, nil } func MustNewNatural(number int) *Natural { natural, err := NewNatural(number) if err != nil { panic(err) } return natural } func (n Natural) Number() int { return n.number }
true
611337864005d402d89217c287b45c1f1fa74543
Go
yudeguang/gather
/pool.go
UTF-8
2,749
3.046875
3
[ "MIT" ]
permissive
[ "MIT" ]
permissive
package gather import ( "fmt" "sync" "time" ) type Pool struct { unUsed sync.Map //空闲的Pool下标 pool []*GatherStruct //缓存池 locker sync.Mutex } var errNoFreeClinetFind = fmt.Errorf("time out,no free client find") //池化技术 同时申明若干个,以备使用,避免频繁的申明回收,最多100个 func NewGatherUtilPool(headers map[string]string, proxyURL string, timeOut int, isCookieLogOpen bool, num int) *Pool { if num <= 0 { num = 1 } if num > 100 { num = 100 } //重设一下maxIdleConns以适应不同的需求 if num >= 1 && num <= 100 { maxIdleConns = num } var gp Pool for i := 0; i < num; i++ { ga := NewGatherUtil(headers, proxyURL, timeOut, isCookieLogOpen) gp.pool = append(gp.pool, ga) gp.unUsed.Store(i, true) } return &gp } //从缓存池中 随便获取一个,然后再利用 func (p *Pool) Get(URL, refererURL string) (html, redirectURL string, err error) { pool_index := p.getPoolIndex() if pool_index == -1 { return "", "", errNoFreeClinetFind } defer p.unUsed.Store(pool_index, true) return p.pool[pool_index].Get(URL, refererURL) } //从缓存池中 随便获取一个,然后再利用 func (p *Pool) GetUtil(URL, refererURL, cookies string) (html, redirectURL string, err error) { pool_index := p.getPoolIndex() if pool_index == -1 { return "", "", errNoFreeClinetFind } defer p.unUsed.Store(pool_index, true) return p.pool[pool_index].GetUtil(URL, refererURL, cookies) } //从缓存池中 随便获取一个,然后再利用 func (p *Pool) Post(URL, refererURL string, postMap map[string]string) (html, redirectURL string, err error) { pool_index := p.getPoolIndex() if pool_index == -1 { return "", "", errNoFreeClinetFind } defer p.unUsed.Store(pool_index, true) return p.pool[pool_index].Post(URL, refererURL, postMap) } //从缓存池中 随便获取一个,然后再利用 func (p *Pool) PostUtil(URL, refererURL, cookies string, postMap map[string]string) (html, redirectURL string, err error) { pool_index := p.getPoolIndex() if pool_index == -1 { return "", "", errNoFreeClinetFind } defer p.unUsed.Store(pool_index, true) return p.pool[pool_index].PostUtil(URL, refererURL, cookies, postMap) } //设置超时30秒超时 ,如果没有找到就返回-1表示失败 func (p *Pool) getPoolIndex() int { p.locker.Lock() defer p.locker.Unlock() pool_index := -1 for num := 0; num < 600; num++ { p.unUsed.Range(func(k, v interface{}) bool { pool_index = k.(int) if pool_index == -1 { return true } else { //false表示不再继续遍历 return false } }) if pool_index != -1 { p.unUsed.Delete(pool_index) break } time.Sleep(time.Millisecond * 100) } return pool_index }
true
8d57e9af9316de370555c3313636b7704c159f8f
Go
wsloong/my_leetcode
/double_pointer/20200609/today/fruit-into-baskets.go
UTF-8
2,709
3.9375
4
[]
no_license
[]
no_license
/* 904. 水果成篮 在一排树中,第 i 棵树产生 tree[i] 型的水果。 你可以从你选择的任何树开始,然后重复执行以下步骤: 把这棵树上的水果放进你的篮子里。如果你做不到,就停下来。 移动到当前树右侧的下一棵树。如果右边没有树,就停下来。 请注意,在选择一颗树后,你没有任何选择:你必须执行步骤 1,然后执行步骤 2,然后返回步骤 1,然后执行步骤 2,依此类推,直至停止。 你有两个篮子,每个篮子可以携带任何数量的水果,但你希望每个篮子只携带一种类型的水果。 用这个程序你能收集的水果总量是多少? 示例 1: 输入:[1,2,1] 输出:3 解释:我们可以收集 [1,2,1]。 示例 2: 输入:[0,1,2,2] 输出:3 解释:我们可以收集 [1,2,2]. 如果我们从第一棵树开始,我们将只能收集到 [0, 1]。 示例 3: 输入:[1,2,3,2,2] 输出:4 解释:我们可以收集 [2,3,2,2]. 如果我们从第一棵树开始,我们将只能收集到 [1, 2]。 示例 4: 输入:[3,3,3,1,2,1,1,2,3,3,4] 输出:5 解释:我们可以收集 [1,2,1,1,2]. 如果我们从第一棵树或第八棵树开始,我们将只能收集到 4 个水果。   提示: 1 <= tree.length <= 40000 0 <= tree[i] < tree.length 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/fruit-into-baskets 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 */ func totalFruit(tree []int) int { result, i := 0, 0 count := newCounter() for j := range tree { count.Add(tree[j], 1) for count.Size() >= 3 { count.Add(tree[i], -1) if count.Get(tree[i]) == 0 { count.Remove(tree[i]) } i++ } result = max(result, j - i + 1) } return result } func max(v1, v2 int) int { if v1 >= v2 { return v1 } return v2 } type Counter struct { item map[int]int } func newCounter() *Counter { return &Counter{ item: make(map[int]int), } } func (c *Counter) Get(k int) int { value, ok := c.item[k] if ok { return value } return 0 } func (c *Counter) Add(k, v int) { c.item[k] = c.Get(k) + v } func (c *Counter) Size() int { return len(c.item) } func (c *Counter) Remove(k int) { delete(c.item, k) } // ====== 早上的 删除排序数组中的重复项 === /* 思路回顾 题目虽然是删除但是跟确切来说是交换 使用双指针,i, j 如果nums[i] != nums[j], i++, nums[i] = nums[j] */ func removeDuplicates(nums []int) int { length, i := len(nums), 0 for j := 1; j < length; j++ { if nums[i] != nums[j] { i++ nums[i]= nums[j] } } return i + 1 }
true
0474e084e77e36d0b09a4242bd57a26b0555819f
Go
wikimedia/OKAPI
/service/server/projects/aggregate_test.go
UTF-8
4,360
2.515625
3
[ "Apache-2.0" ]
permissive
[ "Apache-2.0" ]
permissive
package projects import ( "bytes" "context" "encoding/json" "errors" "fmt" "io" "io/ioutil" "okapi-data-service/models" schema "okapi-data-service/schema/v3" pb "okapi-data-service/server/projects/protos" "testing" "time" "github.com/go-pg/pg/v10/orm" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/mock" ) const aggregateTestProjID = 1 const aggregateTestProjDbName = "enwki" const aggregateTestProjSiteName = "Wikipedia" const aggregateTestProjSiteCode = "wiki" const aggregateTestProjSiteURL = "https://en.wikipedia.org/" const aggregateTestProjLang = "en" const aggregateTestProjActive = true const aggregateTestProjLangName = "English" const aggregateTestProjLangLocalName = "Eng" const aggregateTestStorageErr = "key does not exist" const aggregateTestNsID = schema.NamespaceArticle var aggregateTestProjects = []models.Project{ { ID: aggregateTestProjID, DbName: aggregateTestProjDbName, SiteName: aggregateTestProjSiteName, SiteCode: aggregateTestProjSiteCode, SiteURL: aggregateTestProjSiteURL, Lang: aggregateTestProjLang, Active: aggregateTestProjActive, Language: &models.Language{ Name: aggregateTestProjLangName, LocalName: aggregateTestProjLangLocalName, Code: aggregateTestProjLang, }, }, } type aggregateStorageMock struct { mock.Mock } func (s *aggregateStorageMock) Put(path string, body io.Reader) error { return s.Called(path, body).Error(0) } func (s *aggregateStorageMock) Get(path string) (io.ReadCloser, error) { args := s.Called(path) return args.Get(0).(io.ReadCloser), args.Error(1) } type aggregateRepoMock struct { mock.Mock count int } func (r *aggregateRepoMock) Find(_ context.Context, model interface{}, _ func(*orm.Query) *orm.Query, _ ...interface{}) error { args := r.Called(model) if r.count < len(aggregateTestProjects) { *model.(*[]models.Project) = append(*model.(*[]models.Project), aggregateTestProjects[r.count]) r.count++ } return args.Error(0) } func TestAggregate(t *testing.T) { assert := assert.New(t) ctx := context.Background() store := new(aggregateStorageMock) repo := new(aggregateRepoMock) repo.On("Find", &[]models.Project{}).Return(nil) exports := []schema.Project{} schemas := []schema.Project{} for idx, proj := range aggregateTestProjects { version := "version_hash" dateModified := time.Now() export := schema.Project{ Name: proj.SiteName, Identifier: proj.DbName, URL: proj.SiteURL, Version: &version, DateModified: &dateModified, Size: &schema.Size{ Value: 8.68 + float64(idx), UnitText: "MB", }, InLanguage: &schema.Language{ Name: proj.Language.LocalName, Identifier: proj.Language.Code, }, } fmt.Sprintln(export) exports = append(exports, export) body, err := json.Marshal(export) assert.NoError(err) store. On("Get", fmt.Sprintf("export/%s/%s_%d.json", proj.DbName, proj.DbName, schema.NamespaceCategory)). Return(ioutil.NopCloser(bytes.NewReader([]byte{})), errors.New(aggregateTestStorageErr)) store. On("Get", fmt.Sprintf("export/%s/%s_%d.json", proj.DbName, proj.DbName, schema.NamespaceFile)). Return(ioutil.NopCloser(bytes.NewReader([]byte{})), errors.New(aggregateTestStorageErr)) store. On("Get", fmt.Sprintf("export/%s/%s_%d.json", proj.DbName, proj.DbName, schema.NamespaceTemplate)). Return(ioutil.NopCloser(bytes.NewReader([]byte{})), errors.New(aggregateTestStorageErr)) store. On("Get", fmt.Sprintf("export/%s/%s_%d.json", proj.DbName, proj.DbName, aggregateTestNsID)). Return(ioutil.NopCloser(bytes.NewReader(body)), nil) schemas = append(schemas, schema.Project{ Name: proj.SiteName, Identifier: proj.DbName, URL: proj.SiteURL, InLanguage: &schema.Language{ Name: proj.Language.LocalName, Identifier: proj.Language.Code, }, }) } data, err := json.Marshal(&schemas) assert.NoError(err) store.On("Put", "public/projects.json", bytes.NewReader(data)).Return(nil) data, err = json.Marshal(&exports) assert.NoError(err) store.On("Put", fmt.Sprintf("public/exports_%d.json", aggregateTestNsID), bytes.NewReader(data)).Return(nil) res, err := Aggregate(ctx, new(pb.AggregateRequest), repo, store) assert.NoError(err) assert.NotZero(res.Total) assert.Zero(res.Errors) }
true
3e163d47cf9251974d41099b28ec467c50a151c1
Go
SecurityNeo/ReadingNotes
/Coding/Go/数据结构和算法/双向链表.go
UTF-8
3,772
4.34375
4
[]
no_license
[]
no_license
package main import ( "fmt" ) /* 双向链表: 1、头节点不存储数据 2、头节点指向链表中的第一个数据 3、辅助节点,类似于辅助指针,用于链表节点的定位,辅助节点先指向头节点 4、双向链表的两种插入方式: 1)新数据总是在链表尾部插入(insertHero) 2)新数据按照ID从小到大插入(insertHeroByID) 注意:顺序插入时建议先将待插入节点的pre指向它前一个节点,next指向它后一个节点,然后再修改其前一个 和后一个节点分别指向自己。 5、删除节点时一定要注意判断待删除节点是不是链表的最后一个节点 */ // 示例: 使用单链表实现水浒英雄管理 type HeroNode struct { ID int name string next *HeroNode pre *HeroNode } func insertHero(head *HeroNode, newHeroNode *HeroNode) { // 创建辅助节点,类似于辅助指针,用于链表节点的定位,辅助节点先指向头节点 tempNode := head // 首先找到最后边的节点 for { if tempNode.next == nil { break } tempNode = tempNode.next } // tempNode.next = newHeroNode newHeroNode.pre = tempNode } // 按照ID从小到大的顺序插入新节点 func insertHeroByID(head *HeroNode, newHeroNode *HeroNode) { tempNode := head for { if tempNode.next == nil { tempNode.next = newHeroNode newHeroNode.pre = tempNode break // 如果顺序为从大到小,修改">"为"<"即可 } else if tempNode.next.ID > newHeroNode.ID { newHeroNode.next = tempNode.next newHeroNode.pre = tempNode tempNode.next.pre = newHeroNode tempNode.next = newHeroNode break } else if tempNode.next.ID == newHeroNode.ID { fmt.Printf("ID %d conflict!\n", newHeroNode.ID) break } tempNode = tempNode.next } } // 根据ID删除链表中的数据 func deleteHeroNodeByID(head *HeroNode, id int){ tempNode := head for { if tempNode.next == nil { fmt.Printf("ID %d does not exist! \n", id) break }else if tempNode.next.ID == id { if tempNode.next.next == nil { tempNode.next = nil return }else { tempNode.next = tempNode.next.next tempNode.next.pre = tempNode return } } tempNode = tempNode.next } } // 顺序打印 func showHero(head *HeroNode) { tempNode := head if tempNode.next == nil { fmt.Println("There is no hero!") return } for { // 先打印下一个节点数据,然后辅助节点往后移,当后移之后辅助节点指向为空(tempNode.next),说明已完成整个链表的遍历 fmt.Printf("[%d %s] --> ", tempNode.next.ID, tempNode.next.name) tempNode = tempNode.next if tempNode.next == nil { break } } fmt.Println() } // 逆序打印 func showHeroInReverse(head *HeroNode) { tempNode := head if tempNode.next == nil { fmt.Println("There is no hero!") return } // 先找到链表末尾 for { if tempNode.next == nil { break } tempNode = tempNode.next } for { // 直接打印当前节点数据,然后辅助节点往前移,当前移之后辅助节点指向为空(tempNode.pre),说明已完成整个链表的遍历 fmt.Printf("[%d %s] --> ", tempNode.ID, tempNode.name) tempNode = tempNode.pre if tempNode.pre == nil { break } } fmt.Println() } func main() { head := &HeroNode{} // 定义测试数据 hero1 := &HeroNode{ ID: 1, name: "宋江", } hero2 := &HeroNode{ ID: 2, name: "吴用", } hero3 := &HeroNode{ ID: 3, name: "卢俊义", } hero4 := &HeroNode{ ID: 3, name: "林冲", } insertHeroByID(head, hero1) insertHeroByID(head, hero3) insertHeroByID(head, hero2) insertHeroByID(head, hero4) showHero(head) showHeroInReverse(head) deleteHeroNodeByID(head, 3) showHero(head) showHeroInReverse(head) }
true
bfc07edbcbfd3a3c6c67b7eee5583b36cc808cff
Go
isabella232/honeycomb-goji
/middleware.go
UTF-8
2,233
2.703125
3
[ "Apache-2.0" ]
permissive
[ "Apache-2.0" ]
permissive
package gojihoney import ( "context" "net/http" "time" "goji.io/middleware" "goji.io/pat" "goji.io/pattern" libhoney "github.com/honeycombio/libhoney-go" ) const ( libhoneyEventContextKey = "libhoneyEvent" ) func GetLibhoneyEvent(ctx context.Context) *libhoney.Event { if event, ok := ctx.Value(libhoneyEventContextKey).(*libhoney.Event); ok { return event } return nil } // Middleware: log http.Requests and response HTTP status/content-length/time // to Hound. func LogRequestToHoneycomb(varPrefix string) func(http.Handler) http.Handler { return func(handler http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { ctx := r.Context() before := time.Now() event := libhoney.NewEvent() event.Add(r) gojiPattern := middleware.Pattern(ctx) if gojiPattern != nil { // log our pattern event.AddField("GojiPattern", gojiPattern.(*pat.Pattern).String()) } // and the variables if variables, ok := ctx.Value(pattern.AllVariables).(map[pattern.Variable]interface{}); ok { for k, v := range variables { event.AddField(varPrefix+string(k), v.(string)) } } responseWriter := newResponseWriterProxy(w) handler.ServeHTTP(responseWriter, r.WithContext(context.WithValue(ctx, libhoneyEventContextKey, event))) event.AddField("ResponseHttpStatus", responseWriter.Status()) event.AddField("ResponseContentLength", responseWriter.Length()) event.AddField("ResponseTime_ms", time.Since(before).Seconds()*1000) event.Send() }) } } type responseWriterProxy struct { http.ResponseWriter statusCode int length int } func newResponseWriterProxy(inner http.ResponseWriter) *responseWriterProxy { return &responseWriterProxy{inner, 0, 0} } func (rw *responseWriterProxy) Status() int { return rw.statusCode } func (rw *responseWriterProxy) Length() int { return rw.length } func (rw *responseWriterProxy) Write(bytes []byte) (int, error) { if rw.statusCode == 0 { rw.statusCode = 200 } rv, err := rw.ResponseWriter.Write(bytes) rw.length += rv return rv, err } func (rw *responseWriterProxy) WriteHeader(statusCode int) { rw.statusCode = statusCode rw.ResponseWriter.WriteHeader(statusCode) }
true
0d2136710bd1edd00a4355ebe2be4a570f636272
Go
tangtj/leetcode-go
/155.go
UTF-8
573
3.734375
4
[]
no_license
[]
no_license
package leetcode import "math" type MinStack struct { stack []int min int } /** initialize your data structure here. */ func Constructor() MinStack { return MinStack{ min: math.MinInt64, } } func (this *MinStack) Push(val int) { this.stack = append(this.stack, val) } func (this *MinStack) Pop() { this.stack = this.stack[:len(this.stack)-1] } func (this *MinStack) Top() int { return this.stack[len(this.stack)-1] } func (this *MinStack) GetMin() int { min := math.MaxInt64 for _, i := range this.stack { if i < min { min = i } } return min }
true
0f835becd49f32b2307ca1332cfaea2e4feca8ae
Go
lylex/leetcode
/189_rotate_array/main.go
UTF-8
1,076
3.890625
4
[ "MIT" ]
permissive
[ "MIT" ]
permissive
package main import ( "fmt" ) // 这里是一个非常简单粗暴的解法 func rotate0(nums []int, k int) { length := len(nums) if length == 0 { return } k %= length for i := 0; i < k; i++ { temp := nums[length-1] for j := length - 2; j >= 0; j-- { nums[j+1] = nums[j] } nums[0] = temp } } // 这里涉及到一个切片作为参数,如何修改元素的问题,直接修改了便是了 // 可以将切片理解为一个mallock出来的一个堆内存,即便复制了,这个堆内存还是共享的 func rotate(nums []int, k int) { reverse := func(a []int, start, end int) { for i, j := start, end; i < j; i, j = i+1, j-1 { a[i], a[j] = a[j], a[i] } } length := len(nums) if length == 0 { return } k = k % length reverse(nums, 0, length-k-1) reverse(nums, length-k, length-1) reverse(nums, 0, length-1) } func main() { input := []int{1, 2, 3, 4, 5, 6, 7} rotate(input, 3) fmt.Println(input) }
true
45c6d1f3214861ddebe8a2f09c3b226f4c51aade
Go
itslearninggermany/itsImse
/link.go
UTF-8
3,997
2.8125
3
[]
no_license
[]
no_license
package itsImse import ( "github.com/jinzhu/gorm" "github.com/pkg/errors" ) type Link struct { Id string Description string Language string FormatAny bool FormatAudio bool FormatImage bool FormatInteractive bool FormatText bool FormatVideo bool Keywords string // List with commas IntendedEndUserRoleLearner bool IntendedEndUserRoleInstructor bool IntendedEndUserRoleMentor bool Grade string ThumbnailUrl string EducationalIntentInstructional bool EducationalIntentPractice bool EducationalIntentProfessionalDevelopment bool EducationalIntentAssessment bool EducationalIntentActivity bool Publisher string Title string Url string basicData ItslearningBasicData } type ItslearningBasicData struct { userSyncKey string vendorID string location struct { Course bool Library bool } scope struct { Private bool School bool Site bool Community bool Custom bool } } func NewLink() *Link { return new(Link) } func NewItslearningBasicData() *ItslearningBasicData { return new(ItslearningBasicData) } func (p *ItslearningBasicData) SetItslearningBasicData(vendorID, location, userSyncKey, scope string, locationCourse, locationLibrary, scopePrivate, scopeSchool, scopeSite, scopeCommunity, scopeCustom bool) (err error, r *ItslearningBasicData) { p.vendorID = vendorID p.userSyncKey = userSyncKey p.location.Course = locationCourse p.location.Library = locationLibrary count := 0 if scopeSite { count++ } if scopeSchool { count++ } if scopeCommunity { count++ } if scopeCustom { count++ } if scopePrivate { count++ } if count > 1 { err = errors.New("Scope can only one Item!") } p.scope.Site = scopeSite p.scope.School = scopeSchool p.scope.Community = scopeCommunity p.scope.Custom = scopeCustom p.scope.Private = scopePrivate r = p return } func (p *Link) SetLinkData(title, description, language, format, intendedEndUserRole, grade, thumbnailUrl, educationalIntent, publisher, url, id string, keywords []string, EducationalIntentInstructional, EducationalIntentPractice, EducationalIntentProfessionalDevelopment, EducationalIntentAssessment, EducationalIntentActivity, IntendedEndUserRoleLearner, IntendedEndUserRoleInstructor, IntendedEndUserRoleMentor bool, FormatAny, FormatAudio, FortmatImage, FormatInteractive, FormatText, FormatVideo bool) (err error, r *Link) { p.Id = id p.Title = title p.Description = description p.Language = language count := 0 if FormatAny { count++ } if FormatAudio { count++ } if FormatInteractive { count++ } if FormatText { count++ } if FormatVideo { count++ } if FortmatImage { count++ } if count > 1 { err = errors.New("Only one Format is allowed!") } p.FormatText = FormatText p.FormatAny = FormatAny p.FormatAudio = FormatAudio p.FormatImage = FortmatImage p.FormatInteractive = FormatInteractive p.FormatVideo = FormatVideo tmp := "" for i := 0; i < len (keywords); i++ { if i == 0 { tmp = keywords[i] }else { tmp = tmp + "," + keywords[i] } } p.Keywords = tmp p.IntendedEndUserRoleInstructor = IntendedEndUserRoleInstructor p.IntendedEndUserRoleLearner = IntendedEndUserRoleLearner p.IntendedEndUserRoleMentor = IntendedEndUserRoleMentor p.Grade = grade p.ThumbnailUrl = thumbnailUrl p.EducationalIntentActivity = EducationalIntentActivity p.EducationalIntentAssessment = EducationalIntentAssessment p.EducationalIntentInstructional = EducationalIntentInstructional p.EducationalIntentPractice = EducationalIntentPractice p.EducationalIntentProfessionalDevelopment = EducationalIntentProfessionalDevelopment p.Publisher = publisher p.Url = url r = p return } func (p *Link) SetItslearningBasicData(data ItslearningBasicData) *Link { p.basicData = data return p } //TODO: func (p *Link) StoreInDataBase(db *gorm.DB) *Link { return p }
true
0fe1f96e4f1e97f6b5946b8ee9b18eb9661f6153
Go
itchio/lake
/tlc/permissions.go
UTF-8
1,460
2.765625
3
[ "MIT" ]
permissive
[ "MIT" ]
permissive
package tlc import ( "io" "github.com/itchio/lake" "github.com/pkg/errors" ) const minScannedFileSize = 4 func (c *Container) FixPermissions(pool lake.Pool) error { defer pool.Close() buf := make([]byte, minScannedFileSize) for index, f := range c.Files { if f.Size < minScannedFileSize { continue } r, err := pool.GetReader(int64(index)) if err != nil { return errors.WithStack(err) } _, err = io.ReadFull(r, buf) if err != nil { return errors.WithStack(err) } if isExecutable(buf) { f.Mode |= 0o111 } } return nil } // cf. https://github.com/itchio/fnout/blob/master/src/index.js func isExecutable(buf []byte) bool { // intel Mach-O executables start with 0xCEFAEDFE or 0xCFFAEDFE // (old PowerPC Mach-O executables started with 0xFEEDFACE) if (buf[0] == 0xCE || buf[0] == 0xCF) && buf[1] == 0xFA && buf[2] == 0xED && buf[3] == 0xFE { return true } // Mach-O universal binaries start with 0xCAFEBABE // it's Apple's 'fat binary' stuff that contains multiple architectures if buf[0] == 0xCA && buf[1] == 0xFE && buf[2] == 0xBA && buf[3] == 0xBE { return true } // ELF executables start with 0x7F454C46 // (e.g. 0x7F + 'ELF' in ASCII) if buf[0] == 0x7F && buf[1] == 0x45 && buf[2] == 0x4C && buf[3] == 0x46 { return true } // Shell scripts start with a shebang (#!) // https://en.wikipedia.org/wiki/Shebang_(Unix) if buf[0] == 0x23 && buf[1] == 0x21 { return true } return false }
true
3195bef28a246bcf2ef9ab85827317964e085657
Go
jackparra253/Go-Ya
/ejercicio007.go
UTF-8
685
3.78125
4
[]
no_license
[]
no_license
//Realizar un programa que solicite por teclado cuatro valores numéricos enteros e informar su suma y promedio package main import "fmt" func main(){ var numeroUno, numeroDos, numeroTres, numeroCuatro, suma, promedio int fmt.Print("Ingrese un número: ") fmt.Scan(&numeroUno) fmt.Print("Ingrese un número: ") fmt.Scan(&numeroDos) fmt.Print("Ingrese un número: ") fmt.Scan(&numeroTres) fmt.Print("Ingrese un número: ") fmt.Scan(&numeroCuatro) suma = numeroUno + numeroDos + numeroTres + numeroCuatro promedio = suma / 4 fmt.Println("El valor de la suma es: ", suma) fmt.Println("El valor del promedio es: ", promedio) }
true
b53cd0d5624587c1b534b2bdf68e85394d08d00c
Go
ryan2333/leetcode
/342isPowerOfFour/main.go
UTF-8
595
3.46875
3
[]
no_license
[]
no_license
package main import "fmt" func isPowerOfFour(num int) bool { if num < 1 { return false } var check = 1 for num >= check { if num == check { return true } check <<= 2 } return false } func isPowerOfFour1(num int) bool { if num < 1 { return false } if num&(num-1) == 0 && (num&0x55555555) == num { return true } return false } func isPowerOfFour2(num int) bool { if num < 1 { return false } for num > 1 && num%4 == 0 { num /= 4 } return num == 1 } func main() { fmt.Println(isPowerOfFour1(4)) fmt.Println(4 & 3) fmt.Println(isPowerOfFour1(64)) }
true
33e942d98795c53d99f19a00f08cea1c888ff5ef
Go
ilgooz/service-devcon-update
/main.go
UTF-8
1,585
2.53125
3
[]
no_license
[]
no_license
package main import ( "context" "io/ioutil" "log" "net/http" "os" "strings" "time" api "github.com/mesg-foundation/core/api/service" "google.golang.org/grpc" ) var files = make(map[string]string) const index = "https://devcon.ethereum.org/" const js = "https://devcon.ethereum.org/dist/main.bundle.js" const css = "https://devcon.ethereum.org/dist/main.bundle.css" func handleError(err error) { if err != nil { log.Fatalln(err) } } func fetchFile(endpoint string) (file string, err error) { resp, err := http.Get(endpoint) if err != nil { return "", err } html, err := ioutil.ReadAll(resp.Body) if err != nil { return "", err } return string(html), nil } func isFileUpdatedAndUpdateMap(endpoint string) (updated bool) { file, err := fetchFile(endpoint) if err != nil { log.Println("Error", err) return false } if strings.Compare(files[endpoint], file) != 0 { files[endpoint] = file return true } return false } func main() { var err error ctx := context.Background() connection, err := grpc.Dial(os.Getenv("MESG_ENDPOINT"), grpc.WithInsecure()) handleError(err) mesg := api.NewServiceClient(connection) for { indexUpdated := isFileUpdatedAndUpdateMap(index) jsUpdated := isFileUpdatedAndUpdateMap(js) cssUpdated := isFileUpdatedAndUpdateMap(css) if indexUpdated || jsUpdated || cssUpdated { log.Println("update") _, err := mesg.EmitEvent(ctx, &api.EmitEventRequest{ Token: os.Getenv("MESG_TOKEN"), EventKey: "update", EventData: "{}", }) handleError(err) } time.Sleep(1 * time.Second) } }
true
3718f0bad9a96b9c5619c7ef4850f8ffb824cedd
Go
saonam/go-clean-architecture-web-application-boilerplate
/app/infrastructure/router.go
UTF-8
797
2.625
3
[ "MIT" ]
permissive
[ "MIT" ]
permissive
package infrastructure import ( "net/http" "os" "github.com/bmf-san/go-clean-architecture-web-application-boilerplate/app/interfaces" "github.com/bmf-san/go-clean-architecture-web-application-boilerplate/app/usecases" ) // Dispatch is handle routing func Dispatch(logger usecases.Logger, sqlHandler interfaces.SQLHandler, mux *http.ServeMux) { userController := interfaces.NewUserController(sqlHandler, logger) postController := interfaces.NewPostController(sqlHandler, logger) // TODO: Maybe I'll implement a routing package ... mux.HandleFunc("/users", userController.Index) mux.HandleFunc("/user", userController.Show) mux.HandleFunc("/post", postController.Store) if err := http.ListenAndServe(":"+os.Getenv("SERVER_PORT"), mux); err != nil { logger.LogError("%s", err) } }
true
13f4a7e191903c893b7940ea6f5ffb764cbeaa59
Go
bishion/go-learn
/base/variable.go
UTF-8
661
3.796875
4
[]
no_license
[]
no_license
package base import "fmt" // 定义变量并指定类型 var name string // 同时定义多个变量 var age, score int8 // 定义变量并赋值 var birthday string = "1989-11-08" // 同时定义多个变量并赋值 var name1, name2, name3 string = "guo", "bizi", "bishion" // 同时定义多个变量并赋值, 可以省略变量类型 var age1, age2, age3 = 18, 28, 30 var _ = "赋值给下划线的变量都会被丢弃" func method() { // 最简单的定义方式,不过需要放在方法里 score1, score2, score3 := 90, 80, 70 // 变量定义了就要使用, 不然编译不通过 fmt.Print(score1) fmt.Print(score2) fmt.Print(score3) }
true
ce9b23750adf4b9a342ce57ca6879415d0ebbbdc
Go
leobcn/sqlb
/join_test.go
UTF-8
2,957
2.84375
3
[ "Apache-2.0" ]
permissive
[ "Apache-2.0" ]
permissive
// // Use and distribution licensed under the Apache license version 2. // // See the COPYING file in the root project directory for full text. // package sqlb import ( "testing" "github.com/stretchr/testify/assert" ) type joinClauseTest struct { c *joinClause qs string qargs []interface{} } func TestJoinClause(t *testing.T) { assert := assert.New(t) m := testFixtureMeta() users := m.Table("users") articles := m.Table("articles") colUserId := users.C("id") colArticleAuthor := articles.C("author") auCond := Equal(colArticleAuthor, colUserId) uaCond := Equal(colUserId, colArticleAuthor) tests := []joinClauseTest{ // articles to users table defs joinClauseTest{ c: Join(articles, users, auCond), qs: " JOIN users ON articles.author = users.id", }, // users to articles table defs joinClauseTest{ c: Join(users, articles, uaCond), qs: " JOIN articles ON users.id = articles.author", }, // articles to users tables joinClauseTest{ c: Join(articles, users, auCond), qs: " JOIN users ON articles.author = users.id", }, // join an aliased table to non-aliased table joinClauseTest{ c: &joinClause{ left: articles.As("a"), right: users, on: Equal(articles.As("a").C("author"), colUserId), }, qs: " JOIN users ON a.author = users.id", }, // join a non-aliased table to aliased table joinClauseTest{ c: &joinClause{ left: articles, right: users.As("u"), on: Equal(colArticleAuthor, users.As("u").C("id")), }, qs: " JOIN users AS u ON articles.author = u.id", }, // aliased projections should not include "AS alias" in output joinClauseTest{ c: &joinClause{ left: articles, right: users, on: Equal(colArticleAuthor, colUserId.As("user_id")), }, qs: " JOIN users ON articles.author = users.id", }, // simple outer join manual construction joinClauseTest{ c: &joinClause{ joinType: JOIN_OUTER, left: articles, right: users, on: Equal(colArticleAuthor, colUserId), }, qs: " LEFT JOIN users ON articles.author = users.id", }, // OuterJoin() function joinClauseTest{ c: OuterJoin(articles, users, Equal(colArticleAuthor, colUserId)), qs: " LEFT JOIN users ON articles.author = users.id", }, // cross join manual construction joinClauseTest{ c: &joinClause{ joinType: JOIN_CROSS, left: articles, right: users, }, qs: " CROSS JOIN users", }, // CrossJoin() function joinClauseTest{ c: CrossJoin(articles, users), qs: " CROSS JOIN users", }, } for _, test := range tests { expLen := len(test.qs) s := test.c.size(defaultScanner) assert.Equal(expLen, s) expArgc := len(test.qargs) assert.Equal(expArgc, test.c.argCount()) b := make([]byte, s) curArg := 0 written := test.c.scan(defaultScanner, b, test.qargs, &curArg) assert.Equal(written, s) assert.Equal(test.qs, string(b)) } }
true
8bc3b154f8cbd2431d495089a41372c70708d589
Go
xcastilla/sensor-check
/server/data/data.go
UTF-8
1,530
2.75
3
[]
no_license
[]
no_license
package data import ( "context" "fmt" "os" "time" "../models" "go.mongodb.org/mongo-driver/mongo" "go.mongodb.org/mongo-driver/mongo/options" "go.mongodb.org/mongo-driver/bson" ) var db *mongo.Database func InitDBConnection() (error) { URI := fmt.Sprintf("mongodb://%s", os.Getenv("MONGO_URL")) clientOptions := options.Client().ApplyURI(URI). SetAuth(options.Credential{ AuthSource: os.Getenv("MONGO_DB_NAME"), Username: os.Getenv("MONGO_USER"), Password: os.Getenv("MONGO_PASSWORD"), }) client, err := mongo.Connect(context.TODO(), clientOptions) if err != nil { return err } err = client.Ping(context.TODO(), nil) if err != nil { return err } db = client.Database(os.Getenv("MONGO_DB_NAME")) return nil } // Return all readings starting from fromDate func GetReadings(fromDate time.Time) ([]models.SensorReading, error) { collection := db.Collection("measurements2") ctx, _ := context.WithTimeout(context.Background(), 30*time.Second) projection := bson.D{ {"_id", 0}, {"temperature", 1}, {"timestamp", 1}, } var query = bson.M{"timestamp": bson.M{"$gt": fromDate}} cur, err := collection.Find(ctx, query, options.Find().SetProjection(projection),) if err != nil { return nil, err } defer cur.Close(ctx) // Pack results results := []models.SensorReading{} for cur.Next(ctx) { reading := models.SensorReading{} err = cur.Decode(&reading) if err != nil { return nil, err } results = append(results, reading) } return results, nil }
true
5fb9e449900825e1fac74e20cf7c108d90f0d0d0
Go
mcscoggy85/udemy-go
/closure/closure2.go
UTF-8
452
3.453125
3
[]
no_license
[]
no_license
package main import "fmt" func main() { x := 0 //narrow scope instead of using a global scope variable increment := func() int{ // This line is a nested function in go as well as an anonymous function x++ // an anon function is a function without a name, it looks like a function that is return x // assigned to a variable *** a func expression *** } fmt.Println(increment()) fmt.Println(increment()) fmt.Println(increment()) }
true
1fd61583e8497b1e446e78b1fa748b4b2508182d
Go
ajstarks/go-info-displays
/code/fullgen.go
UTF-8
1,011
2.984375
3
[]
no_license
[]
no_license
package main import ( "github.com/ajstarks/deck/generate" "os" ) func main() { deck := generate.NewSlides(os.Stdout, 0, 0) deck.StartDeck() // Text alignment deck.StartSlide("rgb(180,180,180)") deck.Text(50, 80, "Left", "sans", 10, "black") deck.TextMid(50, 50, "Center", "sans", 10, "gray") deck.TextEnd(50, 20, "Right", "sans", 10, "white") deck.Line(50, 100, 50, 0, 0.2, "black", 20) deck.EndSlide() // List items := []string{"First", "Second", "Third", "Fourth", "Fifth"} deck.StartSlide("blanchedalmond") deck.Text(10, 80, "Important Items", "sans", 5, "") deck.List(10, 60, 4, 1.4, 50, items, "bullet", "sans", "maroon") deck.EndSlide() // Picture with text annotation quote := "Tony Stark was able to build this in a cave. With a box of scraps!" deck.StartSlide("black", "white") deck.Image(50, 50, 1600, 681, "cave.jpg", "https://youtu.be/g1fzMbAr1u0?t=253") deck.Rect(70, 60, 60, 40, "black", 40) deck.TextBlock(45, 70, quote, "sans", 5, 45, "") deck.EndSlide() deck.EndDeck() }
true
10c9f5f098d36c262816052a015da337008d7bbb
Go
nightlark/vvgo
/pkg/api/slash_commands_test.go
UTF-8
9,997
2.703125
3
[ "Apache-2.0" ]
permissive
[ "Apache-2.0" ]
permissive
package api import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/virtual-vgo/vvgo/pkg/discord" "github.com/virtual-vgo/vvgo/pkg/redis" "github.com/virtual-vgo/vvgo/pkg/sheets" "github.com/virtual-vgo/vvgo/pkg/when2meet" "net/http" "net/http/httptest" "strings" "testing" ) func TestSlashCommand(t *testing.T) { ts := httptest.NewServer(http.HandlerFunc(HandleSlashCommand)) req, err := http.NewRequest(http.MethodPost, ts.URL, strings.NewReader(`{"type":1}`)) require.NoError(t, err, "http.NewRequest() failed") req.Header.Set("X-Signature-Ed25519", "acbd") req.Header.Set("X-Signature-Timestamp", "1234") resp, err := http.DefaultClient.Do(req) assert.NoError(t, err, "http.Do()") assert.Equal(t, http.StatusUnauthorized, resp.StatusCode, "status code") } func TestHandleBeepInteraction(t *testing.T) { interaction := discord.Interaction{ Type: discord.InteractionTypeApplicationCommand, Data: &discord.ApplicationCommandInteractionData{ Name: "beep", }, } response, ok := HandleInteraction(backgroundContext(), interaction) assert.True(t, ok) assertEqualInteractionResponse(t, discord.InteractionResponse{ Type: discord.InteractionCallbackTypeChannelMessageWithSource, Data: &discord.InteractionApplicationCommandCallbackData{Content: "boop"}, }, response) } func TestHandlePartsInteraction(t *testing.T) { ctx := backgroundContext() sheets.WriteValuesToRedis(ctx, sheets.WebsiteDataSpreadsheetID(ctx), "Projects", [][]interface{}{ {"Name", "Title", "Parts Released"}, {"10-hildas-healing", "Hilda's Healing", true}, }) interaction := discord.Interaction{ Type: discord.InteractionTypeApplicationCommand, Data: &discord.ApplicationCommandInteractionData{ Name: "parts", Options: []discord.ApplicationCommandInteractionDataOption{ {Name: "project", Value: "10-hildas-healing"}, }, }, } response, ok := HandleInteraction(ctx, interaction) assert.True(t, ok) assertEqualInteractionResponse(t, discord.InteractionResponse{ Type: discord.InteractionCallbackTypeChannelMessageWithSource, Data: &discord.InteractionApplicationCommandCallbackData{ Embeds: []discord.Embed{{ Title: "Hilda's Healing", Type: "rich", Description: "· Parts are [here!](https://vvgo.org/parts?project=10-hildas-healing)\n· Submit files [here!]()\n· Submission Deadline: .", Url: "https://vvgo.org/parts?project=10-hildas-healing", Color: 9181145, Footer: &discord.EmbedFooter{Text: "Bottom text."}, }}, }, }, response) } func TestHandleSubmissionInteraction(t *testing.T) { ctx := backgroundContext() sheets.WriteValuesToRedis(ctx, sheets.WebsiteDataSpreadsheetID(ctx), "Projects", [][]interface{}{ {"Name", "Title", "Parts Released", "Submission Link"}, {"10-hildas-healing", "Hilda's Healing", true, "https://bit.ly/vvgo10submit"}, }) interaction := discord.Interaction{ Type: discord.InteractionTypeApplicationCommand, Data: &discord.ApplicationCommandInteractionData{ Name: "submit", Options: []discord.ApplicationCommandInteractionDataOption{ {Name: "project", Value: "10-hildas-healing"}, }, }, } response, ok := HandleInteraction(ctx, interaction) assert.True(t, ok) assertEqualInteractionResponse(t, discord.InteractionResponse{ Type: discord.InteractionCallbackTypeChannelMessageWithSource, Data: &discord.InteractionApplicationCommandCallbackData{ Content: "[Submit here](https://bit.ly/vvgo10submit) for Hilda's Healing. Submission Deadline is ", }, }, response) } func TestHandleWhen2MeetInteraction(t *testing.T) { ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Write([]byte(`<body onload="window.location='/?10947260-c2u6i'">`)) })) defer ts.Close() when2meet.Endpoint = ts.URL ctx := backgroundContext() interaction := discord.Interaction{ Type: discord.InteractionTypeApplicationCommand, Member: discord.GuildMember{User: discord.User{ID: "42069"}}, Data: &discord.ApplicationCommandInteractionData{ Name: "when2meet", Options: []discord.ApplicationCommandInteractionDataOption{ {Name: "start_date", Value: "2030-02-01"}, {Name: "end_date", Value: "2030-02-02"}, {Name: "event_name", Value: "holy cheesus"}, }, }, } response, ok := HandleInteraction(ctx, interaction) assert.True(t, ok) want := interactionResponseMessage("<@42069> created a [when2meet](https://when2meet.com/?10947260-c2u6i).", true) assertEqualInteractionResponse(t, want, response) } func TestAboutmeHandler(t *testing.T) { ctx := backgroundContext() resetAboutMeEntries := func(t *testing.T) { require.NoError(t, redis.Do(ctx, redis.Cmd(nil, "DEL", "about_me:entries"))) } aboutMeInteraction := func(cmd string, options []discord.ApplicationCommandInteractionDataOption) discord.Interaction { return discord.Interaction{ Type: discord.InteractionTypeApplicationCommand, Member: discord.GuildMember{User: discord.User{ID: "42069"}, Roles: []string{discord.VVGOProductionTeamRoleID}}, Data: &discord.ApplicationCommandInteractionData{ Name: "aboutme", Options: []discord.ApplicationCommandInteractionDataOption{ {Name: cmd, Options: options}, }, }, } } testNotOnProductionTeam := func(t *testing.T, cmd string) { t.Run("not on production team", func(t *testing.T) { resetAboutMeEntries(t) interaction := aboutMeInteraction(cmd, nil) interaction.Member.Roles = nil response, ok := HandleInteraction(ctx, interaction) assert.True(t, ok) want := interactionResponseMessage("Sorry, this tool is only for production teams. :bow:", true) assertEqualInteractionResponse(t, want, response) got, err := readAboutMeEntries(ctx, nil) assert.NoError(t, err) assert.Empty(t, got) }) } t.Run("hide", func(t *testing.T) { testNotOnProductionTeam(t, "hide") t.Run("ok", func(t *testing.T) { resetAboutMeEntries(t) require.NoError(t, writeAboutMeEntries(ctx, map[string]AboutMeEntry{"42069": {DiscordID: "42069", Show: true}})) response, ok := HandleInteraction(ctx, aboutMeInteraction("hide", nil)) assert.True(t, ok) want := interactionResponseMessage(":person_gesturing_ok: You are hidden from https://vvgo.org/about.", true) assertEqualInteractionResponse(t, want, response) got, err := readAboutMeEntries(ctx, nil) assert.NoError(t, err) assert.Equal(t, map[string]AboutMeEntry{"42069": {DiscordID: "42069", Show: false}}, got) }) t.Run("no blurb", func(t *testing.T) { resetAboutMeEntries(t) response, ok := HandleInteraction(ctx, aboutMeInteraction("hide", nil)) assert.True(t, ok) want := interactionResponseMessage("You dont have a blurb! :open_mouth:", true) assertEqualInteractionResponse(t, want, response) }) }) t.Run("show", func(t *testing.T) { testNotOnProductionTeam(t, "show") t.Run("ok", func(t *testing.T) { resetAboutMeEntries(t) require.NoError(t, writeAboutMeEntries(ctx, map[string]AboutMeEntry{"42069": {DiscordID: "42069", Show: false}})) response, ok := HandleInteraction(ctx, aboutMeInteraction("show", nil)) assert.True(t, ok) want := interactionResponseMessage(":person_gesturing_ok: You are visible on https://vvgo.org/about.", true) assertEqualInteractionResponse(t, want, response) got, err := readAboutMeEntries(ctx, nil) assert.NoError(t, err) assert.Equal(t, map[string]AboutMeEntry{"42069": {DiscordID: "42069", Show: true}}, got) }) t.Run("no blurb", func(t *testing.T) { resetAboutMeEntries(t) response, ok := HandleInteraction(ctx, aboutMeInteraction("show", nil)) assert.True(t, ok) want := interactionResponseMessage("You dont have a blurb! :open_mouth:", true) assertEqualInteractionResponse(t, want, response) }) }) t.Run("update", func(t *testing.T) { testNotOnProductionTeam(t, "update") t.Run("exists", func(t *testing.T) { resetAboutMeEntries(t) require.NoError(t, writeAboutMeEntries(ctx, map[string]AboutMeEntry{"42069": {DiscordID: "42069"}})) response, ok := HandleInteraction(ctx, aboutMeInteraction("update", []discord.ApplicationCommandInteractionDataOption{ {Name: "name", Value: "chester cheeta"}, {Name: "blurb", Value: "dangerously cheesy"}, })) assert.True(t, ok) want := interactionResponseMessage(":person_gesturing_ok: It is written.", true) assertEqualInteractionResponse(t, want, response) got, err := readAboutMeEntries(ctx, nil) assert.NoError(t, err) assert.Equal(t, map[string]AboutMeEntry{ "42069": {DiscordID: "42069", Name: "chester cheeta", Title: "Production Team", Blurb: "dangerously cheesy"}, }, got) }) t.Run("doesnt exist", func(t *testing.T) { resetAboutMeEntries(t) response, ok := HandleInteraction(ctx, aboutMeInteraction("update", []discord.ApplicationCommandInteractionDataOption{ {Name: "name", Value: "chester cheeta"}, {Name: "blurb", Value: "dangerously cheesy"}, })) assert.True(t, ok) want := interactionResponseMessage(":person_gesturing_ok: It is written.", true) assertEqualInteractionResponse(t, want, response) got, err := readAboutMeEntries(ctx, nil) assert.NoError(t, err) assert.Equal(t, map[string]AboutMeEntry{ "42069": {DiscordID: "42069", Name: "chester cheeta", Title: "Production Team", Blurb: "dangerously cheesy"}, }, got) }) }) } func assertEqualInteractionResponse(t *testing.T, want, got discord.InteractionResponse) { assert.Equal(t, want.Type, got.Type, "interaction.Type") assertEqualInteractionApplicationCommandCallbackData(t, want.Data, got.Data) } func assertEqualInteractionApplicationCommandCallbackData(t *testing.T, want, got *discord.InteractionApplicationCommandCallbackData) { assert.Equal(t, want.Content, got.Content, "interaction.Data.Content") assert.Equal(t, want.TTS, got.TTS, "interaction.Data.TTS") assert.Equal(t, want.Embeds, got.Embeds, "interaction.Data.Embeds") }
true
778b302d5aa8028ba06826ddd1ea29a6c046e5eb
Go
aralvesandrade/carrinho-api-gorm
/business/itensCarrinhoBusiness.go
UTF-8
790
2.703125
3
[]
no_license
[]
no_license
package business import ( "carrinho-api-gorm/model" "carrinho-api-gorm/repository" ) //IItensCarrinhoBusiness ... type IItensCarrinhoBusiness interface { ItensCarrinhoByCarrinhoID(carrinhoID string) (*[]model.ItensCarrinho, error) } //ItensCarrinhoBusiness ... type ItensCarrinhoBusiness struct { ItensCarrinhoRepository repository.IItensCarrinhoRepository } //NewItensCarrinhoBusiness ... func NewItensCarrinhoBusiness(ItensCarrinhoRepository repository.IItensCarrinhoRepository) IItensCarrinhoBusiness { return &ItensCarrinhoBusiness{ItensCarrinhoRepository} } //ItensCarrinhoByCarrinhoID ... func (l *ItensCarrinhoBusiness) ItensCarrinhoByCarrinhoID(carrinhoID string) (*[]model.ItensCarrinho, error) { return l.ItensCarrinhoRepository.ItensCarrinhoByCarrinhoID(carrinhoID) }
true
55f7f606c0033e73b92e18df601c9002e9785f28
Go
dexterorion/smartmei
/handler/handler_test.go
UTF-8
1,974
2.984375
3
[]
no_license
[]
no_license
package handler import ( "net/http" "testing" "github.com/gavv/httpexpect" ) func TestAPI_Crawler(t *testing.T) { type TestMock struct { name string path string url string expectedCode int expectedBody string } tt := []TestMock{ { name: "wrong path request", expectedCode: http.StatusNotFound, expectedBody: "404 page not found\n", }, { name: "wrong url", expectedCode: http.StatusInternalServerError, path: "/smartmei/crawler", expectedBody: "{\"result\":false,\"code\":-1,\"message\":\"Unknown error: result: false; code: 4010009; message: query params `url` is not valid\"}\n", }, { name: "error getting info", expectedCode: http.StatusInternalServerError, url: "https://www.google.com", path: "/smartmei/crawler", expectedBody: "{\"result\":false,\"code\":-1,\"message\":\"Unknown error: result: false; code: 4010005; message: error crawling data: result: false; code: 4010008; message: found array size 1, but array size 2 is required\"}\n", }, { name: "all ok", expectedCode: http.StatusOK, url: "https://www.smartmei.com.br", path: "/smartmei/crawler", }, } for _, tc := range tt { t.Run(tc.name, func(t *testing.T) { api := New() exp := httpexpect.WithConfig(httpexpect.Config{ Client: &http.Client{ Transport: httpexpect.NewBinder(api), Jar: httpexpect.NewJar(), }, Reporter: httpexpect.NewAssertReporter(t), }) if tc.expectedCode != http.StatusOK { exp.GET(tc.path). WithQuery("url", tc.url). Expect(). Status(tc.expectedCode). Body().Equal(tc.expectedBody) } else { // just checking if it is not empty, since I don't know exactly what to expect // as response body exp.GET(tc.path). WithQuery("url", tc.url). Expect(). Status(tc.expectedCode). Body().NotEmpty() } }) } }
true
2ac3455609bee8f7a66db68ea5502cf59c4ba089
Go
kbsizer/learning_go
/Algorithms_in_Go__Jon_Calhoun/module01_green/std_demo/main.go
UTF-8
218
2.734375
3
[]
no_license
[]
no_license
package main import ( "algo/module01" "fmt" ) func main() { var n int fmt.Scanf("%d", &n) for i := 0; i < n; i++ { var a, b int fmt.Scanf("%d %d", &a, &b) gcd := module01.GCD(a, b) fmt.Println(gcd) } }
true
7347d14cbaa0523099a9c6f9d7e6a1cc1f25250f
Go
TJM/go-trello-example
/delete_boards/delete_boards.go
UTF-8
4,087
2.984375
3
[ "Apache-2.0" ]
permissive
[ "Apache-2.0" ]
permissive
package main import ( "encoding/json" "fmt" "log" "os" "strings" "text/tabwriter" "github.com/TJM/go-trello" "github.com/alexflint/go-arg" ) var args struct { AppKey string `arg:"required,env:TRELLO_APP_KEY" help:"Trello API App Key.\n\t\t Obtain yours at https://trello.com/app-key\n\t\t (env: TRELLO_APP_KEY)"` Token string `arg:"required,env:TRELLO_TOKEN" help:"Trello API App Key.\n\t\t Authorize your App Key to use your account at <https://trello.com/1/connect?key=<appKey from above>&name=Go-Trello-Example-delete_boards&response_type=token&scope=read,write&expiration=1day>\n\t\t (env: TRELLO_TOKEN)"` AnyOf bool `help:"Match AnyOf the StartsWith, Contains or EndsWith conditions. By default board name must match all of the conditions."` StartsWith string `help:"Select boards to delete that *start with* this string"` Contains string `help:"Select boards to delete that *contain* this string"` EndsWith string `help:"Select boards to delete that *end with* this string"` Delete bool `help:"Actually DELETE the boards (defaults to false so you can see what will happen)"` Debug bool `help:"Enable debugging output"` } var w *tabwriter.Writer func main() { // Parse Command Line Args arg.MustParse(&args) // Tab Writer w = new(tabwriter.Writer) w.Init(os.Stdout, 4, 4, 2, ' ', tabwriter.TabIndent) // New Trello Client appKey := args.AppKey token := args.Token trello, err := trello.NewAuthClient(appKey, &token) if err != nil { log.Fatal(err) } // User @trello user, err := trello.Member("me") if err != nil { log.Fatal(err) } fmt.Printf("Trello User: %s (%s) <%s>\n", user.FullName, user.Username, user.URL) // @trello Boards boards, err := user.Boards() if err != nil { log.Fatal(err) } fmt.Printf("Trello Boards: %v\n", len(user.IDBoards)) fmt.Fprintf(w, "\tAction\tBoard Name\tURL\n") fmt.Fprintf(w, "\t------\t----------\t---\n") for _, board := range boards { var action string if args.Debug { boardJSON, err := json.MarshalIndent(board, "", " ") if err != nil { log.Fatalf(err.Error()) } fmt.Printf("====================\n%s:\n%s\n\n", board.Name, string(boardJSON)) } if args.AnyOf { // AnyOf if args.StartsWith != "" && strings.HasPrefix(board.Name, args.StartsWith) { action = removeBoard(board, user) } else if args.Contains != "" && strings.Contains(board.Name, args.Contains) { action = removeBoard(board, user) } else if args.EndsWith != "" && strings.HasSuffix(board.Name, args.EndsWith) { action = removeBoard(board, user) } else { action = "KEEP" } } else { if args.StartsWith == "" && args.Contains == "" && args.EndsWith == "" { // If no conditions are set, KEEP action = "KEEP" } else if (args.StartsWith == "" || strings.HasPrefix(board.Name, args.StartsWith)) && (args.Contains == "" || strings.Contains(board.Name, args.Contains)) && (args.EndsWith == "" || strings.HasSuffix(board.Name, args.EndsWith)) { // If a condition is set, and matches, DELETE action = removeBoard(board, user) } else { // KEEP by default action = "KEEP" } } fmt.Fprintf(w, "\t%s\t%s\t<%s>\n", action, board.Name, board.ShortURL) } // Output Tabwriter Table fmt.Printf("\n") w.Flush() if !args.Delete { fmt.Printf("\n\n ** Run again with --delete flag to actually delete the board(s).\n\n") } } func removeBoard(board *trello.Board, user *trello.Member) (action string) { if args.Delete { if board.IsAdmin(user) { fmt.Printf("DELETING: %s <%s> ...\n", board.Name, board.ShortURL) err := board.Delete() action = "DELETED" if err != nil { fmt.Printf("ERROR Deleting board: %v\n", err) action = "ERROR DELETING" } } else { fmt.Printf("LEAVING: %s <%s> ...\n", board.Name, board.ShortURL) err := board.RemoveMember(user) action = "LEFT" if err != nil { fmt.Printf("ERROR Leaving board: %v\n", err) action = "ERROR LEAVING" } } } else { if board.IsAdmin(user) { action = "DELETE" } else { action = "LEAVE" } } return }
true
34709e497b0b91f10e248c5742234b3ebbb7ba6b
Go
bendiksh/RT-Prog
/Project/ferdig_heis/driver/driver.go
UTF-8
2,889
2.953125
3
[]
no_license
[]
no_license
package driver //import . "time" import . "math" import . "fmt" // // Matrices of buttons, lights and sensor to loop through easier // var Button_matrix = [N_floors][N_buttons]int{ {BUTTON_UP1,BUTTON_DOWN1,BUTTON_COMMAND1}, {BUTTON_UP2,BUTTON_DOWN2,BUTTON_COMMAND2}, {BUTTON_UP3,BUTTON_DOWN3,BUTTON_COMMAND3}, {BUTTON_UP4,BUTTON_DOWN4,BUTTON_COMMAND4}, } var Light_matrix = [N_floors][N_buttons]int{ {LIGHT_UP1,LIGHT_DOWN1,LIGHT_COMMAND1}, {LIGHT_UP2,LIGHT_DOWN2,LIGHT_COMMAND2}, {LIGHT_UP3,LIGHT_DOWN3,LIGHT_COMMAND3}, {LIGHT_UP4,LIGHT_DOWN4,LIGHT_COMMAND4}, } var button=[N_floors][N_buttons]int{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, } var Sensors = [N_floors]int{SENSOR_FLOOR1,SENSOR_FLOOR2,SENSOR_FLOOR3,SENSOR_FLOOR4} // // Functions // func Elev_init() (err, floor int){ // returns a status int and a floor int if (int(Io_init()) != 1) { return 1, -1 } // turn off all lights for i := 0; i < N_floors; i++ { if i != 0 { Button_light(i, Button_down, 0) } if i != (N_floors - 1) { Button_light(i, Button_up, 0) } Button_light(i, Button_command, 0) } Stop_light(0) Door_light(0) // find current floor floor = 0 for i := 0; i < N_floors; i++{ if(Io_read_bit(Sensors[i]) == 1) { floor = i } } Printf("Init floor : %d\n", floor) Floor_ind(floor) Motor(0) return } func Floor_ind(floor int){ if (floor & 0x02 == 0x02) { Io_set_bit(LIGHT_FLOOR_IND1) } else{ Io_clear_bit(LIGHT_FLOOR_IND1) } if (floor & 0x01 == 0x01) { Io_set_bit(LIGHT_FLOOR_IND2) } else{ Io_clear_bit(LIGHT_FLOOR_IND2) } } func Poll_buttons() Event_t{ for i := 0; i < N_floors; i++ { for j := 0; j < N_buttons; j++{ if (Io_read_bit(Button_matrix[i][j]) == 1 && button[i][j] == 0){ button[i][j] = 1 return Event_t{i,j} // returns on which floor (i) the button (j) has been pressed }else if (Io_read_bit(Button_matrix[i][j]) == 0){ button[i][j] = 0 } } } return Event_t{-1,-1} } func Button_light(floor, button, value int){ if value == 1 { Io_set_bit(Light_matrix[floor][button]) }else { Io_clear_bit(Light_matrix[floor][button]) } } func Get_floor() int { for i := 0; i < N_floors; i++ { if Io_read_bit(Sensors[i]) == 1 { return i } } return -1 } func Stop_light(i int){ if (i == 1) { Io_set_bit(LIGHT_STOP) }else{ Io_clear_bit(LIGHT_STOP) } } func Door_light(i int){ if (i == 1) { Io_set_bit(LIGHT_DOOR_OPEN) }else{ Io_clear_bit(LIGHT_DOOR_OPEN) } } var prev_speed int func Motor(speed int){ if ( speed > 0 ){ Io_clear_bit(MOTORDIR) Io_write_analog(MOTOR, int(2048 + 4*Abs(float64(speed)))) }else if (speed < 0){ Io_set_bit(MOTORDIR) Io_write_analog(MOTOR, int(2048 + 4*Abs(float64(speed)))) }else{ if (prev_speed < 0){ Io_clear_bit(MOTORDIR) }else if(prev_speed > 0){ Io_set_bit(MOTORDIR) } Io_write_analog(MOTOR, 0) } prev_speed = speed }
true
c4a11af70adbbdeb74dcb5f53bd74dcb6471c632
Go
yupengfei/PillarsFlowNet
/chartStorage/chartOperation.go
UTF-8
999
2.765625
3
[]
no_license
[]
no_license
package chartStorage import ( "PillarsFlowNet/mongoUtility" "PillarsFlowNet/utility" "labix.org/v2/mgo/bson" "time" ) func StoreToChart(chart * utility.Chart) (* utility.Chart, error){ err := mongoUtility.ChartCollection.Insert(chart) if err != nil { return chart, err } mongoUtility.ChartCollection.Find(bson.M{"_id":chart.Id}).One(chart) return chart, err } func MarkAsReceiveByChartCode(chartCode * string) (* string, error) { err := mongoUtility.ChartCollection.Update(bson.M{"_id": *chartCode}, bson.M{"$set": bson.M{"isreceived": 1, "receivedtime": time.Now().Format("2006-01-02 15:04:05")}}) if err != nil { return chartCode, err } return chartCode, err } func GetAllUnreceivedMessageByUserCode(userCode * string) ([] utility.Chart, error) { var chartSlice [] utility.Chart iter := mongoUtility.ChartCollection.Find(bson.M{"to":*userCode, "isreceived":0}).Iter() err := iter.All(&chartSlice) if err != nil { return chartSlice, err } return chartSlice, err }
true
6fd7566dbb6b72c7e7434f3f2c23de52676d41f5
Go
google/kf
/third_party/mapfs/src/main_test.go
UTF-8
5,428
2.65625
3
[ "Apache-2.0", "ISC", "BSD-2-Clause", "MIT", "BSD-3-Clause", "MPL-2.0" ]
permissive
[ "Apache-2.0", "ISC", "BSD-2-Clause", "MIT", "BSD-3-Clause", "MPL-2.0" ]
permissive
package main import ( "io" "io/ioutil" "os/exec" "path/filepath" "code.cloudfoundry.org/goshims/bufioshim" "code.cloudfoundry.org/goshims/osshim" "code.cloudfoundry.org/volumedriver/mountchecker" "fmt" "os" "time" "github.com/onsi/gomega/gbytes" "github.com/onsi/gomega/gexec" "github.com/tedsuo/ifrit" "github.com/tedsuo/ifrit/ginkgomon" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) type failRunner struct { Command *exec.Cmd Name string AnsiColorCode string StartCheck string StartCheckTimeout time.Duration Cleanup func() session *gexec.Session sessionReady chan struct{} } func (r failRunner) Run(sigChan <-chan os.Signal, ready chan<- struct{}) error { defer GinkgoRecover() allOutput := gbytes.NewBuffer() debugWriter := gexec.NewPrefixedWriter( fmt.Sprintf("\x1b[32m[d]\x1b[%s[%s]\x1b[0m ", r.AnsiColorCode, r.Name), GinkgoWriter, ) session, err := gexec.Start( r.Command, gexec.NewPrefixedWriter( fmt.Sprintf("\x1b[32m[o]\x1b[%s[%s]\x1b[0m ", r.AnsiColorCode, r.Name), io.MultiWriter(allOutput, GinkgoWriter), ), gexec.NewPrefixedWriter( fmt.Sprintf("\x1b[91m[e]\x1b[%s[%s]\x1b[0m ", r.AnsiColorCode, r.Name), io.MultiWriter(allOutput, GinkgoWriter), ), ) Ω(err).ShouldNot(HaveOccurred()) fmt.Fprintf(debugWriter, "spawned %s (pid: %d)\n", r.Command.Path, r.Command.Process.Pid) r.session = session if r.sessionReady != nil { close(r.sessionReady) } startCheckDuration := r.StartCheckTimeout if startCheckDuration == 0 { startCheckDuration = 5 * time.Second } var startCheckTimeout <-chan time.Time if r.StartCheck != "" { startCheckTimeout = time.After(startCheckDuration) } detectStartCheck := allOutput.Detect(r.StartCheck) for { select { case <-detectStartCheck: // works even with empty string allOutput.CancelDetects() startCheckTimeout = nil detectStartCheck = nil close(ready) case <-startCheckTimeout: // clean up hanging process session.Kill().Wait() // fail to start return fmt.Errorf( "did not see %s in command's output within %s. full output:\n\n%s", r.StartCheck, startCheckDuration, string(allOutput.Contents()), ) case signal := <-sigChan: session.Signal(signal) case <-session.Exited: if r.Cleanup != nil { r.Cleanup() } Expect(string(allOutput.Contents())).To(ContainSubstring(r.StartCheck)) Expect(session.ExitCode()).To(Not(Equal(0)), fmt.Sprintf("Expected process to exit with non-zero, got: 0")) return nil } } } var _ = Describe("mapfs Main", func() { Context("Missing required args", func() { var process ifrit.Process It("shows usage", func() { var args []string driverRunner := failRunner{ Name: "mapfs", Command: exec.Command(binaryPath, args...), StartCheck: "usage: " + binaryName + " -uid UID -gid GID", } process = ifrit.Invoke(driverRunner) }) It("shows usage again", func() { var args []string = []string{"/foo", "/bar"} driverRunner := failRunner{ Name: "mapfs", Command: exec.Command(binaryPath, args...), StartCheck: "usage: " + binaryName + " -uid UID -gid GID", } process = ifrit.Invoke(driverRunner) }) It("shows usage even still", func() { var args []string = []string{"uid", "0", "gid", "0", "/foo", "/bar"} driverRunner := failRunner{ Name: "mapfs", Command: exec.Command(binaryPath, args...), StartCheck: "usage: " + binaryName + " -uid UID -gid GID", } process = ifrit.Invoke(driverRunner) }) AfterEach(func() { ginkgomon.Kill(process) // this is only if incorrect implementation leaves process running }) }) Context("when starting succesfully", func() { var ( driverProcess ifrit.Process flockProcess ifrit.Process ) AfterEach(func() { ginkgomon.Kill(driverProcess) ginkgomon.Kill(flockProcess) }) It("flock works", func() { srcDir, err := ioutil.TempDir("", "src") Expect(err).NotTo(HaveOccurred()) targetDir, err := ioutil.TempDir("", "target") Expect(err).NotTo(HaveOccurred()) Expect(os.Chmod(srcDir, os.ModePerm)).To(Succeed()) driverRunner := ginkgomon.New( ginkgomon.Config{ Name: "mapfs", Command: exec.Command(binaryPath, "-uid", "1000", "-gid", "1000", targetDir, srcDir), StartCheck: "Mounted!", }, ) driverProcess = ifrit.Invoke(driverRunner) By("ensure that mapfs has mounted correctly", func() { mountChecker := mountchecker.NewChecker(&bufioshim.BufioShim{}, &osshim.OsShim{}) mounted, err := mountChecker.Exists(targetDir) Expect(err).NotTo(HaveOccurred()) Expect(mounted).To(BeTrue()) }) lockPath := filepath.Join(targetDir, "lockfile") _, err = os.OpenFile(lockPath, os.O_RDONLY|os.O_CREATE, 0666) Expect(err).NotTo(HaveOccurred()) flockRunner1 := ginkgomon.New( ginkgomon.Config{ Name: "flock", Command: exec.Command("flock", lockPath, "-c", "echo success1 && sleep 1"), StartCheck: "success1", }, ) flockProcess = ifrit.Invoke(flockRunner1) flockCommand := exec.Command("flock", "-n", lockPath, "-c", "echo ok") flockSession, err := gexec.Start(flockCommand, GinkgoWriter, GinkgoWriter) Expect(err).NotTo(HaveOccurred()) <-flockSession.Exited Expect(flockSession.ExitCode()).To(Equal(1)) }) }) })
true
572d9507ff7fb3655a170f3622c000cbd5adcb94
Go
joseph-ortiz/go-fundamentals
/slices.go
UTF-8
744
4.125
4
[]
no_license
[]
no_license
package main import ( "fmt" ) func main() { //Delcare a slice called myCourses //slice of strings w/ length of 5 and a capacity of 10 //mySlice := make([]int, 1, 4) //gets init with zero values mySlice := []int{1, 2, 3, 4, 5} //gets init with zero values //myCourses := []string{"Docker", "Puppet", "Python"} fmt.Println(mySlice) fmt.Printf("Length is %d. \nCapacity is: %d\n", len(mySlice), cap(mySlice)) //for i := 1; i < 17; i++ { // mySlice = append(mySlice, i) // fmt.Printf("\nCapacity is: %d", cap(mySlice)) //} for _, i := range mySlice { fmt.Println("for range loop:", i) } newSlice := []int{10, 20, 30} mySlice = append(mySlice, newSlice...) //this appends all the elements to the slice fmt.Println(mySlice) }
true
4164e9c69f59a6584d9787ebb14d2456d0534557
Go
wesleyholiveira/wfalerts
/main.go
UTF-8
7,292
2.640625
3
[]
no_license
[]
no_license
package main import ( "bytes" "encoding/xml" "fmt" "github.com/bwmarrin/discordgo" log "github.com/sirupsen/logrus" "github.com/spf13/viper" "golang.org/x/net/html/charset" "io/ioutil" "net/http" "regexp" "runtime" "strings" "time" ) const wfurl = "http://content.warframe.com/dynamic/rss.php" type WFRSS struct { XMLName xml.Name `xml:"rss"` Item []WFItem `xml:"channel>item"` } type WFItem struct { Guid string `xml:"guid"` Title string `xml:"title"` Author string `xml:"author"` Description string `xml:"description"` PubDate string `xml:"pubDate"` ExpiryDate string `xml:"expiry"` PubDateTime time.Time `xml:"-"` ExpiryDateTime time.Time `xml:"-"` } var token, webhookID, webhookToken string var msg string var wfrss *WFRSS var data chan *WFRSS var pattern *regexp.Regexp var ignoreExp map[string]bool = make(map[string]bool, 1) var ignorePub map[string]bool = make(map[string]bool, 1) var ignorePubAnt map[string]bool = make(map[string]bool, 1) func main() { runtime.GOMAXPROCS(runtime.NumCPU()) pattern = regexp.MustCompile(`[\/: ]`) ignoreExp = make(map[string]bool, 1) ignorePub = make(map[string]bool, 1) ignorePubAnt = make(map[string]bool, 1) done := make(chan bool) data = make(chan *WFRSS) wfrss = new(WFRSS) dg, err := discordgo.New("Bot " + token) if err != nil { log.Fatalln("Error creating Discord session", err) } go discord(dg) go retrieveData(dg, data) go processData(dg, data) go notification(dg, data) dg.Close() <-done } func init() { viper.SetConfigFile("./credentials.json") if err := viper.ReadInConfig(); err != nil { log.Fatalf("Error reading config file, %s", err) } token = viper.GetString("botToken") webhookID = viper.GetString("webhookID") webhookToken = viper.GetString("webhookToken") } func discord(dg *discordgo.Session) { dg.AddHandler(messageCreate) err := dg.Open() if err != nil { log.Errorln("Error opening connection", err) return } log.Infoln("Bot is now running. Press CTRL-C to exit.") } func retrieveData(dg *discordgo.Session, data chan<- *WFRSS) { resp, err := http.Get(wfurl) wf := &WFRSS{} if err != nil { log.Errorf("Cannot retrieve the content of %s\n", wfurl) log.Errorln(err) } respReader, err := ioutil.ReadAll(resp.Body) if err != nil { log.Errorln(err) } resp.Body.Close() err = parseXML(respReader, wf) if err != nil { log.Errorln(err) } err = parseDate(wf) if err != nil { log.Errorln(err) } data <- wf if data != nil { c := time.Tick(1 * time.Minute) for now := range c { log.Infoln("Retrieving infos of rss at: ", now) go retrieveData(dg, nil) } } } func processData(dg *discordgo.Session, data chan *WFRSS) { wf := <-data now := time.Now() expiryIndex, rateExp := nearestExpiryDate(wf.Item) pubIndex, ratePub := nearestPubDate(wf.Item) wfi := wf.Item[expiryIndex] if ignoreExp[wfi.Guid] == false { if rateExp == 1.00 { msg = fmt.Sprintf("**EXPIRADO!!!!**\n%s", alertMessage(now, &wfi)) dg.WebhookExecute(webhookID, webhookToken, false, &discordgo.WebhookParams{ Content: msg, }) ignoreExp[wfi.Guid] = true } } wfi = wf.Item[pubIndex] if ignorePubAnt[wfi.Guid] == false { minute := 10 tmpMsg := fmt.Sprintf("**ALERTA!!!!!**\n%s\n", alertMessage(now, &wfi)) if now.Unix() == wfi.PubDateTime.Add(time.Duration(-minute)*time.Minute).Unix() { dg.WebhookExecute(webhookID, webhookToken, false, &discordgo.WebhookParams{ Content: tmpMsg, }) } ignorePubAnt[wfi.Guid] = true } msg = alertMessage(now, &wfi) if ignorePub[wfi.Guid] == false { if ratePub == 1.00 { log.Info("Sending content to webhook") dg.WebhookExecute(webhookID, webhookToken, false, &discordgo.WebhookParams{ Content: msg, }) ignorePub[wfi.Guid] = true } } wfrss = wf data <- wf } func notification(dg *discordgo.Session, data chan *WFRSS) { c := time.Tick(200 * time.Millisecond) for now := range c { now.Second() //log.Info("Processing notification at: ", now) go processData(dg, data) } } func parseXML(xmlDoc []byte, target interface{}) error { reader := bytes.NewReader(xmlDoc) decoder := xml.NewDecoder(reader) decoder.CharsetReader = charset.NewReaderLabel if err := decoder.Decode(target); err != nil { return err } return nil } func parseDate(wf *WFRSS) error { var err error for i, _ := range wf.Item { err = strDateToTime(&wf.Item[i]) if err != nil { return err } } return nil } func strDateToTime(wf *WFItem) error { var err error if wf.ExpiryDate != "" { wf.PubDateTime, err = time.Parse(time.RFC1123Z, wf.PubDate) wf.ExpiryDateTime, err = time.Parse(time.RFC1123Z, wf.ExpiryDate) wf.PubDateTime = wf.PubDateTime.Local() wf.ExpiryDateTime = wf.ExpiryDateTime.Local() if err != nil { return err } } return nil } func nearestPubDate(wf []WFItem) (int, float32) { var max float32 = 0.00 var index int = 0 now := time.Now() for i, el := range wf { nowUnix := now.Unix() pubUnix := el.PubDateTime.Unix() if el.PubDate != "" { var value float32 = float32(nowUnix) / float32(pubUnix) if value > max { max = value index = i } } } return index, max } func nearestExpiryDate(wf []WFItem) (int, float32) { var max float32 = 0.00 var index int = 0 now := time.Now() for i, el := range wf { nowUnix := now.Unix() expiryUnix := el.ExpiryDateTime.Unix() if el.ExpiryDate != "" { var value float32 = float32(nowUnix) / float32(expiryUnix) if value > max { max = value index = i } } } return index, max } func messageCreate(s *discordgo.Session, m *discordgo.MessageCreate) { c := m.Content if strings.HasPrefix(c, "wf!") { if strings.HasSuffix(c, "alert") { s.ChannelMessageSend(m.ChannelID, msg) } if strings.HasSuffix(c, "alerts") { var tmpMsg string now := time.Now() for _, el := range wfrss.Item { if el.PubDate != "" && el.ExpiryDate != "" { tmpMsg += alertMessage(now, &el) } } s.ChannelMessageSend(m.ChannelID, tmpMsg) } } } func alertMessage(t time.Time, item *WFItem) string { lp := item.PubDateTime.Local() le := item.ExpiryDateTime.Local() start := "JA COMECOU CARA!!!" expiry := "PERDEU PLAYBOY!" subPub := item.PubDateTime.Sub(t) subExp := item.ExpiryDateTime.Sub(t) if m := subPub.Minutes(); m >= 0.00 { start = fmt.Sprintf("***%dm***", int(m)) } if m := subExp.Minutes(); m >= 0.00 { expiry = fmt.Sprintf("***%dm***", int(m)) } starts := fmt.Sprintf("%d/%d/%d %d:%d:%d", lp.Day(), lp.Month(), lp.Year(), lp.Hour(), lp.Minute(), lp.Second()) ends := fmt.Sprintf("%d/%d/%d %d:%d:%d", le.Day(), le.Month(), le.Year(), le.Hour(), le.Minute(), le.Second()) starts = addZerosToDateHours(pattern, starts) ends = addZerosToDateHours(pattern, ends) ret := fmt.Sprintf("**Titulo:** %s\n**Inicia em:** %s *(%s)*\n**Expira em:** %s *(%s)*\n**Tipo:** %s\n\n", item.Title, start, starts, expiry, ends, item.Author) return ret } func addZerosToDateHours(r *regexp.Regexp, s string) string { array := r.Split(s, -1) for i := range array { if len(array[i]) == 1 { array[i] = "0" + array[i] } } return fmt.Sprintf("%s/%s/%s %s:%s:%s", array[0], array[1], array[2], array[3], array[4], array[5]) }
true
a37b79631e3c31e7291059a865e56abebe10b7b7
Go
abeatrice/leetcode-go
/shuffleTheArray/shuffleTheArray_test.go
UTF-8
930
3.21875
3
[]
no_license
[]
no_license
package shuffleTheArray_test import ( "testing" "github.com/abeatrice/leetcode-go/shuffleTheArray" ) type testItem struct { nums []int n int expected []int } func TestShufffleTheArray(t *testing.T) { testItems := []testItem{ {[]int{2, 5, 1, 3, 4, 7}, 3, []int{2, 3, 5, 4, 1, 7}}, {[]int{1, 2, 3, 4, 4, 3, 2, 1}, 4, []int{1, 4, 2, 3, 3, 2, 4, 1}}, {[]int{1, 1, 2, 2}, 2, []int{1, 2, 1, 2}}, } for _, testItem := range testItems { results := shuffleTheArray.ShuffleTheArray(testItem.nums, testItem.n) if len(results) != len(testItem.expected) { t.Errorf("shuffleTheArray(%v, %v) expected: %v, result: %v", testItem.nums, testItem.n, testItem.expected, results) continue } for i, result := range results { if result != testItem.expected[i] { t.Errorf("shuffleTheArray(%v, %v) expected: %v, result: %v", testItem.nums, testItem.n, testItem.expected, results) break } } } }
true
adac0003f7cf6117a8bf98e1852fb53219f60b30
Go
8090Lambert/Leetcode-Practice
/easy/26-removeDuplicates/removeDuplicates.go
UTF-8
475
3.109375
3
[]
no_license
[]
no_license
package removeDuplicates func removeDuplicates(nums []int) int { count := len(nums) if count < 2 { return count } prev := 0 for i := 1; i < count; i++ { if nums[prev] != nums[i] { prev++ nums[prev] = nums[i] } } return prev+1 } func removeDuplicates1(nums []int) int { count := len(nums) if count <= 1 { return count } slow := 0 for i := 0; i < count; i++ { if nums[slow] != nums[i] { slow++ nums[slow] = nums[i] } } return slow + 1 }
true
84c39429ca1788f639ae8834b088378d23b7eea8
Go
ashwathps/gofizzbuzz
/fizzbuzz-server/src/fizzbuzz_test.go
UTF-8
361
3.015625
3
[]
no_license
[]
no_license
package main import ( "strings" "fmt" "testing" ) func TestFizzBuzz15(t *testing.T) { have := FizzBuzz(int64(15)) have = strings.Replace(have, "\n", "", -1) fmt.Println(have) want := "12Fizz4BuzzFizz78FizzBuzz11Fizz1314FizzBuzz" fmt.Println(want) if have != want { t.Errorf("TestFizzBuzz15 wanted: \n %v \n but got \n %v \n", want, have) } }
true
99f7130bb93c6b39f5dc490a86364eaf657d2ffe
Go
bobrnor/hl-course
/pkg/authenticating/service.go
UTF-8
517
3.140625
3
[]
no_license
[]
no_license
package authenticating import "fmt" var ErrUserNotFound = fmt.Errorf("user not found") type Service interface { Authenticate(token string) (id int, err error) } type Repository interface { FindUser(token string) (*User, error) } type service struct { repo Repository } func NewService(r Repository) Service { return &service{ repo: r, } } func (s *service) Authenticate(token string) (id int, err error) { user, err := s.repo.FindUser(token) if err != nil { return 0, err } return user.ID, nil }
true
c5eb6acfd5b8740627b6dea6e9d5877a60a7f85f
Go
JasonZhao86/DevOpsGoScripts
/mylogger/filelogger.go
UTF-8
3,787
3.28125
3
[]
no_license
[]
no_license
package mylogger import ( "fmt" "os" "path" "time" ) // FileLogger 记录日志到文件的 type FileLogger struct { Level Level FileName string FilePath string File *os.File ErrFile *os.File MaxSize int64 } // NewFileLogger 构造FileLogger实例 func NewFileLogger(Level Level, FileName, FilePath string) (f *FileLogger) { logfile := path.Join(FilePath, FileName) errLogfile := fmt.Sprintf("%s.error", logfile) File, err := os.OpenFile(logfile, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0644) if err != nil { panic(fmt.Errorf("打开文件%s 失败, 原因是:%s", logfile, err)) } ErrFile, err := os.OpenFile(errLogfile, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0644) if err != nil { panic(fmt.Errorf("打开文件%s 失败, 原因是:%s", errLogfile, err)) } return &FileLogger{ Level: Level, FileName: FileName, FilePath: FilePath, File: File, ErrFile: ErrFile, MaxSize: 1 * MB, } } // CheckSplit 是否切割 func (f *FileLogger) CheckSplit(file *os.File) bool { fileinfo, _ := file.Stat() filesize := fileinfo.Size() return filesize >= f.MaxSize } // SplitFile 切割日志 func (f *FileLogger) SplitFile(file *os.File) *os.File { // 传入的可能是正常日志文件,也可能是error日志文件句柄 splittime := time.Now().Unix() filename := file.Name() // 获取的filename是带路径的 tarname := fmt.Sprintf("%s.log_%v", filename, splittime) // 拼接后的tarname也是带路径的。 file.Close() os.Rename(filename, tarname) fileobj, err := os.OpenFile(filename, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0644) if err != nil { panic(fmt.Errorf("Error: 打开文件%s失败", filename)) } return fileobj } // WriterLog 记录日志 func (f *FileLogger) WriterLog(level Level, format string, args ...interface{}) { // FileLogger实例的level属性如果高于日志的某个级别,则不记录该级别的日志。 if f.Level > level { /* WriterLog没有定义返回值,但是这里却有return,则实际上该函数不会反回任何数据,因此调用函数时 也就不能使用变量接收,所以此处的return语句只起到提前结束函数执行的作用。 */ return } msg := fmt.Sprintf(format, args...) nowStr := time.Now().Format("2006-01-02 15:04:05") funcName, file, line := GetCallerInfo(2) levelstr := ConvertLevelTOLevelstring(level) // 生成要写入日志信息 logmsg := fmt.Sprintf( "[%s][%s:%d][%s][%s]%s", nowStr, file, line, funcName, levelstr, msg, ) if level >= ErrorLevel { if f.CheckSplit(f.ErrFile) { f.ErrFile = f.SplitFile(f.ErrFile) } fmt.Fprintln(f.ErrFile, logmsg) return } if f.CheckSplit(f.File) { f.File = f.SplitFile(f.File) } fmt.Fprintln(f.File, logmsg) } // Debug 输出Debug日志到文件 func (f *FileLogger) Debug(format string, args ...interface{}) { f.WriterLog(DebugLevel, format, args...) } // Info 记录info级别的日志。 func (f *FileLogger) Info(format string, args ...interface{}) { f.WriterLog(InfoLevel, format, args...) } // Warning 记录Warning级别的日志。 func (f *FileLogger) Warning(format string, args ...interface{}) { f.WriterLog(WarningLevel, format, args...) } // Error 记录Error级别的日志。 func (f *FileLogger) Error(format string, args ...interface{}) { f.WriterLog(ErrorLevel, format, args...) } // Fatal 记录重大错误日志 func (f *FileLogger) Fatal(format string, args ...interface{}) { f.WriterLog(FatalLevel, format, args...) } // Close 关闭结构体中保存的日志文件句柄 func (f *FileLogger) Close() { f.File.Close() f.ErrFile.Close() }
true
3d81afec2fd499fe84c01f7214fbc6fce163196f
Go
yaminmhd/go-store-api-docker
/handler/product.go
UTF-8
791
2.703125
3
[]
no_license
[]
no_license
package handler import ( "net/http" "github.com/yaminmhd/go-hardware-store/constant" "github.com/yaminmhd/go-hardware-store/contract" "github.com/yaminmhd/go-hardware-store/log" ) type Product struct { service ProductService } func (handler *Product) GetProducts(w http.ResponseWriter, r *http.Request) { ctx := r.Context() products, err := handler.service.GetProducts(ctx) if err != nil { log.Log.Errorf(r, "[Products] Could not fetch products, %s", err) status := contract.ErrorObjects[err.Error()].Status contract.ErrorResponse(w, []string{err.Error()}, status) return } successStatus := constant.SuccessOK contract.SuccessfulResponse(w, products, successStatus) } func NewProductHandler(service ProductService) Product { return Product{ service: service, } }
true
24b6f377a1e3c4033b5dc94e567c1978d9f81c23
Go
pyhuo/goproject
/goproject/src/go/07(管道)/main.go
UTF-8
633
4.03125
4
[]
no_license
[]
no_license
package main import ( "fmt" "time" ) //定义一个管道 全局的变量 var ch = make(chan int) func main() { go method1() go method2() i := 0 for { i++ } } //目的是先执行方法1 在执行方法2 func method1() { Printer("jia") //在执行方法后往管道里面放数据 ch <- 200 } func method2() { //当开始执行的时候 从管道里面取数据,当发现里面没有那么阻塞, // 直到里面有数据了,取到了才开始执行 <-ch Printer("song") } func Printer(str string) { for _, value := range str { fmt.Print(string(value)) time.Sleep(time.Second) } fmt.Println() }
true
c377f2356ccf09a65fef8307a64efcd11def90b9
Go
zhangmingkai4315/golang-essentials
/04-基本类型/05-bit-shifting/main.go
UTF-8
386
3.015625
3
[ "MIT" ]
permissive
[ "MIT" ]
permissive
package main import ( "fmt" ) const ( _ = iota kb = 1 << (10 * iota) mb gb tb ) func main() { x := 10 fmt.Printf("%d\t\t%b\n", x, x) // 10 1010 fmt.Printf("%d\t\t%b\n", x<<1, x<<1) // 20 10100 fmt.Printf("%d\n", kb) fmt.Printf("%d\n", mb) fmt.Printf("%d\n", gb) fmt.Printf("%d\n", tb) // 1024 // 1048576 // 1073741824 // 1099511627776 }
true
80e0be3d9139cc96283b87f97df5ac76a6c5cdfd
Go
henrytk/aoc
/2016/01/taxi.go
UTF-8
2,814
3.765625
4
[]
no_license
[]
no_license
package main import ( "fmt" "math" "os" "strconv" "strings" ) type Instruction struct { Direction string Steps int } type InstructionParser interface { Parse(string) []Instruction } type BunnyInstructionParser struct{} func NewBunnyInstructionParser() *BunnyInstructionParser { return &BunnyInstructionParser{} } func (bip *BunnyInstructionParser) Parse(in string) []Instruction { var instructions []Instruction split := strings.Split(in, ", ") for _, v := range split { steps, _ := strconv.ParseInt(v[1:], 10, 64) instructions = append(instructions, Instruction{Direction: v[:1], Steps: int(steps)}) } return instructions } type Compass interface { Turn(string) Compass } type North struct{} type East struct{} type South struct{} type West struct{} func (n *North) Turn(dir string) Compass { if dir == "R" { return &East{} } return &West{} } func (e *East) Turn(dir string) Compass { if dir == "R" { return &South{} } return &North{} } func (s *South) Turn(dir string) Compass { if dir == "R" { return &West{} } return &East{} } func (w *West) Turn(dir string) Compass { if dir == "R" { return &North{} } return &South{} } type Point struct { X int Y int } type Taxi struct { Position Point Direction Compass BeenTo []Point } func NewTaxi() Taxi { return Taxi{ Position: Point{X: 0, Y: 0}, Direction: &North{}, } } func (t *Taxi) FollowInstructions(instructions string) { bip := NewBunnyInstructionParser() in := bip.Parse(instructions) for _, i := range in { t.Direction = t.Direction.Turn(i.Direction) for x := 0; x < i.Steps; x++ { t.Drive() } } } func (t *Taxi) Drive() { switch t.Direction.(type) { case *North: t.Position.Y = t.Position.Y + 1 case *East: t.Position.X = t.Position.X + 1 case *South: t.Position.Y = t.Position.Y - 1 default: t.Position.X = t.Position.X - 1 } t.BeenTo = append(t.BeenTo, t.Position) } func (t *Taxi) Distance() float64 { return distanceFromPoint(t.Position) } func distanceFromPoint(p Point) float64 { x := math.Abs(float64(p.X)) y := math.Abs(float64(p.Y)) return x + y } func (t *Taxi) DistanceFromFirstRepeatedPosition() float64 { positions := make(map[Point]bool) for _, location := range t.BeenTo { if _, ok := positions[location]; ok { return distanceFromPoint(location) } positions[location] = true } return float64(0) } func main() { if len(os.Args) != 2 { fmt.Fprintf(os.Stderr, "You must pass instructions as the first and only argument, you passed %v\n", len(os.Args)) os.Exit(1) } taxi := NewTaxi() taxi.FollowInstructions(os.Args[1]) fmt.Fprintf(os.Stdout, "You have travelled a distance of %v\n", taxi.Distance()) fmt.Fprintf(os.Stdout, "The Easter Bunny HQ is %v blocks away\n", taxi.DistanceFromFirstRepeatedPosition()) }
true
e8c0bed710ae5e37c02f8d7042ce84227f3ea6b9
Go
ocdogan/goutils
/dictionary/hashhelper.go
UTF-8
2,683
2.84375
3
[ "MIT" ]
permissive
[ "MIT" ]
permissive
// The MIT License (MIT) // // Copyright (c) 2016, Cagatay Dogan // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. package dictionary import ( "errors" "math" ) const hashPrime int = 101 const MaxPrimeArrayLength int = 0x7FEFFFFD var primes = []int{ 3, 7, 11, 17, 23, 29, 37, 47, 59, 71, 89, 107, 131, 163, 197, 239, 293, 353, 431, 521, 631, 761, 919, 1103, 1327, 1597, 1931, 2333, 2801, 3371, 4049, 4861, 5839, 7013, 8419, 10103, 12143, 14591, 17519, 21023, 25229, 30293, 36353, 43627, 52361, 62851, 75431, 90523, 108631, 130363, 156437, 187751, 225307, 270371, 324449, 389357, 467237, 560689, 672827, 807403, 968897, 1162687, 1395263, 1674319, 2009191, 2411033, 2893249, 3471899, 4166287, 4999559, 5999471, 7199369} func IsPrime(candidate int) bool { if (candidate & 1) != 0 { limit := candidate * candidate for divisor := 3; divisor <= limit; divisor += 2 { if (candidate % divisor) == 0 { return false } } return true } return (candidate == 2) } func GetPrime(min int) (int, error) { if min < 0 { return 0, errors.New("Capacity overflow") } primesLen := len(primes) for i := 0; i < primesLen; i++ { prime := primes[i] if prime >= min { return prime, nil } } for i := (min | 1); i < math.MaxInt32; i += 2 { if IsPrime(i) && ((i-1)%hashPrime != 0) { return i, nil } } return min, nil } func ExpandPrime(oldSize int) int { newSize := 2 * oldSize if uint(newSize) > uint(MaxPrimeArrayLength) && MaxPrimeArrayLength > oldSize { return MaxPrimeArrayLength } result, _ := GetPrime(newSize) return result }
true
2f93b7c6a09489a4eb8583d45c28276fcc60be7d
Go
danna1005/avatar
/controllers/tag.go
UTF-8
4,210
2.84375
3
[ "Apache-2.0" ]
permissive
[ "Apache-2.0" ]
permissive
package controllers import ( "avatar/models" "github.com/astaxie/beego" ) type TagController struct { beego.Controller } // 绑定标签 // article string 所属文章 // name string 标签名 func (this *TagController) Bind() { ok, data := func() (bool, interface{}) { member := &models.Member{} var session interface{} if session = this.GetSession("ID"); session == nil { return false, "未登录" } if _ok, _ := member.FindOne(session.(string)); !_ok { return false, "用户不存在" } article := &models.Article{} if _ok, _ := article.FindOne(this.GetString("article")); !_ok { return false, "文章不存在" } if member.Id != article.Uid && !member.Admin { return false, "没有权限" } // 标签数量限制、长度限制、同文章不能重复 if len(article.Tag) >= 5 { return false, "最多5个标签" } if len([]rune(this.GetString("name"))) > 15 || len([]rune(this.GetString("name"))) < 1 { return false, "标签最大长度为15" } tag := &models.Tag{} for k, _ := range article.Tag { if this.GetString("name") == article.Tag[k] { return false, "标签不能重复" } } // tag新增 tag.Upsert(this.GetString("name")) // 文章新增tag article.AddTag(this.GetString("name")) return true, "" }() this.Data["json"] = map[string]interface{}{ "ok": ok, "data": data, } this.ServeJson() } // 解绑标签 // topic string 所属文章 // name string 标签名 func (this *TagController) UnBind() { ok, data := func() (bool, interface{}) { member := &models.Member{} var session interface{} if session = this.GetSession("ID"); session == nil { return false, "未登录" } if _ok, _ := member.FindOne(session.(string)); !_ok { return false, "用户不存在" } article := &models.Article{} if _ok, _ := article.FindOne(this.GetString("article")); !_ok { return false, "文章不存在" } if member.Id != article.Uid && !member.Admin { return false, "没有权限" } // tag减少 tag := &models.Tag{} tag.CountReduce(this.GetString("name")) // 文章删除tag article.RemoveTag(this.GetString("name")) return true, "" }() this.Data["json"] = map[string]interface{}{ "ok": ok, "data": data, } this.ServeJson() } // 搜索标签 func (this *TagController) SearchTag() { tag := &models.Tag{} results := tag.Like(this.GetString("query")) suggestions := make([]string, len(results)) for k, _ := range results { suggestions[k] = results[k].Name } this.Data["json"] = map[string]interface{}{ "query": "Unit", "suggestions": suggestions, } this.ServeJson() } // 获取列表 func (this *TagController) GetList() { ok, data := func() (bool, interface{}) { if len([]rune(this.GetString("name"))) > 15 { return false, "标签最大长度为15" } from, _ := this.GetInt("from") number, _ := this.GetInt("number") if number > 100 { return false, "最多显示100项" } //查找标签 article := &models.Article{} lists := article.FindByTag(this.GetString("tag"), from, number) //查询该分类文章总数 count := article.FindTagCount(this.GetString("tag")) // 查询每个文章作者信息 member := &models.Member{} members := member.FindArticles(lists) return true, map[string]interface{}{ "lists": lists, "count": count, "members": members, } }() this.Data["json"] = map[string]interface{}{ "ok": ok, "data": data, } this.ServeJson() } // 获得排名前30的标签 func (this *TagController) Hot() { ok, data := func() (bool, interface{}) { tag := &models.Tag{} result := tag.Hot() return true, result }() this.Data["json"] = map[string]interface{}{ "ok": ok, "data": data, } this.ServeJson() } // 获取具有相同标签的文章 func (this *TagController) Same() { ok, data := func() (bool, interface{}) { // 查找文章 article := &models.Article{} if _ok, _ := article.FindOne(this.GetString("article")); !_ok { return false, "文章不存在" } result := article.Same() return true, result }() this.Data["json"] = map[string]interface{}{ "ok": ok, "data": data, } this.ServeJson() }
true
c8f6d47872275447fbb09e36700aca97884f1a7b
Go
seregayoga/twitchstream
/pkg/twitch/irc_ws_streamer.go
UTF-8
4,142
2.71875
3
[]
no_license
[]
no_license
package twitch import ( "encoding/json" "fmt" twitchirc "github.com/gempir/go-twitch-irc" "github.com/gorilla/websocket" ) // Event stream event type Event struct { Type string `json:"type"` Content string `json:"content"` } // IRCToWSStreamer streamer for events from irc to websocket type IRCToWSStreamer struct { ws *websocket.Conn ircClient *twitchirc.Client streamerName string token string } // NewIRCToWSStreamer creates new IRCToWSStreamer func NewIRCToWSStreamer(ws *websocket.Conn, userName string, streamerName string, token string) *IRCToWSStreamer { return &IRCToWSStreamer{ ws: ws, ircClient: twitchirc.NewClient(userName, "oauth:"+token), streamerName: streamerName, token: token, } } // Stream streams events from irc to websocket func (ircws *IRCToWSStreamer) Stream() error { ircws.ircClient.OnNewWhisper(func(user twitchirc.User, message twitchirc.Message) { event := Event{ Type: "whisper", Content: fmt.Sprintf("%s: %s", user.DisplayName, message.Text), } data, _ := json.Marshal(event) err := ircws.ws.WriteMessage(websocket.TextMessage, data) if err != nil { ircws.ircClient.Disconnect() } }) ircws.ircClient.OnNewMessage(func(channel string, user twitchirc.User, message twitchirc.Message) { event := Event{ Type: "message", Content: fmt.Sprintf("%s: %s", user.DisplayName, message.Text), } data, _ := json.Marshal(event) err := ircws.ws.WriteMessage(websocket.TextMessage, data) if err != nil { ircws.ircClient.Disconnect() } }) ircws.ircClient.OnNewRoomstateMessage(func(channel string, user twitchirc.User, message twitchirc.Message) { event := Event{ Type: "room state message", Content: fmt.Sprintf("%s: %s", user.DisplayName, message.Text), } data, _ := json.Marshal(event) err := ircws.ws.WriteMessage(websocket.TextMessage, data) if err != nil { ircws.ircClient.Disconnect() } }) ircws.ircClient.OnNewClearchatMessage(func(channel string, user twitchirc.User, message twitchirc.Message) { event := Event{ Type: "clear chat message", Content: fmt.Sprintf("%s: %s", user.DisplayName, message.Text), } data, _ := json.Marshal(event) err := ircws.ws.WriteMessage(websocket.TextMessage, data) if err != nil { ircws.ircClient.Disconnect() } }) ircws.ircClient.OnNewUsernoticeMessage(func(channel string, user twitchirc.User, message twitchirc.Message) { event := Event{ Type: "user notice message", Content: fmt.Sprintf("%s: %s", user.DisplayName, message.Text), } data, _ := json.Marshal(event) err := ircws.ws.WriteMessage(websocket.TextMessage, data) if err != nil { ircws.ircClient.Disconnect() } }) ircws.ircClient.OnNewNoticeMessage(func(channel string, user twitchirc.User, message twitchirc.Message) { event := Event{ Type: "notice message", Content: fmt.Sprintf("%s: %s", user.DisplayName, message.Text), } data, _ := json.Marshal(event) err := ircws.ws.WriteMessage(websocket.TextMessage, data) if err != nil { ircws.ircClient.Disconnect() } }) ircws.ircClient.OnNewUserstateMessage(func(channel string, user twitchirc.User, message twitchirc.Message) { event := Event{ Type: "user state message", Content: fmt.Sprintf("%s: %s", user.DisplayName, message.Text), } data, _ := json.Marshal(event) err := ircws.ws.WriteMessage(websocket.TextMessage, data) if err != nil { ircws.ircClient.Disconnect() } }) ircws.ircClient.OnUserJoin(func(channel, user string) { event := Event{ Type: "user join", Content: user, } data, _ := json.Marshal(event) err := ircws.ws.WriteMessage(websocket.TextMessage, data) if err != nil { ircws.ircClient.Disconnect() } }) ircws.ircClient.OnUserPart(func(channel, user string) { event := Event{ Type: "user part", Content: user, } data, _ := json.Marshal(event) err := ircws.ws.WriteMessage(websocket.TextMessage, data) if err != nil { ircws.ircClient.Disconnect() } }) ircws.ircClient.Join(ircws.streamerName) return ircws.ircClient.Connect() }
true
83be1e57917b1e308488af4d401da6e4e8113c57
Go
umitanuki/bigpot
/src/bigpot/system/spin/slock.go
UTF-8
312
2.734375
3
[]
no_license
[]
no_license
package spin import ( "runtime" "sync/atomic" ) type Lock uint32 func (slock *Lock) Lock() { for !atomic.CompareAndSwapUint32((*uint32)(slock), 0, 1) { runtime.Gosched() } } func (slock *Lock) Unlock() { if old := atomic.SwapUint32((*uint32)(slock), 0); old != 1 { panic("spin lock corrupted") } }
true
ef863b95021e1ff73a219614b26dcadebb7d48a7
Go
TheWug/fsb
/pkg/api/tags/tagset_test.go
UTF-8
11,426
3.171875
3
[ "MIT" ]
permissive
[ "MIT" ]
permissive
package tags import ( "testing" ) func TestTagSet(t *testing.T) { t.Run("Equal", Equal) t.Run("Set", Set) t.Run("Clear", Clear) t.Run("Apply", Apply) t.Run("Status", Status) t.Run("Merge", Merge) t.Run("ToggleArray", ToggleArray) t.Run("String", String) t.Run("Len", Len) t.Run("Reset", Reset) t.Run("ApplyDiff", ApplyDiff) t.Run("Clone", Clone) t.Run("ToggleString", ToggleString) t.Run("ApplyString", ApplyString) } func Equal(t *testing.T) { var pairs = []struct { name string expected bool first, second TagSet }{ {"empty to empty", true, TagSet{}, TagSet{}}, {"nil to empty", true, TagSet{StringSet: StringSet{Data: map[string]bool{}}}, TagSet{}}, {"empty to nonempty", false, TagSet{}, TagSet{StringSet: StringSet{Data: map[string]bool{"new string":true}}}}, {"same", true, TagSet{StringSet: StringSet{Data: map[string]bool{"new string":true, "old string":true}}}, TagSet{StringSet: StringSet{Data: map[string]bool{"old string":true, "new string":true}}}}, {"different", false, TagSet{StringSet: StringSet{Data: map[string]bool{"string 1":true}}}, TagSet{StringSet: StringSet{Data: map[string]bool{"string 2":true}}}}, } for _, x := range pairs { t.Run(x.name, func(t *testing.T) { if x.first.Equal(x.second) != x.expected { t.Errorf("\nExpected: %t\nActual: %t\n", x.expected, !x.expected) } }) } } func Set(t *testing.T) { var pairs = []struct { name string add string before, after TagSet }{ {"empty with space", "new tag", TagSet{}, TagSet{StringSet: StringSet{Data: map[string]bool{"new tag":true}}}}, {"empty", "newtag", TagSet{}, TagSet{StringSet: StringSet{Data: map[string]bool{"newtag":true}}}}, {"prefixed", "-newtag", TagSet{}, TagSet{StringSet: StringSet{Data: map[string]bool{"-newtag":true}}}}, {"nonempty", "newtag", TagSet{StringSet: StringSet{Data: map[string]bool{"existing":true}}}, TagSet{StringSet: StringSet{Data: map[string]bool{"existing":true, "newtag":true}}}}, {"duplicate", "duplicate", TagSet{StringSet: StringSet{Data: map[string]bool{"duplicate":true}}}, TagSet{StringSet: StringSet{Data: map[string]bool{"duplicate":true}}}}, } for _, x := range pairs { t.Run(x.name, func(t *testing.T) { x.before.Set(x.add) if !x.before.Equal(x.after) { t.Errorf("\nExpected: %+v\nActual: %+v\n", x.after, x.before) } }) } } func Clear(t *testing.T) { var pairs = []struct { name string remove string before, after TagSet }{ {"empty", "tag", TagSet{}, TagSet{}}, {"applicable", "tag", TagSet{StringSet: StringSet{Data: map[string]bool{"tag":true}}}, TagSet{}}, {"not applicable", "tag", TagSet{StringSet: StringSet{Data: map[string]bool{"othertag":true}}}, TagSet{StringSet: StringSet{Data: map[string]bool{"othertag":true}}}}, {"prefixed", "-tag", TagSet{StringSet: StringSet{Data: map[string]bool{"-tag":true}}}, TagSet{}}, } for _, x := range pairs { t.Run(x.name, func(t *testing.T) { x.before.Clear(x.remove) if !x.before.Equal(x.after) { t.Errorf("\nExpected: %+v\nActual: %+v\n", x.after, x.before) } }) } } func Apply(t *testing.T) { var pairs = []struct { name string tag string before, after TagSet }{ {"empty add", "tag", TagSet{}, TagSet{StringSet: StringSet{Data: map[string]bool{"tag":true}}}}, {"empty remove", "-tag", TagSet{}, TagSet{}}, {"extra add", "tag", TagSet{StringSet: StringSet{Data: map[string]bool{"extra":true}}}, TagSet{StringSet: StringSet{Data: map[string]bool{"extra":true, "tag":true}}}}, {"extra remove", "-tag", TagSet{StringSet: StringSet{Data: map[string]bool{"extra":true, "tag":true}}}, TagSet{StringSet: StringSet{Data: map[string]bool{"extra":true}}}}, {"duplicate add", "tag", TagSet{StringSet: StringSet{Data: map[string]bool{"tag":true}}}, TagSet{StringSet: StringSet{Data: map[string]bool{"tag":true}}}}, {"applicable remove", "-tag", TagSet{StringSet: StringSet{Data: map[string]bool{"tag":true}}}, TagSet{}}, {"wildcard remove", "-tag_*", TagSet{StringSet: StringSet{Data: map[string]bool{"tag_a":true, "tag_b":true}}}, TagSet{}}, } for _, x := range pairs { t.Run(x.name, func(t *testing.T) { x.before.Apply(x.tag) if !x.before.Equal(x.after) { t.Errorf("\nExpected: %+v\nActual: %+v\n", x.after, x.before) } }) } } func Status(t *testing.T) { var pairs = []struct { name string tag string expected DiffMembership set TagSet }{ {"empty", "tag", NotPresent, TagSet{}}, {"nonmember", "tag", NotPresent, TagSet{StringSet: StringSet{Data: map[string]bool{"other":true}}}}, {"member", "tag", AddsTag, TagSet{StringSet: StringSet{Data: map[string]bool{"tag":true}}}}, } for _, x := range pairs { t.Run(x.name, func(t *testing.T) { has := x.set.Status(x.tag) if has != x.expected { t.Errorf("\nExpected: %d\nActual: %d\n", x.expected, has) } }) } } func Merge(t *testing.T) { var pairs = []struct { name string merge TagSet start, end TagSet }{ {"empty", TagSet{}, TagSet{}, TagSet{}}, {"identity", TagSet{StringSet: StringSet{Data: map[string]bool{"member":true}}}, TagSet{StringSet: StringSet{Data: map[string]bool{"member":true}}}, TagSet{StringSet: StringSet{Data: map[string]bool{"member":true}}}}, {"normal", TagSet{StringSet: StringSet{Data: map[string]bool{"bar":true, "no":false}}}, TagSet{StringSet: StringSet{Data: map[string]bool{"foo":true}}}, TagSet{StringSet: StringSet{Data: map[string]bool{"foo":true, "bar":true}}}}, } for _, x := range pairs { t.Run(x.name, func(t *testing.T) { x.start.Merge(x.merge) if !x.start.Equal(x.end) { t.Errorf("\nExpected: %+v\nActual: %+v\n", x.end, x.start) } }) } } func ToggleArray(t *testing.T) { var pairs = []struct { name string toggle []string start, end TagSet }{ {"empty", []string{}, TagSet{}, TagSet{}}, {"identity", []string{}, TagSet{StringSet: StringSet{Data: map[string]bool{"foo":true}}}, TagSet{StringSet: StringSet{Data: map[string]bool{"foo":true}}}}, {"on", []string{"new"}, TagSet{StringSet: StringSet{Data: map[string]bool{"member":true}}}, TagSet{StringSet: StringSet{Data: map[string]bool{"member":true, "new":true}}}}, {"off", []string{"old"}, TagSet{StringSet: StringSet{Data: map[string]bool{"member":true, "old":true}}}, TagSet{StringSet: StringSet{Data: map[string]bool{"member":true}}}}, {"plus present", []string{"+member"}, TagSet{StringSet: StringSet{Data: map[string]bool{"member":true, "old":true}}}, TagSet{StringSet: StringSet{Data: map[string]bool{"member":true, "old":true}}}}, {"plus missing", []string{"+member"}, TagSet{StringSet: StringSet{Data: map[string]bool{"old":true}}}, TagSet{StringSet: StringSet{Data: map[string]bool{"old":true, "member":true}}}}, {"minus present", []string{"-member"}, TagSet{StringSet: StringSet{Data: map[string]bool{"member":true, "old":true}}}, TagSet{StringSet: StringSet{Data: map[string]bool{"old":true}}}}, {"minus missing", []string{"-member"}, TagSet{StringSet: StringSet{Data: map[string]bool{"old":true}}}, TagSet{StringSet: StringSet{Data: map[string]bool{"old":true}}}}, } for _, x := range pairs { t.Run(x.name, func(t *testing.T) { x.start.ToggleArray(x.toggle) if !x.start.Equal(x.end) { t.Errorf("\nExpected: %+v\nActual: %+v\n", x.end, x.start) } }) } } func String(t *testing.T) { var pairs = []struct { name, expected string start TagSet }{ {"empty", "", TagSet{}}, {"weird", "+foo -bar", TagSet{StringSet: StringSet{Data: map[string]bool{"+foo":true, "-bar":true}}}}, {"normal", "bar foo", TagSet{StringSet: StringSet{Data: map[string]bool{"foo":true, "bar":true}}}}, } for _, x := range pairs { t.Run(x.name, func(t *testing.T) { out := x.start.String() if out != x.expected { t.Errorf("\nExpected: %s\nActual: %s\n", x.expected, out) } }) } } func Len(t *testing.T) { var pairs = []struct { name string count int value TagSet }{ {"empty", 0, TagSet{}}, {"4", 4, TagSet{StringSet: StringSet{Data: map[string]bool{"a":true, "aa":true, "aaa":true, "aaaa":true}}}}, } for _, x := range pairs { t.Run(x.name, func(t *testing.T) { out := x.value.Len() if out != x.count { t.Errorf("\nExpected: %d\nActual: %d\n", x.count, out) } }) } } func Reset(t *testing.T) { set := TagSet{StringSet: StringSet{Data: map[string]bool{"foobar":true}}} set.Reset() if !set.Equal(TagSet{}) { t.Errorf("\nExpected: %+v\nActual: %+v\n", TagSet{}, set) } } func ApplyDiff(t *testing.T) { var pairs = []struct { name string in TagSet diff TagDiff out TagSet }{ {"empty", TagSet{}, TagDiff{}, TagSet{}}, {"identity", TagSet{StringSet: StringSet{Data: map[string]bool{"foo":true, "bar":true}}}, TagDiff{}, TagSet{StringSet: StringSet{Data: map[string]bool{"foo":true, "bar":true}}}}, {"mixed remove", TagSet{StringSet: StringSet{Data: map[string]bool{"foo":true, "bar":true}}}, TagDiff{StringDiff: StringDiff{RemoveList: map[string]bool{"bar":true, "baz":true}}}, TagSet{StringSet: StringSet{Data: map[string]bool{"foo":true}}}}, {"mixed add", TagSet{StringSet: StringSet{Data: map[string]bool{"foo":true, "bar":true}}}, TagDiff{StringDiff: StringDiff{AddList: map[string]bool{"bar":true, "baz":true}}}, TagSet{StringSet: StringSet{Data: map[string]bool{"foo":true, "bar":true, "baz":true}}}}, } for _, x := range pairs { t.Run(x.name, func(t *testing.T) { x.in.ApplyDiff(x.diff) if !x.in.Equal(x.out) { t.Errorf("\nExpected: %+v\nActual: %+v\n", x.out, x.in) } }) } } func Clone(t *testing.T) { testcases := map[string]struct{ in TagSet }{ "empty": {}, "normal": {TagSet{StringSet{Data: map[string]bool{"foo":true, "bar":true}}}}, } for k, v := range testcases { t.Run(k, func(t *testing.T) { out := v.in.Clone() if !v.in.Equal(out) { t.Errorf("\nExpected: %+v\nActual: %+v\n", out, v.in) } out.Set("previously-unset") if v.in.Equal(out) { t.Errorf("Clone performed a shallow copy!") } }) } } func ToggleString(t *testing.T) { testcases := map[string]struct{ in TagSet out TagSet toggle string }{ "empty": {}, "simple 1": {TagSet{StringSet{nil}}, TagSet{StringSet{map[string]bool{"foo":true, "baz":true}}}, "foo -bar +baz"}, "simple 2": {TagSet{StringSet{map[string]bool{"foo":true, "baz":true, "bar":true}}}, TagSet{StringSet{map[string]bool{"baz":true}}}, "foo -bar +baz"}, } for k, v := range testcases { t.Run(k, func(t *testing.T) { v.in.ToggleString(v.toggle) if !v.in.Equal(v.out) { t.Errorf("\nExpected: %+v\nActual: %+v\n", v.out, v.in) } }) } } func ApplyString(t *testing.T) { testcases := map[string]struct{ in TagSet out TagSet toggle string }{ "empty": {}, "simple 1": {TagSet{StringSet{nil}}, TagSet{StringSet{map[string]bool{"foo":true, "baz":true}}}, "foo -bar baz"}, "simple 2": {TagSet{StringSet{map[string]bool{"foo":true, "baz":true, "bar":true}}}, TagSet{StringSet{map[string]bool{"foo":true, "baz":true}}}, "foo -bar baz"}, } for k, v := range testcases { t.Run(k, func(t *testing.T) { v.in.ApplyString(v.toggle) if !v.in.Equal(v.out) { t.Errorf("\nExpected: %+v\nActual: %+v\n", v.out, v.in) } }) } }
true
3ebb5100d96710bbc45cbfdc98762edf07e8bc4e
Go
matrixorigin/matrixone
/pkg/container/types/binary.go
UTF-8
1,339
2.53125
3
[ "Apache-2.0" ]
permissive
[ "Apache-2.0" ]
permissive
// Copyright 2021 - 2022 Matrix Origin // // 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 "github.com/matrixorigin/matrixone/pkg/common/moerr" func BitAnd(result, v1, v2 []byte) { if len(v1) != len(v2) { panic(moerr.NewInternalErrorNoCtx("Binary operands of bitwise operators must be of equal length")) } for i := range v1 { result[i] = v1[i] & v2[i] } } func BitOr(result, v1, v2 []byte) { if len(v1) != len(v2) { panic(moerr.NewInternalErrorNoCtx("Binary operands of bitwise operators must be of equal length")) } for i := range v1 { result[i] = v1[i] | v2[i] } } func BitXor(result, v1, v2 []byte) { if len(v1) != len(v2) { panic(moerr.NewInternalErrorNoCtx("Binary operands of bitwise operators must be of equal length")) } for i := range v1 { result[i] = v1[i] ^ v2[i] } }
true
a9be88e3a312df556f775e2d2daab3792fb2df87
Go
caozhijian/go-study
/func/func_params/main.go
UTF-8
1,625
4.3125
4
[]
no_license
[]
no_license
package main import "fmt" //省略号的用途 1.函数参数不定长 2.将slice打散 3.初始化数组 func main() { // 通过省略号去动态设置多个参数值 fmt.Println(add(1, 2, 3, 4, 5)) slice := []int{2, 3, 4, 5, 6} fmt.Println(add(slice...)) //将slice打散 //slice是一种类型,还是引用传递,所以需要谨慎使用 slice2 := []int{1, 2, 3, 4, 5} fmt.Println(add2(slice2)) fmt.Println(slice2) arr := [...]int{1, 2, 3} fmt.Printf("%T\n", arr) //函数是一等公民,可以作为参数、返回值、赋值给另一个变量 myFunc := add fmt.Printf("myFunc的类型是%T\n", myFunc()) //匿名函数 myFunc2 := func(a, b int) int { return a + b } myFunc2(1, 2) result := func(a, b int) int { return a + b }(3, 4) fmt.Println(result) var mySub sub = subImpl var mySub2 sub = func(a, b int) int { return a - b } fmt.Println(mySub(9, 0), mySub2(8, 1)) //函数可以作为其它函数的参数进行传递 score := []int{90, 33, 69, 88, 100} fmt.Println(filter(score, func(i int) bool { if i >= 90 { return true } else { return false } })) } func add(params ...int) (sum int) { for _, param := range params { sum += param } return } func add2(params []int) (sum int) { for _, param := range params { sum += param } params[0] = 9 return } //自定义sub类型 type sub func(a, b int) int func subImpl(a, b int) int { return a - b } func filter(scores []int, line func(int) bool) []int { reSlice := make([]int, 0) for _, score := range scores { if line(score) { reSlice = append(reSlice, score) } } return reSlice }
true
3bf5b192fae58ab17dd8d8e9a234056dd3e3b8a0
Go
shahabkhan22/GoLangLearning
/BasicConcepts/Exercise4.go
UTF-8
165
3.25
3
[]
no_license
[]
no_license
package main import "fmt" var t int type myType int var x myType func main() { fmt.Println("x = ", x) fmt.Printf("%T\n", x) x = 42 fmt.Println("x = ", x) }
true
0ff0ba11ef223a6cc8c12de1dd279b966fde00a6
Go
lpdpzc/GoServer
/go/src/svr_sdk/logic/recv_game_msg.go
UTF-8
1,421
2.515625
3
[]
no_license
[]
no_license
/*********************************************************************** * @ 游戏服msg的处理 * @ brief 1、gamesvr先通知SDK进程,建立新充值订单 2、第三方充值信息到达后,验证是否为有效订单 * @ author zhoumf * @ date 2016-8-18 ***********************************************************************/ package logic import ( "encoding/json" "fmt" "gamelog" "msg/sdk_msg" "net/http" ) func HandSvr_CreateRechargeOrder(w http.ResponseWriter, r *http.Request) { gamelog.Info("message: %s", r.URL.String()) //! 接收信息 buffer := make([]byte, r.ContentLength) r.Body.Read(buffer) //! 解析消息 var req sdk_msg.SDKMsg_create_recharge_order_Req err := json.Unmarshal(buffer, &req) if err != nil { gamelog.Error("HandSvr_CreateRechargeOrder unmarshal fail. Error: %s", err.Error()) return } fmt.Println(req) //! 创建回复 var response sdk_msg.SDKMsg_create_recharge_order_Ack response.RetCode = -1 defer func() { b, _ := json.Marshal(&response) w.Write(b) }() //TODO:生成订单,等待第三方的充值信息 pOrder := new(TRechargeOrder) pOrder.OrderID = req.OrderID pOrder.GamesvrID = req.GamesvrID pOrder.PlayerID = req.PlayerID pOrder.AccountID = req.PlayerID pOrder.Channel = req.Channel pOrder.PlatformEnum = req.PlatformEnum pOrder.chargeCsvID = req.ChargeCsvID CacheRechargeOrder(pOrder) response.RetCode = 0 }
true
ff396b70ac2f1747089b5ad43d5eeb6ef84c7d13
Go
thomas995/GO-Group-Web-App
/src/github.com/go-bootstrap/go-bootstrap/project-templates/postgresql/models/user.go
UTF-8
3,040
3.078125
3
[ "MIT" ]
permissive
[ "MIT" ]
permissive
package models import ( "database/sql" "errors" "fmt" "github.com/jmoiron/sqlx" "golang.org/x/crypto/bcrypt" ) func NewUser(db *sqlx.DB) *User { user := &User{} user.db = db user.table = "users" user.hasID = true return user } type UserRow struct { ID int64 `db:"id"` Email string `db:"email"` Password string `db:"password"` } type User struct { Base } func (u *User) userRowFromSqlResult(tx *sqlx.Tx, sqlResult sql.Result) (*UserRow, error) { userId, err := sqlResult.LastInsertId() if err != nil { return nil, err } return u.GetById(tx, userId) } // AllUsers returns all user rows. func (u *User) AllUsers(tx *sqlx.Tx) ([]*UserRow, error) { users := []*UserRow{} query := fmt.Sprintf("SELECT * FROM %v", u.table) err := u.db.Select(&users, query) return users, err } // GetById returns record by id. func (u *User) GetById(tx *sqlx.Tx, id int64) (*UserRow, error) { user := &UserRow{} query := fmt.Sprintf("SELECT * FROM %v WHERE id=$1", u.table) err := u.db.Get(user, query, id) return user, err } // GetByEmail returns record by email. func (u *User) GetByEmail(tx *sqlx.Tx, email string) (*UserRow, error) { user := &UserRow{} query := fmt.Sprintf("SELECT * FROM %v WHERE email=$1", u.table) err := u.db.Get(user, query, email) return user, err } // GetByEmail returns record by email but checks password first. func (u *User) GetUserByEmailAndPassword(tx *sqlx.Tx, email, password string) (*UserRow, error) { user, err := u.GetByEmail(tx, email) if err != nil { return nil, err } err = bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(password)) if err != nil { return nil, err } return user, err } // Signup create a new record of user. func (u *User) Signup(tx *sqlx.Tx, email, password, passwordAgain string) (*UserRow, error) { if email == "" { return nil, errors.New("Email cannot be blank.") } if password == "" { return nil, errors.New("Password cannot be blank.") } if password != passwordAgain { return nil, errors.New("Password is invalid.") } hashedPassword, err := bcrypt.GenerateFromPassword([]byte(password), 5) if err != nil { return nil, err } data := make(map[string]interface{}) data["email"] = email data["password"] = hashedPassword sqlResult, err := u.InsertIntoTable(tx, data) if err != nil { return nil, err } return u.userRowFromSqlResult(tx, sqlResult) } // UpdateEmailAndPasswordById updates user email and password. func (u *User) UpdateEmailAndPasswordById(tx *sqlx.Tx, userId int64, email, password, passwordAgain string) (*UserRow, error) { data := make(map[string]interface{}) if email != "" { data["email"] = email } if password != "" && passwordAgain != "" && password == passwordAgain { hashedPassword, err := bcrypt.GenerateFromPassword([]byte(password), 5) if err != nil { return nil, err } data["password"] = hashedPassword } if len(data) > 0 { _, err := u.UpdateByID(tx, data, userId) if err != nil { return nil, err } } return u.GetById(tx, userId) }
true
6edd862979828b4a98483c7538b23b42152df3da
Go
knkcms/go-xslt
/xslt.go
UTF-8
1,932
2.703125
3
[ "MIT" ]
permissive
[ "MIT" ]
permissive
package xslt /* #cgo LDFLAGS: -lxml2 -lxslt -lz -llzma -lm #cgo CFLAGS: -I/usr/include -I/usr/include/libxml2 #cgo freebsd LDFLAGS: -L/usr/local/lib #cgo freebsd CFLAGS: -I/usr/local/include -I/usr/local/include/libxml2 #include <string.h> #include "xslt.h" */ import "C" import ( "errors" "unsafe" ) // Transformation errors var ( ErrXSLTFailure = errors.New("XSL transformation failed") ErrXSLParseFailure = errors.New("Failed to parse XSL") ) // Stylesheet represents an XSL type Stylesheet struct { ptr C.xsltStylesheetPtr } // Close frees memory associated with a stylesheet. Additional calls // to Close will be ignored. func (xs *Stylesheet) Close() { if xs.ptr != nil { C.free_style(&xs.ptr) xs.ptr = nil } } // Transform applies the receiver to the XML and returns the result of // an XSL transformation and any errors. The resulting document may // be nil (a zero-length and zero-capacity byte slice) in the case of // an error. func (xs *Stylesheet) Transform(xml []byte) ([]byte, error) { var ( cxml *C.char cout *C.char ret C.int size C.size_t ) cxml = C.CString(string(xml)) defer C.free(unsafe.Pointer(cxml)) ret = C.apply_style(xs.ptr, cxml, &cout, &size) if ret != 0 { defer C.free(unsafe.Pointer(cout)) return nil, ErrXSLTFailure } ptr := unsafe.Pointer(cout) defer C.free(ptr) return C.GoBytes(ptr, C.int(size)), nil } // NewStylesheet creates and returns a new stylesheet along with any // errors. The resulting stylesheet ay be nil if an error is // encountered during parsing. This implementation relies on Libxslt, // which supports XSLT 1.0. func NewStylesheet(xsl []byte) (*Stylesheet, error) { var ( cxsl *C.char cssp C.xsltStylesheetPtr ret C.int ) cxsl = C.CString(string(xsl)) defer C.free(unsafe.Pointer(cxsl)) ret = C.make_style(cxsl, &cssp) if ret != 0 { return nil, ErrXSLParseFailure } return &Stylesheet{ptr: cssp}, nil }
true
8ad7d66f98cb3224f225c33efa1f473bc592b22b
Go
golang/image
/vector/vector_test.go
UTF-8
17,076
3.171875
3
[ "LicenseRef-scancode-google-patent-license-golang", "BSD-3-Clause" ]
permissive
[ "LicenseRef-scancode-google-patent-license-golang", "BSD-3-Clause" ]
permissive
// Copyright 2016 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package vector // TODO: add tests for NaN and Inf coordinates. import ( "fmt" "image" "image/color" "image/draw" "image/png" "math" "math/rand" "os" "path/filepath" "testing" ) // encodePNG is useful for manually debugging the tests. func encodePNG(dstFilename string, src image.Image) error { f, err := os.Create(dstFilename) if err != nil { return err } encErr := png.Encode(f, src) closeErr := f.Close() if encErr != nil { return encErr } return closeErr } func pointOnCircle(center, radius, index, number int) (x, y float32) { c := float64(center) r := float64(radius) i := float64(index) n := float64(number) return float32(c + r*(math.Cos(2*math.Pi*i/n))), float32(c + r*(math.Sin(2*math.Pi*i/n))) } func TestRasterizeOutOfBounds(t *testing.T) { // Set this to a non-empty string such as "/tmp" to manually inspect the // rasterization. // // If empty, this test simply checks that calling LineTo with points out of // the rasterizer's bounds doesn't panic. const tmpDir = "" const center, radius, n = 16, 20, 16 var z Rasterizer for i := 0; i < n; i++ { for j := 1; j < n/2; j++ { z.Reset(2*center, 2*center) z.MoveTo(1*center, 1*center) z.LineTo(pointOnCircle(center, radius, i+0, n)) z.LineTo(pointOnCircle(center, radius, i+j, n)) z.ClosePath() z.MoveTo(0*center, 0*center) z.LineTo(0*center, 2*center) z.LineTo(2*center, 2*center) z.LineTo(2*center, 0*center) z.ClosePath() dst := image.NewAlpha(z.Bounds()) z.Draw(dst, dst.Bounds(), image.Opaque, image.Point{}) if tmpDir == "" { continue } filename := filepath.Join(tmpDir, fmt.Sprintf("out-%02d-%02d.png", i, j)) if err := encodePNG(filename, dst); err != nil { t.Error(err) } t.Logf("wrote %s", filename) } } } func TestRasterizePolygon(t *testing.T) { var z Rasterizer for radius := 4; radius <= 256; radius *= 2 { for n := 3; n <= 19; n += 4 { z.Reset(2*radius, 2*radius) z.MoveTo(float32(2*radius), float32(1*radius)) for i := 1; i < n; i++ { z.LineTo(pointOnCircle(radius, radius, i, n)) } z.ClosePath() dst := image.NewAlpha(z.Bounds()) z.Draw(dst, dst.Bounds(), image.Opaque, image.Point{}) if err := checkCornersCenter(dst); err != nil { t.Errorf("radius=%d, n=%d: %v", radius, n, err) } } } } func TestRasterizeAlmostAxisAligned(t *testing.T) { z := NewRasterizer(8, 8) z.MoveTo(2, 2) z.LineTo(6, math.Nextafter32(2, 0)) z.LineTo(6, 6) z.LineTo(math.Nextafter32(2, 0), 6) z.ClosePath() dst := image.NewAlpha(z.Bounds()) z.Draw(dst, dst.Bounds(), image.Opaque, image.Point{}) if err := checkCornersCenter(dst); err != nil { t.Error(err) } } func TestRasterizeWideAlmostHorizontalLines(t *testing.T) { var z Rasterizer for i := uint(3); i < 16; i++ { x := float32(int(1 << i)) z.Reset(8, 8) z.MoveTo(-x, 3) z.LineTo(+x, 4) z.LineTo(+x, 6) z.LineTo(-x, 6) z.ClosePath() dst := image.NewAlpha(z.Bounds()) z.Draw(dst, dst.Bounds(), image.Opaque, image.Point{}) if err := checkCornersCenter(dst); err != nil { t.Errorf("i=%d: %v", i, err) } } } func TestRasterize30Degrees(t *testing.T) { z := NewRasterizer(8, 8) z.MoveTo(4, 4) z.LineTo(8, 4) z.LineTo(4, 6) z.ClosePath() dst := image.NewAlpha(z.Bounds()) z.Draw(dst, dst.Bounds(), image.Opaque, image.Point{}) if err := checkCornersCenter(dst); err != nil { t.Error(err) } } func TestRasterizeRandomLineTos(t *testing.T) { var z Rasterizer for i := 5; i < 50; i++ { n, rng := 0, rand.New(rand.NewSource(int64(i))) z.Reset(i+2, i+2) z.MoveTo(float32(i/2), float32(i/2)) for ; rng.Intn(16) != 0; n++ { x := 1 + rng.Intn(i) y := 1 + rng.Intn(i) z.LineTo(float32(x), float32(y)) } z.ClosePath() dst := image.NewAlpha(z.Bounds()) z.Draw(dst, dst.Bounds(), image.Opaque, image.Point{}) if err := checkCorners(dst); err != nil { t.Errorf("i=%d (%d nodes): %v", i, n, err) } } } // checkCornersCenter checks that the corners of the image are all 0x00 and the // center is 0xff. func checkCornersCenter(m *image.Alpha) error { if err := checkCorners(m); err != nil { return err } size := m.Bounds().Size() center := m.Pix[(size.Y/2)*m.Stride+(size.X/2)] if center != 0xff { return fmt.Errorf("center: got %#02x, want 0xff", center) } return nil } // checkCorners checks that the corners of the image are all 0x00. func checkCorners(m *image.Alpha) error { size := m.Bounds().Size() corners := [4]uint8{ m.Pix[(0*size.Y+0)*m.Stride+(0*size.X+0)], m.Pix[(0*size.Y+0)*m.Stride+(1*size.X-1)], m.Pix[(1*size.Y-1)*m.Stride+(0*size.X+0)], m.Pix[(1*size.Y-1)*m.Stride+(1*size.X-1)], } if corners != [4]uint8{} { return fmt.Errorf("corners were not all zero: %v", corners) } return nil } var basicMask = []byte{ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xe3, 0xaa, 0x3e, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfa, 0x5f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfc, 0x24, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xa1, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfc, 0x14, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x4a, 0x00, 0x00, 0x00, 0x00, 0xcc, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x81, 0x00, 0x00, 0x00, 0x00, 0x66, 0xff, 0xff, 0xff, 0xff, 0xff, 0xef, 0xe4, 0xff, 0xff, 0xff, 0xb6, 0x00, 0x00, 0x00, 0x00, 0x0c, 0xf2, 0xff, 0xff, 0xfe, 0x9e, 0x15, 0x00, 0x15, 0x96, 0xff, 0xce, 0x00, 0x00, 0x00, 0x00, 0x00, 0x88, 0xfc, 0xe3, 0x43, 0x00, 0x00, 0x00, 0x00, 0x06, 0xcd, 0xdc, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x0f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x25, 0xde, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x56, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, } func testBasicPath(t *testing.T, prefix string, dst draw.Image, src image.Image, op draw.Op, want []byte) { z := NewRasterizer(16, 16) z.MoveTo(2, 2) z.LineTo(8, 2) z.QuadTo(14, 2, 14, 14) z.CubeTo(8, 2, 5, 20, 2, 8) z.ClosePath() z.DrawOp = op z.Draw(dst, z.Bounds(), src, image.Point{}) var got []byte switch dst := dst.(type) { case *image.Alpha: got = dst.Pix case *image.RGBA: got = dst.Pix default: t.Errorf("%s: unrecognized dst image type %T", prefix, dst) } if len(got) != len(want) { t.Errorf("%s: len(got)=%d and len(want)=%d differ", prefix, len(got), len(want)) return } for i := range got { delta := int(got[i]) - int(want[i]) // The +/- 2 allows different implementations to give different // rounding errors. if delta < -2 || +2 < delta { t.Errorf("%s: i=%d: got %#02x, want %#02x", prefix, i, got[i], want[i]) return } } } func TestBasicPathDstAlpha(t *testing.T) { for _, background := range []uint8{0x00, 0x80} { for _, op := range []draw.Op{draw.Over, draw.Src} { for _, xPadding := range []int{0, 7} { bounds := image.Rect(0, 0, 16+xPadding, 16) dst := image.NewAlpha(bounds) for i := range dst.Pix { dst.Pix[i] = background } want := make([]byte, len(dst.Pix)) copy(want, dst.Pix) if op == draw.Over && background == 0x80 { for y := 0; y < 16; y++ { for x := 0; x < 16; x++ { ma := basicMask[16*y+x] i := dst.PixOffset(x, y) want[i] = 0xff - (0xff-ma)/2 } } } else { for y := 0; y < 16; y++ { for x := 0; x < 16; x++ { ma := basicMask[16*y+x] i := dst.PixOffset(x, y) want[i] = ma } } } prefix := fmt.Sprintf("background=%#02x, op=%v, xPadding=%d", background, op, xPadding) testBasicPath(t, prefix, dst, image.Opaque, op, want) } } } } func TestBasicPathDstRGBA(t *testing.T) { blue := image.NewUniform(color.RGBA{0x00, 0x00, 0xff, 0xff}) for _, op := range []draw.Op{draw.Over, draw.Src} { for _, xPadding := range []int{0, 7} { bounds := image.Rect(0, 0, 16+xPadding, 16) dst := image.NewRGBA(bounds) for y := bounds.Min.Y; y < bounds.Max.Y; y++ { for x := bounds.Min.X; x < bounds.Max.X; x++ { dst.SetRGBA(x, y, color.RGBA{ R: uint8(y * 0x07), G: uint8(x * 0x05), B: 0x00, A: 0x80, }) } } want := make([]byte, len(dst.Pix)) copy(want, dst.Pix) if op == draw.Over { for y := 0; y < 16; y++ { for x := 0; x < 16; x++ { ma := basicMask[16*y+x] i := dst.PixOffset(x, y) want[i+0] = uint8((uint32(0xff-ma) * uint32(y*0x07)) / 0xff) want[i+1] = uint8((uint32(0xff-ma) * uint32(x*0x05)) / 0xff) want[i+2] = ma want[i+3] = ma/2 + 0x80 } } } else { for y := 0; y < 16; y++ { for x := 0; x < 16; x++ { ma := basicMask[16*y+x] i := dst.PixOffset(x, y) want[i+0] = 0x00 want[i+1] = 0x00 want[i+2] = ma want[i+3] = ma } } } prefix := fmt.Sprintf("op=%v, xPadding=%d", op, xPadding) testBasicPath(t, prefix, dst, blue, op, want) } } } const ( benchmarkGlyphWidth = 893 benchmarkGlyphHeight = 1122 ) type benchmarkGlyphDatum struct { // n being 0, 1 or 2 means moveTo, lineTo or quadTo. n uint32 px float32 py float32 qx float32 qy float32 } // benchmarkGlyphData is the 'a' glyph from the Roboto Regular font, translated // so that its top left corner is (0, 0). var benchmarkGlyphData = []benchmarkGlyphDatum{ {0, 699, 1102, 0, 0}, {2, 683, 1070, 673, 988}, {2, 544, 1122, 365, 1122}, {2, 205, 1122, 102.5, 1031.5}, {2, 0, 941, 0, 802}, {2, 0, 633, 128.5, 539.5}, {2, 257, 446, 490, 446}, {1, 670, 446, 0, 0}, {1, 670, 361, 0, 0}, {2, 670, 264, 612, 206.5}, {2, 554, 149, 441, 149}, {2, 342, 149, 275, 199}, {2, 208, 249, 208, 320}, {1, 22, 320, 0, 0}, {2, 22, 239, 79.5, 163.5}, {2, 137, 88, 235.5, 44}, {2, 334, 0, 452, 0}, {2, 639, 0, 745, 93.5}, {2, 851, 187, 855, 351}, {1, 855, 849, 0, 0}, {2, 855, 998, 893, 1086}, {1, 893, 1102, 0, 0}, {1, 699, 1102, 0, 0}, {0, 392, 961, 0, 0}, {2, 479, 961, 557, 916}, {2, 635, 871, 670, 799}, {1, 670, 577, 0, 0}, {1, 525, 577, 0, 0}, {2, 185, 577, 185, 776}, {2, 185, 863, 243, 912}, {2, 301, 961, 392, 961}, } func scaledBenchmarkGlyphData(height int) (width int, data []benchmarkGlyphDatum) { scale := float32(height) / benchmarkGlyphHeight // Clone the benchmarkGlyphData slice and scale its coordinates. data = append(data, benchmarkGlyphData...) for i := range data { data[i].px *= scale data[i].py *= scale data[i].qx *= scale data[i].qy *= scale } return int(math.Ceil(float64(benchmarkGlyphWidth * scale))), data } // benchGlyph benchmarks rasterizing a TrueType glyph. // // Note that, compared to the github.com/google/font-go prototype, the height // here is the height of the bounding box, not the pixels per em used to scale // a glyph's vectors. A height of 64 corresponds to a ppem greater than 64. func benchGlyph(b *testing.B, colorModel byte, loose bool, height int, op draw.Op) { width, data := scaledBenchmarkGlyphData(height) z := NewRasterizer(width, height) bounds := z.Bounds() if loose { bounds.Max.X++ } dst, src := draw.Image(nil), image.Image(nil) switch colorModel { case 'A': dst = image.NewAlpha(bounds) src = image.Opaque case 'N': dst = image.NewNRGBA(bounds) src = image.NewUniform(color.NRGBA{0x40, 0x80, 0xc0, 0xff}) case 'R': dst = image.NewRGBA(bounds) src = image.NewUniform(color.RGBA{0x40, 0x80, 0xc0, 0xff}) default: b.Fatal("unsupported color model") } bounds = z.Bounds() b.ResetTimer() for i := 0; i < b.N; i++ { z.Reset(width, height) z.DrawOp = op for _, d := range data { switch d.n { case 0: z.MoveTo(d.px, d.py) case 1: z.LineTo(d.px, d.py) case 2: z.QuadTo(d.px, d.py, d.qx, d.qy) } } z.Draw(dst, bounds, src, image.Point{}) } } // The heights 16, 32, 64, 128, 256, 1024 include numbers both above and below // the floatingPointMathThreshold constant (512). func BenchmarkGlyphAlpha16Over(b *testing.B) { benchGlyph(b, 'A', false, 16, draw.Over) } func BenchmarkGlyphAlpha16Src(b *testing.B) { benchGlyph(b, 'A', false, 16, draw.Src) } func BenchmarkGlyphAlpha32Over(b *testing.B) { benchGlyph(b, 'A', false, 32, draw.Over) } func BenchmarkGlyphAlpha32Src(b *testing.B) { benchGlyph(b, 'A', false, 32, draw.Src) } func BenchmarkGlyphAlpha64Over(b *testing.B) { benchGlyph(b, 'A', false, 64, draw.Over) } func BenchmarkGlyphAlpha64Src(b *testing.B) { benchGlyph(b, 'A', false, 64, draw.Src) } func BenchmarkGlyphAlpha128Over(b *testing.B) { benchGlyph(b, 'A', false, 128, draw.Over) } func BenchmarkGlyphAlpha128Src(b *testing.B) { benchGlyph(b, 'A', false, 128, draw.Src) } func BenchmarkGlyphAlpha256Over(b *testing.B) { benchGlyph(b, 'A', false, 256, draw.Over) } func BenchmarkGlyphAlpha256Src(b *testing.B) { benchGlyph(b, 'A', false, 256, draw.Src) } func BenchmarkGlyphAlpha1024Over(b *testing.B) { benchGlyph(b, 'A', false, 1024, draw.Over) } func BenchmarkGlyphAlpha1024Src(b *testing.B) { benchGlyph(b, 'A', false, 1024, draw.Src) } func BenchmarkGlyphAlphaLoose16Over(b *testing.B) { benchGlyph(b, 'A', true, 16, draw.Over) } func BenchmarkGlyphAlphaLoose16Src(b *testing.B) { benchGlyph(b, 'A', true, 16, draw.Src) } func BenchmarkGlyphAlphaLoose32Over(b *testing.B) { benchGlyph(b, 'A', true, 32, draw.Over) } func BenchmarkGlyphAlphaLoose32Src(b *testing.B) { benchGlyph(b, 'A', true, 32, draw.Src) } func BenchmarkGlyphAlphaLoose64Over(b *testing.B) { benchGlyph(b, 'A', true, 64, draw.Over) } func BenchmarkGlyphAlphaLoose64Src(b *testing.B) { benchGlyph(b, 'A', true, 64, draw.Src) } func BenchmarkGlyphAlphaLoose128Over(b *testing.B) { benchGlyph(b, 'A', true, 128, draw.Over) } func BenchmarkGlyphAlphaLoose128Src(b *testing.B) { benchGlyph(b, 'A', true, 128, draw.Src) } func BenchmarkGlyphAlphaLoose256Over(b *testing.B) { benchGlyph(b, 'A', true, 256, draw.Over) } func BenchmarkGlyphAlphaLoose256Src(b *testing.B) { benchGlyph(b, 'A', true, 256, draw.Src) } func BenchmarkGlyphAlphaLoose1024Over(b *testing.B) { benchGlyph(b, 'A', true, 1024, draw.Over) } func BenchmarkGlyphAlphaLoose1024Src(b *testing.B) { benchGlyph(b, 'A', true, 1024, draw.Src) } func BenchmarkGlyphRGBA16Over(b *testing.B) { benchGlyph(b, 'R', false, 16, draw.Over) } func BenchmarkGlyphRGBA16Src(b *testing.B) { benchGlyph(b, 'R', false, 16, draw.Src) } func BenchmarkGlyphRGBA32Over(b *testing.B) { benchGlyph(b, 'R', false, 32, draw.Over) } func BenchmarkGlyphRGBA32Src(b *testing.B) { benchGlyph(b, 'R', false, 32, draw.Src) } func BenchmarkGlyphRGBA64Over(b *testing.B) { benchGlyph(b, 'R', false, 64, draw.Over) } func BenchmarkGlyphRGBA64Src(b *testing.B) { benchGlyph(b, 'R', false, 64, draw.Src) } func BenchmarkGlyphRGBA128Over(b *testing.B) { benchGlyph(b, 'R', false, 128, draw.Over) } func BenchmarkGlyphRGBA128Src(b *testing.B) { benchGlyph(b, 'R', false, 128, draw.Src) } func BenchmarkGlyphRGBA256Over(b *testing.B) { benchGlyph(b, 'R', false, 256, draw.Over) } func BenchmarkGlyphRGBA256Src(b *testing.B) { benchGlyph(b, 'R', false, 256, draw.Src) } func BenchmarkGlyphRGBA1024Over(b *testing.B) { benchGlyph(b, 'R', false, 1024, draw.Over) } func BenchmarkGlyphRGBA1024Src(b *testing.B) { benchGlyph(b, 'R', false, 1024, draw.Src) } func BenchmarkGlyphNRGBA16Over(b *testing.B) { benchGlyph(b, 'N', false, 16, draw.Over) } func BenchmarkGlyphNRGBA16Src(b *testing.B) { benchGlyph(b, 'N', false, 16, draw.Src) } func BenchmarkGlyphNRGBA32Over(b *testing.B) { benchGlyph(b, 'N', false, 32, draw.Over) } func BenchmarkGlyphNRGBA32Src(b *testing.B) { benchGlyph(b, 'N', false, 32, draw.Src) } func BenchmarkGlyphNRGBA64Over(b *testing.B) { benchGlyph(b, 'N', false, 64, draw.Over) } func BenchmarkGlyphNRGBA64Src(b *testing.B) { benchGlyph(b, 'N', false, 64, draw.Src) } func BenchmarkGlyphNRGBA128Over(b *testing.B) { benchGlyph(b, 'N', false, 128, draw.Over) } func BenchmarkGlyphNRGBA128Src(b *testing.B) { benchGlyph(b, 'N', false, 128, draw.Src) } func BenchmarkGlyphNRGBA256Over(b *testing.B) { benchGlyph(b, 'N', false, 256, draw.Over) } func BenchmarkGlyphNRGBA256Src(b *testing.B) { benchGlyph(b, 'N', false, 256, draw.Src) } func BenchmarkGlyphNRGBA1024Over(b *testing.B) { benchGlyph(b, 'N', false, 1024, draw.Over) } func BenchmarkGlyphNRGBA1024Src(b *testing.B) { benchGlyph(b, 'N', false, 1024, draw.Src) }
true
195692299082626c1a1d95f8f360d2a889303009
Go
NikitaSmall/ghost
/server/client.go
UTF-8
1,732
2.6875
3
[ "MIT" ]
permissive
[ "MIT" ]
permissive
package server import ( "errors" "fmt" "net" "github.com/alexyer/ghost/ghost" "github.com/alexyer/ghost/protocol" "github.com/golang/protobuf/proto" ) type client struct { Conn net.Conn Server *Server MsgHeader []byte MsgBuffer []byte collection *ghost.Collection } func newClient(conn net.Conn, s *Server) *client { return &client{ Conn: conn, Server: s, MsgHeader: make([]byte, s.opt.GetMsgHeaderSize()), MsgBuffer: make([]byte, s.opt.GetMsgBufferSize()), collection: s.storage.GetCollection("main"), } } func (c *client) String() string { return fmt.Sprintf("Client<%s>", c.Conn.LocalAddr()) } func (c *client) Exec() (reply []byte, err error) { var ( cmd = new(protocol.Command) ) cmdLen, _ := ghost.ByteArrayToUint64(c.MsgHeader) if err := proto.Unmarshal(c.MsgBuffer[:cmdLen], cmd); err != nil { return nil, err } result, err := c.execCmd(cmd) return c.encodeReply(result, err) } func (c *client) execCmd(cmd *protocol.Command) (result []string, err error) { switch *cmd.CommandId { case protocol.CommandId_PING: result, err = c.Ping() case protocol.CommandId_SET: result, err = c.Set(cmd) case protocol.CommandId_GET: result, err = c.Get(cmd) case protocol.CommandId_DEL: result, err = c.Del(cmd) case protocol.CommandId_CGET: result, err = c.CGet(cmd) case protocol.CommandId_CADD: result, err = c.CAdd(cmd) default: err = errors.New("ghost: unknown command") } return result, err } func (c *client) encodeReply(values []string, err error) ([]byte, error) { var errMsg string if err != nil { errMsg = err.Error() } else { errMsg = "" } return proto.Marshal(&protocol.Reply{ Values: values, Error: &errMsg, }) }
true
f3f1f85479f6f8fd488ae092ab4cfbb8e2f9d1f8
Go
zeptotenshi/zeptoforge
/zforge/renderer/shader.go
UTF-8
770
2.828125
3
[ "Apache-2.0" ]
permissive
[ "Apache-2.0" ]
permissive
package renderer import ( "errors" "github.com/MeiKakuTenShi/zeptoforge/platform/opengl" ) type Shader interface { Bind() Unbind() Dispose() } type ZFshader struct { shader Shader } func NewShader(vSrc, fSrc string) (*ZFshader, error) { switch sAPI.api { case NoneRenderer: panic("RendererAPI::None - currently not supported") case OpenGL: r := new(opengl.OpenGLShader) r.Init(vSrc, fSrc) return &ZFshader{shader: r}, nil default: return nil, errors.New("could not create index buffer; unkown api") } } func (s ZFshader) Bind() { s.shader.Bind() } func (s ZFshader) Unbind() { s.shader.Unbind() } func (s ZFshader) GetShader() (Shader, error) { if s.shader != nil { return s.shader, nil } return nil, errors.New("shader is empty") }
true
44efe429e8864d7a61484084db8cd1b1638f63da
Go
Le-ChatNoir/M1_Golang
/TP1/tp1_2(hello_world).go
UTF-8
189
3.15625
3
[]
no_license
[]
no_license
package main import ( "fmt" ) func main() { var c chan bool c = make(chan bool) go func(){ fmt.Println("Hello") c <- true }() <- c fmt.Println("world") }
true
5e444d8214c0ba7ff9274daef3edc3e55ca19175
Go
dhqiao/go-core-tree
/lock/once.go
UTF-8
330
2.984375
3
[]
no_license
[]
no_license
package main // 官方案例 import ( "fmt" "sync" ) func main() { var once sync.Once //var num int onceBody := func() { fmt.Println("Only once") } done := make(chan bool) for i := 0; i < 10; i++ { go func() { once.Do(onceBody) // 多次调用 done <- true }() } for i := 0; i < 10; i++ { <-done } }
true
dde982481fbd13b6c24e88cc4f47b5ddc0b7fdd6
Go
Sharathnasa/concurrentGo
/BufferedChannel.go
UTF-8
533
3.625
4
[]
no_license
[]
no_license
package main import ( "fmt" "strings" ) func main() { phrase := "Hello World from sharath" words := strings.Split(phrase, " ") //channels ch := make(chan string, len(words)) for _, words := range words { ch <- words } // this is how we close the channel //close(ch) for i := 0; i < len(words); i++ { fmt.Print(<-ch + " ") } //once the channel gets exhausted, we need to close the channel, otherwise deadlock error can occur // ranging over the channels for msg := range ch { fmt.Println(msg + " ") } }
true
1e30eb8cef0d7f556b0a8e3e2a11f47f9987ad3f
Go
newit-tunb/peanut-app-inspector
/wda_handlers/static.go
UTF-8
315
2.546875
3
[ "MIT" ]
permissive
[ "MIT" ]
permissive
// jasonxu-2017/12/5 package wda_handlers import ( "net/http" ) type StaticHandler struct{} func NewStaticHandler() *StaticHandler { return &StaticHandler{} } func (h *StaticHandler) ServeHTTP(rw http.ResponseWriter, req *http.Request) { path := "./resources" + req.URL.Path http.ServeFile(rw, req, path) }
true
60d5d0944fa59e1e6c046ced6f31d3b95bdfeec5
Go
code-for-india/FSCK
/FSCK-server/models/note.go
UTF-8
699
2.765625
3
[]
no_license
[]
no_license
package model import ( "github.com/coopernurse/gorp" "time" ) type Note struct { Note_id int `db:"note_id"` Content string `db:"note"` Title string `db:"title"` Created int64 `db:"created"` Modified int64 `db:"modified"` } func (n *Note) Get(dbMap *gorp.DbMap, start, limit int) ([]Note, int, error) { notes := []Note{} _, err := dbMap.Select(&notes, "SELECT * FROM note ORDER BY modified DESC LIMIT ?,?", start, limit) if err != nil { return nil, 0, err } return notes, len(notes), nil } func (n *Note) Save(dbMap *gorp.DbMap) error { n.Created = time.Now().Unix() n.Modified = time.Now().Unix() err := dbMap.Insert(n) if err != nil { return err } return nil }
true
ad84e8f09e1b48d0584888d58b444e91c2e93bda
Go
OHopiak/go-load-balancer
/master/home.go
UTF-8
505
2.734375
3
[]
no_license
[]
no_license
package master import ( "github.com/labstack/echo/v4" "net/http" ) type ( BaseData struct { LoggedIn bool } ) func (m Master) homeHandler(c echo.Context) error { return c.Render(http.StatusOK, "index.html", m.GetBaseData(c)) } func (m Master) longProcessGetHandler(c echo.Context) error { return c.Render(http.StatusOK, "long_process.html", m.GetBaseData(c)) } func (m Master) GetBaseData(c echo.Context) BaseData { userRaw := c.Get("user") return BaseData{ LoggedIn: userRaw != nil, } }
true
87ba9d400f74737f432f64d8b876d218f3033386
Go
ligenhw/goshare
/orm/models_info_m.go
UTF-8
1,231
2.828125
3
[ "MIT" ]
permissive
[ "MIT" ]
permissive
package orm import ( "fmt" "os" "reflect" ) type modelInfo struct { fields *fields table string fullName string addrField reflect.Value } func newModelInfo(val reflect.Value) *modelInfo { mi := &modelInfo{} mi.addrField = val ind := reflect.Indirect(val) mi.fields = newFields() addModelFields(mi, ind, []int{}) return mi } func addModelFields(mi *modelInfo, ind reflect.Value, index []int) { var ( err error fi *fieldInfo sf reflect.StructField ) for i := 0; i < ind.NumField(); i++ { sf = ind.Type().Field(i) field := ind.Field(i) // add anonymous struct fields if sf.Anonymous { addModelFields(mi, field, append(index, i)) continue } fi, err = newFieldInfo(sf, field) if err == errSkipField { err = nil continue } else if err != nil { break } //record current field index fi.fieldIndex = append(fi.fieldIndex, index...) fi.fieldIndex = append(fi.fieldIndex, i) mi.fields.Add(fi) if fi.pk { if mi.fields.pk != nil { err = fmt.Errorf("one model must have one pk field only") break } else { mi.fields.pk = fi } } } if err != nil { fmt.Println(fmt.Errorf("field: %s.%s, %s", ind.Type(), sf.Name, err)) os.Exit(2) } }
true
dda1445084b901ba33a8b8c9eda9e7dd0f883680
Go
davidfeng88/goex
/gopl/ch1/ex1.4/ex1.4.go
UTF-8
1,086
3.59375
4
[]
no_license
[]
no_license
// Based on dup2, prints the count and text of lines that appear more than once in the input. // It reads from stdin or from a list of named files. // If there are duplicated lines, the filename is also included. package main import ( "bufio" "fmt" "os" ) func main() { counts := make(map[string]int) files := os.Args[1:] if len(files) == 0 { countLines(os.Stdin, counts) } else { for _, arg := range files { f, err := os.Open(arg) if err != nil { fmt.Fprintf(os.Stderr, "dup2: %v\n", err) continue } countLines(f, counts) f.Close() } } for line, n := range counts { if n > 1 { fmt.Printf("%d\t%s\n", n, line) } } } func countLines(f *os.File, counts map[string]int) { input := bufio.NewScanner(f) var fileNamePrinted bool for input.Scan() { line := input.Text() counts[line]++ if counts[line] > 1 && !fileNamePrinted { fmt.Printf("The file %s contains duplicated lines:\n", f.Name()) // if f is stdin, f.Name() returns "/dev/stdin" fileNamePrinted = true } } // NOTE: ignoring potential errors from input.Err() }
true
38db4d7e2c6efcc2a9815b799d783a53a15530a8
Go
Joibel/katafygio
/pkg/recorder/recorder_test.go
UTF-8
3,609
2.765625
3
[ "MIT" ]
permissive
[ "MIT" ]
permissive
package recorder import ( "testing" "time" "github.com/spf13/afero" "github.com/bpineau/katafygio/pkg/event" ) type mockLog struct{} func (m *mockLog) Infof(format string, args ...interface{}) {} func (m *mockLog) Errorf(format string, args ...interface{}) {} func newNotif(action event.Action, key string) *event.Notification { return &event.Notification{ Action: action, Key: key, Kind: "foo", Object: []byte("bar"), } } var ( logs = new(mockLog) fakedir = "/tmp/ktest" ) func TestRecorder(t *testing.T) { appFs = afero.NewMemMapFs() evt := event.New() rec := New(logs, evt, fakedir, 120, false).Start() evt.Send(newNotif(event.Upsert, "foo1")) evt.Send(newNotif(event.Upsert, "foo2")) evt.Send(newNotif(event.Delete, "foo1")) evt.Send(newNotif(event.Upsert, "foo2")) rec.Stop() // to flush ongoing fs operations exist, _ := afero.Exists(appFs, fakedir+"/foo-foo2.yaml") if !exist { t.Error("foo-foo2.yaml should exist; upsert event didn't propagate") } exist, _ = afero.Exists(appFs, fakedir+"/foo-foo1.yaml") if exist { t.Error("foo-foo1.yaml shouldn't exist, delete event didn't propagate") } rogue := fakedir + "/roguefile.yaml" _ = afero.WriteFile(appFs, rogue, []byte{42}, 0600) _ = afero.WriteFile(appFs, rogue+".txt", []byte{42}, 0600) rec.deleteObsoleteFiles() exist, _ = afero.Exists(appFs, rogue) if exist { t.Errorf("%s file should have been garbage collected", rogue) } exist, _ = afero.Exists(appFs, rogue+".txt") if !exist { t.Errorf("garbage collection should only touch .yaml files") } } func TestDryRunRecorder(t *testing.T) { appFs = afero.NewMemMapFs() dryevt := event.New() dryrec := New(logs, dryevt, fakedir, 60, true).Start() dryevt.Send(newNotif(event.Upsert, "foo3")) dryevt.Send(newNotif(event.Upsert, "foo4")) dryevt.Send(newNotif(event.Delete, "foo4")) dryrec.Stop() exist, _ := afero.Exists(appFs, fakedir+"/foo-foo3.yaml") if exist { t.Error("foo-foo3.yaml was created but we're in dry-run mode") } rogue := fakedir + "/roguefile.yaml" _ = afero.WriteFile(appFs, rogue, []byte{42}, 0600) dryrec.deleteObsoleteFiles() exist, _ = afero.Exists(appFs, rogue) if !exist { t.Errorf("garbage collection shouldn't remove files in dry-run mode") } } // testing behavior on fs errors (we shouldn't block the program) func TestFailingFSRecorder(t *testing.T) { appFs = afero.NewMemMapFs() evt := event.New() rec := New(logs, evt, fakedir, 60, false).Start() _ = afero.WriteFile(appFs, fakedir+"/foo.yaml", []byte{42}, 0600) // switching to failing (read-only) filesystem appFs = afero.NewReadOnlyFs(appFs) err := rec.save("foo", []byte("bar")) if err == nil { t.Error("save should return an error in case of failure") } // shouldn't panic in case of failures rec.deleteObsoleteFiles() // shouldn't block (the controllers event loop will retry anyway) ch := make(chan struct{}) go func() { evt.Send(newNotif(event.Upsert, "foo3")) evt.Send(newNotif(event.Upsert, "foo4")) ch <- struct{}{} }() select { case <-ch: case <-time.After(5 * time.Second): t.Error("recorder shouldn't block in case of fs failure") } // back to normal operations rec.Stop() // just to flush ongoing ops before switch filesystem appFs = afero.NewMemMapFs() rec.stopch = make(chan struct{}) rec.donech = make(chan struct{}) rec.Start() evt.Send(newNotif(event.Upsert, "foo2")) rec.Stop() // flush ongoing ops exist, _ := afero.Exists(appFs, fakedir+"/foo-foo2.yaml") if !exist { t.Error("foo-foo2.yaml should exist; recorder should recover from fs failures") } }
true
d67b002ed270a4b976f32926db33257b2c9ce0ba
Go
mistifyio/mistify
/providers/zfs/create.go
UTF-8
1,341
2.609375
3
[ "MIT" ]
permissive
[ "MIT" ]
permissive
package zfs import ( "errors" "net/url" "github.com/mistifyio/gozfs" "github.com/mistifyio/mistify/acomm" ) // CreateArgs are arguments for the Create handler. type CreateArgs struct { Name string `json:"name"` Type string `json:"type"` // gozfs.Dataset[Filesystem,Volume] Volsize uint64 `json:"volsize"` Properties map[string]interface{} `json:"properties"` } // Create will create a new filesystem or volume dataset. func (z *ZFS) Create(req *acomm.Request) (interface{}, *url.URL, error) { var args CreateArgs if err := req.UnmarshalArgs(&args); err != nil { return nil, nil, err } if args.Name == "" { return nil, nil, errors.New("missing arg: name") } if err := fixPropertyTypesFromJSON(args.Properties); err != nil { return nil, nil, err } var ds *gozfs.Dataset var err error switch args.Type { case gozfs.DatasetFilesystem: ds, err = gozfs.CreateFilesystem(args.Name, args.Properties) case gozfs.DatasetVolume: if args.Volsize <= 0 { err = errors.New("missing or invalid arg: volsize") break } ds, err = gozfs.CreateVolume(args.Name, args.Volsize, args.Properties) default: err = errors.New("missing or invalid arg: type") } if err != nil { return nil, nil, err } return &DatasetResult{newDataset(ds)}, nil, nil }
true
433510d2db4774d6f0143d17dd6c1368c80c771f
Go
ijoywan/eventbus
/bus.go
UTF-8
1,473
3.25
3
[]
no_license
[]
no_license
package eventbus import ( "errors" "sync" ) type EventBus struct { subNode map[string]*node rw sync.RWMutex } func NewEventBus() EventBus { return EventBus{ subNode: make(map[string]*node), rw: sync.RWMutex{}, } } func (b *EventBus) Subscribe(topic string, sub Sub) { b.rw.Lock() if n, ok := b.subNode[topic]; ok { b.rw.Unlock() n.rw.Lock() defer n.rw.Unlock() n.subs = append(n.subs, sub) return } defer b.rw.Unlock() n := NewNode() b.subNode[topic] = &n n.subs = append(n.subs, sub) } func (b *EventBus) UnSubscribe(topic string, sub Sub) { b.rw.Lock() if n, ok := b.subNode[topic]; ok && n.SubsLen() > 0 { b.rw.Unlock() b.subNode[topic].RemoveSub(sub) return } b.rw.Unlock() } func (b *EventBus) Publish(topic string, msg interface{}) error { b.rw.Lock() if n, ok := b.subNode[topic]; ok { b.rw.Unlock() n.rw.Lock() defer n.rw.Unlock() go func(subs []Sub, msg interface{}) { for _, sub := range subs { sub.receive(msg) } }(n.subs, msg) return nil } defer b.rw.Unlock() return errors.New("topic not exists") } func (b *EventBus) PubFunc(topic string) func(msg interface{}) { return func(msg interface{}) { b.Publish(topic, msg) } } func (b *EventBus) SubsLen(topic string) (int, error) { b.rw.Lock() if n, ok := b.subNode[topic]; ok { b.rw.Unlock() n.rw.RLock() defer n.rw.RUnlock() return n.SubsLen(), nil } defer b.rw.Unlock() return 0, errors.New("topic not exists") }
true
51798c79a0908c4f9aa40234b0af8b965602b62a
Go
wrp/examples
/go/src/sync.go
UTF-8
593
4.0625
4
[]
no_license
[]
no_license
// Trivial example using sync.Mutex package main import ( "fmt" "sync" ) type Counter struct { sync.Mutex n int64 } // This method is okay. func (c *Counter) incr(d int64) (r int64) { c.Lock() c.n += d r = c.n c.Unlock() return } // The method is bad. When it is called, // the Counter receiver value will be copied. func (c Counter) Value() (r int64) { c.Lock() r = c.n c.Unlock() return } func main() { var ( c Counter wg sync.WaitGroup ) for i := 0; i < 100; i += 1 { wg.Add(1) go func() { c.incr(1); wg.Done() }() } wg.Wait() fmt.Println( " c = ", c.n) }
true
fbea0abccb08a1040476f646e665dd2b5c6feff1
Go
tkrajina/gpxchart
/gpxcharts/utils.go
UTF-8
2,817
3.03125
3
[ "Apache-2.0" ]
permissive
[ "Apache-2.0" ]
permissive
package gpxcharts import ( "bytes" "encoding/xml" "errors" "fmt" "image" "image/png" "math" "strings" "github.com/llgcode/draw2d/draw2dsvg" ) func SVGToBytes(svg *draw2dsvg.Svg) ([]byte, error) { byts, err := xml.Marshal(svg) if err != nil { return nil, errors.New("error marhslling") } return byts, nil } func RGBAToBytes(m *image.RGBA) ([]byte, error) { var b bytes.Buffer if err := png.Encode(&b, m); err != nil { return nil, errors.New("error encoding png") } return b.Bytes(), nil } func FormatSpeed(meters_per_seconds float64, unit_type UnitType, round bool) string { if meters_per_seconds <= 0 { return "n/a" } if len(unit_type) == 0 { unit_type = UnitTypeMetric } var ( speed float64 unit string ) if unit_type == UnitTypeImperial { speed = meters_per_seconds * 60 * 60 / UnitTypeImperial.Units()["mi"] unit = "mph" } else if unit_type == UnitTypeNautical { speed = meters_per_seconds * 60 * 60 / 1852. unit = "kn" } else { speed = meters_per_seconds * 60 * 60 / 1000. unit = "kmh" } if round { return fmt.Sprintf("%d%s", int(math.Round(speed)), unit) } if speed < 10 { return fmt.Sprintf("%.2f%s", speed, unit) } return fmt.Sprintf("%.1f%s", speed, unit) } func FormatLength(lengthM float64, ut UnitType) string { if lengthM < 0 { return "n/a" } if len(ut) == 0 { ut = UnitTypeMetric } if ut == UnitTypeNautical { miles := ConvertFromM(lengthM, "NM") if miles < 10 { return FormatFloat(miles, 2) + "NM" } else { return FormatFloat(miles, 1) + "NM" } } else if ut == UnitTypeImperial { miles := ConvertFromM(lengthM, "mi") if miles < 10 { return FormatFloat(miles, 2) + "mi" } else { return FormatFloat(miles, 1) + "mi" } } else { // metric: if lengthM < 1000 { return FormatFloat(lengthM, 0) + "m" } if lengthM < 50000 { return FormatFloat(lengthM/1000, 2) + "km" } } return FormatFloat(lengthM/1000, 1) + "km" } // Convert from meters (or m/s if speed) into... func ConvertFromM(n float64, toUnit string) float64 { toUnit = strings.TrimSpace(strings.ToLower(toUnit)) if v, is := SPEED_UNITS[toUnit]; is { return n / v } if v, is := Units[toUnit]; is { return n / v } return 0 } func FormatFloat(f float64, digits int) string { format := fmt.Sprintf("%%.%df", digits) res := fmt.Sprintf(format, f) if strings.Contains(res, ".") { res = strings.TrimRight(res, "0") } return strings.TrimRight(res, ".") } func FormatAltitude(altitude_m float64, unit_type UnitType) string { if altitude_m < -20000 || altitude_m > 20000 { return "n/a" } if unit_type == UnitTypeMetric { return FormatFloat(altitude_m, 0) + "m" } return FormatFloat(ConvertFromM(altitude_m, "ft"), 0) + "ft" } func IsNanOrOnf(f float64) bool { return math.IsNaN(f) || math.IsInf(f, 0) }
true
1a78917cde253fc5221d82adbbe66acd82a022d6
Go
laashub-soa/harbor-scanner-microscanner
/pkg/http/api/v1/base_handler_test.go
UTF-8
583
2.71875
3
[ "Apache-2.0" ]
permissive
[ "Apache-2.0" ]
permissive
package v1 import ( "github.com/aquasecurity/harbor-scanner-microscanner/pkg/model/harbor" "github.com/stretchr/testify/assert" "net/http" "net/http/httptest" "testing" ) func TestBaseHandler_WriteJSONError(t *testing.T) { // given recorder := httptest.NewRecorder() handler := &BaseHandler{} // when handler.WriteJSONError(recorder, harbor.Error{ HTTPCode: http.StatusBadRequest, Message: "Invalid request", }) // then assert.Equal(t, http.StatusBadRequest, recorder.Code) assert.JSONEq(t, `{"error":{"message":"Invalid request"}}`, recorder.Body.String()) }
true
f3ec7133b4ee8b1dfe71144bcd44e62903aa8ad4
Go
hjacquir/go-training
/pointerReceptor.go
UTF-8
347
3.96875
4
[]
no_license
[]
no_license
package main import ( "fmt" "math" ) type Vertex struct { X, Y float64 } func (v Vertex) Abs() float64 { var operation float64 = v.X*v.X + v.Y*v.Y var res float64 = math.Sqrt(operation) return res } func (v Vertex) Scale(f float64) { v.X = v.X * f v.Y = v.Y * f } func main() { v := Vertex{3, 4} v.Scale(10) fmt.Println(v.Abs()) }
true
d3d9c0177ebf842538fb5457c336946dfb8d4c19
Go
niclabs/testResolvers
/resolvertests/resolvertests.go
UTF-8
3,508
2.796875
3
[]
no_license
[]
no_license
package resolvertests import ( "math" "math/bits" "fmt" "github.com/miekg/dns" "time" "strings" "math/rand" ) type Response struct { Ip string IsAlive int HasRecursion int HasDNSSEC int HasDNSSECfail int QidRatio int PortRatio int Txt string } const letterBytes = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" const ( letterIdxBits = 6 // 6 bits to represent a letter index letterIdxMask = 1<<letterIdxBits - 1 // All 1-bits, as many as letterIdxBits letterIdxMax = 63 / letterIdxBits // # of letter indices fitting in 63 bits ) func randString(n int) string { var src = rand.NewSource(time.Now().UnixNano()) b := make([]byte, n) // A src.Int63() generates 63 random bits, enough for letterIdxMax characters! for i, cache, remain := n-1, src.Int63(), letterIdxMax; i >= 0; { if remain == 0 { cache, remain = src.Int63(), letterIdxMax } if idx := int(cache & letterIdxMask); idx < len(letterBytes) { b[i] = letterBytes[idx] i-- } cache >>= letterIdxBits remain-- } return string(b) } // 1 is random func testRandomness(shorts []uint16) int { var pos,neg,n int = 0,0,0 for _, ui := range shorts { pos += bits.OnesCount16(ui) neg += 16 - bits.OnesCount16(ui) n += 16 } s := math.Abs(float64(pos - neg)) / math.Sqrt (float64(n)) if math.Erfc(s) < 0.01 { return 0 } return 1 } func checkRandomness(ip string) (int,int) { var ids []uint16 for i:= 0; i < 10; i++ { line := "bip"+randString(16)+".niclabs.cl" c := new(dns.Client) m := new(dns.Msg) m.SetQuestion(dns.Fqdn(line),dns.TypeA) msg ,_ , err := c.Exchange(m , ip + ":53") if err == nil { ids = append(ids,msg.MsgHdr.Id) } } return testRandomness(ids),0 } func checkAuthority(ip string) string { b := strings.Split(ip , ".") arp := b[3] + "." + b[2] + "." + b[1] + "." + b[0] + ".in-addr.arpa" c := new(dns.Client) m := new(dns.Msg) m.SetQuestion(dns.Fqdn(arp),dns.TypePTR) msg ,_ ,err := c.Exchange(m,ip + ":53") if err != nil { return "" } if (len(msg.Answer) < 1 || len(msg.Ns) < 1) { return "" } return fmt.Sprintf("%s",msg.Ns) } func checkDNSSECok (ip string) int { line := "sigok.verteiltesysteme.net" c := new(dns.Client) m := new(dns.Msg) m.SetQuestion(dns.Fqdn(line),dns.TypeA) m.SetEdns0(4096,true) msg ,_ ,err := c.Exchange(m, ip +":53") if err != nil { return -1 // other error, typically i/o timeout } return msg.MsgHdr.Rcode } func checkDNSSECnook (ip string) int { line := "sigfail.verteiltesysteme.net" c := new(dns.Client) m := new(dns.Msg) m.SetQuestion(dns.Fqdn(line),dns.TypeA) m.SetEdns0(4096,true) msg ,_ ,err := c.Exchange(m, ip + ":53") if err != nil { return -1 // other error } return msg.MsgHdr.Rcode } func CheckDNS(id int, ips <- chan string, results chan <- Response) { line := "www.google.com" for ip := range ips { ip := strings.TrimSpace(ip) c := new(dns.Client) m := new(dns.Msg) r := Response{Ip : ip, IsAlive : 1} m.SetQuestion(dns.Fqdn(line), dns.TypeA) m.RecursionDesired = true m.CheckingDisabled = false msg ,_ ,err := c.Exchange(m, ip + ":53") if err != nil { r.IsAlive = 0; } else { if msg != nil { if msg.Rcode != dns.RcodeRefused && msg.RecursionAvailable { r.HasRecursion = 1 r.HasDNSSEC = checkDNSSECok(ip); r.HasDNSSECfail = checkDNSSECnook(ip); r.Txt = checkAuthority(ip); // r.qidRatio,_ = checkRandomness(ip); } } } results <- r } }
true
2d7f6908bde4ccf2a99e51b8625cbb825a2fac09
Go
meenakshisl/go
/gobyexample/for.go
UTF-8
372
3.53125
4
[]
no_license
[]
no_license
package main import "fmt" func main() { i:=1 for i<=5 { //for loop with one condition; similiar to while fmt.Println(i) i=i+3 } for { //endless loop == while(True) fmt.Println("Endless loop bout to break") break } for j:=7;j<=10;j++ { //normal while loop fmt.Println(j) } for n:=0;n<=9;n=n+2 { if(n==3) { continue } fmt.Println(n) } }
true
5d22473369b547e3d3899a73c900f6c0ea7da63b
Go
chenxuey/mango
/app/users/user.go
UTF-8
368
2.5625
3
[]
no_license
[]
no_license
package users import ( "mango/app" "mango/config" "fmt" ) type UserHttp struct { app.AppBase } func NewUserHttp(logger *config.Logger) *UserHttp { appHttp := UserHttp{} appHttp.Logger = logger return &appHttp } func (userHttp *UserHttp) Get() { fmt.Println("你请求了 user GET 方法", userHttp.Info) userHttp.Println("你请求了 user GET 方法") }
true
a00f7b584f09167b1026f1be560d548c7ba2677d
Go
farbanas/dependency-manager
/main.go
UTF-8
2,703
2.65625
3
[]
no_license
[]
no_license
package main import ( "flag" "fmt" "os" "strings" ) var username string var password string var nexusUrl string var configPath string func init() { username = os.Getenv("USERNAME") password = os.Getenv("PASSWORD") nexusUrl = os.Getenv("NEXUS_URL") configPath = os.Getenv("CONFIG_PATH") flag.StringVar(&username, "username", username, "Username for the Nexus repository") flag.StringVar(&password, "password", password, "Password for the Nexus repository") flag.StringVar(&nexusUrl, "url", nexusUrl, "URL for the Nexus repository") flag.StringVar(&configPath, "config-path", configPath, "Path to config.yaml") flag.Parse() } func parseVars() { if username == "" { panic("Missing username for nexus repo!") } if password == "" { panic("Missing password for nexus repo!") } if nexusUrl == "" { panic("Missing nexus url!") } } func main() { parseVars() config := ReadConfigFile("config.yaml") for i, repoConfig := range config.Config { if i != 0 { fmt.Println() } fmt.Println(strings.Title(repoConfig.RepositoryType), "packages that need update:") strlen := len(repoConfig.RepositoryType) + len("packages that need update:") fmt.Println(strings.Repeat("=", strlen+1)) for _, reqFileDef := range repoConfig.RequirementFiles { var repository Requirements if repoConfig.RepositoryType == "helm" { repository = HelmRequirements{reqFileDef.Path, nil, HelmYaml{}} } else if repoConfig.RepositoryType == "pip" { repository = PipRequirements{reqFileDef.Path, nil } } else if repoConfig.RepositoryType == "pom" { repository = PomRequirements{reqFileDef.Path, nil, PomXML{}} } if repository != nil { process(reqFileDef, repository) } else { fmt.Println("No packages need update!") } } } } func process(reqDefinition RequirementsDefinition, requirements Requirements) { toUpdate := make(map[string]string) reader, f := requirements.OpenRequirementsFile() defer f.Close() requirements = requirements.ReadCurrentVersion(reader) libraryVersions := requirements.GetLibraryVersions() for _, req := range libraryVersions { url := fmt.Sprintf("https://%s:%s@%s/service/rest/v1/search?repository=%s&name=%s&sort=version", username, password, nexusUrl, reqDefinition.Repository, req.Library) assets := NexusGetAssets(url) versions := NexusExtractVersions(assets) if len(versions) > 0 { if versions[0] != req.Version { toUpdate[req.Library] = versions[0] fmt.Printf("%-25s\t%-7s -> %7s\n", req.Library, req.Version, versions[0]) } } else { fmt.Println("Could not get version for library:", req.Library) } } fmt.Println("Getting done, starting update") requirements.UpdateVersion(toUpdate) }
true
55e60087274679310616b74a839a2da9cba939ba
Go
lab47/aperture
/pkg/metadata/repo.go
UTF-8
650
2.734375
3
[ "BSD-3-Clause" ]
permissive
[ "BSD-3-Clause" ]
permissive
package metadata import ( "net/url" "path" "strings" ) type RepoConfig struct { Id string `json:"id"` CarURLS []string `json:"car_urls"` RegistryPath string `json:"registry_path"` OCIRoot string `json:"oci"` } func (r *RepoConfig) CalculateCarURLs(name string) []string { var expanded []string for _, n := range r.CarURLS { if strings.Contains(n, "$name") { expanded = append(expanded, strings.Replace(n, "$name", name, -1)) } else { u, err := url.Parse(n) if err != nil { continue } u.Path = path.Join(u.Path, name) expanded = append(expanded, u.String()) } } return expanded }
true
a29cc61618cc8e9a3b4ce23271701d30e19f12c2
Go
igoratron/mechanodoro
/src/github.com/igoratron/mechanodoro/arduino/arduino.go
UTF-8
1,290
3.1875
3
[]
no_license
[]
no_license
package arduino import "log" import "time" import "github.com/tarm/serial" var FLAG_RAISED = byte(255) var FLAG_LOWERED = byte(128) type Arduino struct { Name string connection *serial.Port } func (a *Arduino) Start() { c := &serial.Config{Name: a.Name, Baud: 115200} var err error a.connection, err = serial.OpenPort(c) if err != nil { log.Fatal("Can't talk to the Arduino. ", err) } waitForArduino(a.connection) } func (a *Arduino) Stop() { a.connection.Close() } func (a *Arduino) send(b byte) { _, err := a.connection.Write([]byte{b}) if err != nil { log.Fatal("Failed to send to Arduino", err) } } func (a *Arduino) RaiseFlag() { a.send(FLAG_RAISED) } func (a *Arduino) LowerFlag() { a.send(FLAG_LOWERED) } func waitForArduino(port *serial.Port) { var isConnectionEstablished bool log.Printf("Establishing connection with the Arduino") defer log.Println("Connected to Arduino") go func() { for !isConnectionEstablished { _, err := port.Write([]byte{0}) if err != nil { log.Println(err) } time.Sleep(time.Until(time.Now().Add(200 * time.Millisecond))) } }() buf := make([]byte, 32) _, err := port.Read(buf) if err != nil { log.Fatal(err) } isConnectionEstablished = true }
true
14096ce0f5c3fe4085a298a02f31eb288dd50ce1
Go
redsnapper2006/leetcode-cn
/T/5830-three-divisors/main.go
UTF-8
302
2.859375
3
[]
no_license
[]
no_license
package main import ( "fmt" "math" ) func isThree(n int) bool { if n <= 2 { return false } for i := 2; i < int(math.Sqrt(float64(n))); i++ { if n%i == 0 { return false } } d := int(math.Sqrt(float64(n))) if d*d == n { return true } return false } func main() { fmt.Println() }
true
ac6ddf6b63dab21598b0d05d9bed00a349f2162e
Go
cnymw/learnGo
/src/algorithm/sort/quicksort/quicksort.go
UTF-8
714
3.78125
4
[]
no_license
[]
no_license
package quicksort type QuickSort struct { Value []int } func (q *QuickSort) Sort() ([]int, error) { if len(q.Value) <= 1 { return nil, nil } quickSort(q.Value, 0, len(q.Value)-1) return q.Value, nil } func quickSort(s []int, left, right int) { temp, index := s[left], left i, j := left, right for j >= i { // 比temp大的放在右边 for j >= index && s[j] >= temp { j-- } if j >= index { s[index] = s[j] index = j } // 比temp小的放在左边 for index >= i && s[i] <= temp { i++ } if index >= i { s[index] = s[i] index = i } } s[index] = temp if index-left > 1 { quickSort(s, left, index-1) } if right-index > 1 { quickSort(s, index+1, right) } }
true
d4410b972fc8b2f763348e4c1e164b26879d79b7
Go
airabinovich/memequotes_front
/api/rest/health_test.go
UTF-8
740
2.9375
3
[ "MIT" ]
permissive
[ "MIT" ]
permissive
package rest import ( "net/http" "net/http/httptest" "testing" "github.com/gin-gonic/gin" "github.com/stretchr/testify/assert" ) func TestHealthShouldReturn200Ok(t *testing.T) { t.Log("Health should return 200 OK when service is healthy") w := httptest.NewRecorder() req := httptest.NewRequest(http.MethodGet, "/memequotes/health", nil) r := testRouter() r.GET("memequotes/health", Health) r.ServeHTTP(w, req) assert.Equal(t, 200, w.Code) } // TODO: this could be improved, here we are creating a new router. We cannot use router.CreateRouter() because it generates cyclic references func testRouter() *gin.Engine { gin.SetMode(gin.TestMode) router := gin.Default() router.HandleMethodNotAllowed = true return router }
true
fcfcf17fc9e0c4695f70bad06699cea3475b7344
Go
aw33598/Mastering-Golang
/src/10.DataTypes/UnsignedInteger/uint32/uint32.go
UTF-8
262
3.09375
3
[ "MIT" ]
permissive
[ "MIT" ]
permissive
package main import "fmt" func main() { var maxUint32 uint32 = 4294967295 fmt.Println(maxUint32) // Output : 4294967295 /* var anotherMaxUint32 uint32 = 4294967295 + 1 fmt.Println(anotherMaxUint32) */ // Output : constant 4294967296 overflows uint32 }
true
510c0e617648e37a30400712ef49746c1dddc091
Go
mky-cyber/go-training
/control-flow/ex10.go
UTF-8
207
2.546875
3
[]
no_license
[]
no_license
package main import ( "fmt" ) func ex10() { fmt.Println("Exercise 10") fmt.Println(true && true) fmt.Println(true && false) fmt.Println(true || true) fmt.Println(true || false) fmt.Println(!true) }
true
85b3a2d2d9695e6cfee68a524433ab99b89fb8b0
Go
callerobertsson/gotools
/gohuman/human/human.go
UTF-8
1,685
3.828125
4
[]
no_license
[]
no_license
// Package human provides functions for converting a number to human readable form package human import ( "fmt" "math" "strconv" "strings" ) // Bytes transforms a number into a string with 1024 as base. // Arguments: n - number to transform, decimals - number of decimals to show, // long - if true, show full names, otherwise show abbreviated. func Bytes(n int64, decimals int, long bool) string { padding := " " levels := []string{ "B", "KB", "MB", "GB", "TB", "PB", "EB", /* "ZB", "YB" will overflow int64 */ } if long { levels = []string{ "bytes", "kilobyte", "megabyte", "gigabyte", "terabyte", "petabyte", "exabyte", } } return human(n, levels, 1024, decimals, padding) } // Kilos transforms a number into a string with 1000 as base // Arguments: n - number to transform, decimals - number of decimals to show, // long - if true, show full names, otherwise show abbreviated. func Kilos(n int64, decimals int, long bool) string { padding := " " levels := []string{ "", "k", "M", "G", "T", "P", "E", /* "Z", "Y" will overflow int64 */ } if long { levels = []string{ "s", "kilo", "mega", "giga", "tera", "peta", "exa", } } return human(n, levels, 1000, decimals, padding) } // human - generic number to string conversion function func human(n int64, levels []string, base int, decimals int, padding string) string { format := fmt.Sprintf("%%.%df%v%%v", decimals, padding) res := strconv.FormatInt(n, 10) for i, level := range levels { nom := float64(n) den := math.Pow(float64(base), float64(i)) val := nom / den if val < float64(base) { res = fmt.Sprintf(format, val, level) break } } return strings.TrimSpace(res) }
true
2558776f4ea21c535e2d668ff3292da2c5f44856
Go
kschiess/hens_and_eggs
/go/gotour/slices.go
UTF-8
416
3.15625
3
[]
no_license
[]
no_license
package main import "fmt" func main() { p := []int{1,2,3,4,5,6} fmt.Println("p ==", p) fmt.Println("p[1:4] ==", p[1:4]) // missing low index implies 0 fmt.Println("p[:3] ==", p[:3]) // missing high index implies len(s) fmt.Println("p[4:] ==", p[4:]) // This panics: nice stack traces! // for i:=0; i<len(p)+1; i++ { // fmt.Println(p[i]) // } v := new([10]int) fmt.Println(v) }
true
77a13b7173c827eaffda61af5d14e53a2884480b
Go
dhseah/GoPasarSG
/pkg/search/search.go
UTF-8
1,401
3.265625
3
[]
no_license
[]
no_license
package search import ( "ProjectGoLive/pkg/models" "sort" "sync" ) // Search looks through the IndexSlice for matches for // every search term provided by the user. If a match is // found, the ProductID is inserted into the results map // that maps ProductID to relevance score. func (idx IndexSlice) Search(text string) ([]int, map[int]int) { var countMap = make(map[int]int) var wg sync.WaitGroup for _, token := range analyze(text) { wg.Add(3) go func() { defer wg.Done() if ids, ok := idx[0][token]; ok { for _, v := range ids { countMap[v] += 2 } } }() go func() { defer wg.Done() if ids, ok := idx[1][token]; ok { for _, v := range ids { countMap[v]++ } } }() go func() { defer wg.Done() if ids, ok := idx[2][token]; ok { for _, v := range ids { countMap[v] += 4 } } }() wg.Wait() } unsorted := []int{} for k := range countMap { unsorted = append(unsorted, k) } return unsorted, countMap } // RankedProduct // RankedProduct is called to prepare a list of products // for writing to the http response in sorted order. func RankedProducts(input []*models.Product, countMap map[int]int) []*models.Product { for i := 0; i < len(input); i++ { input[i].Score = countMap[input[i].ProductID] } sort.SliceStable(input, func(i, j int) bool { return input[i].Score > input[j].Score }) return input }
true