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
6316aa10ab07ff7262de8782c93f775d74ca60ac
Go
shockerli/spiker
/ast.go
UTF-8
247
2.84375
3
[ "MIT" ]
permissive
[ "MIT" ]
permissive
package spiker // AstNode AST node interface type AstNode interface { Format() string Raw() *Token } // Ast syntax parsing infrastructure type Ast struct { raw *Token } // Raw return the token func (ast Ast) Raw() *Token { return ast.raw }
true
853a85f0e2186d982b2cc9f0e34bcf57f29097a5
Go
gebv/gong
/src/widgets/router.go
UTF-8
4,069
2.71875
3
[ "MIT" ]
permissive
[ "MIT" ]
permissive
package widgets import "strings" import "net/url" import "github.com/golang/glog" import "fmt" type matcher interface { Match(*Request, *RouteMatch) bool } type Request struct { URL *url.URL Method string } func NewHandlerFromString(str string) Handler { hConf := strings.Fields(str) if len(hConf) != 2 { glog.Warningf("not valid handler, route=%v", hConf) return Handler{} } return Handler{hConf[0], hConf[1]} } func NewHandler(bucket, file string) Handler { return Handler{bucket, file} } type Handler struct { Bucket string File string } func (h Handler) IsEmpty() bool { return len(h.Bucket) == 0 && len(h.File) == 0 } type RouteMatch struct { Route *Route Handler Handler Vars map[string]string } type Route struct { handler Handler // // List of matchers. matchers []matcher // // Manager for the variables from host and path. regexp *routeRegexpGroup name string strictSlash bool err error } func (r *Route) Match(req *Request, match *RouteMatch) bool { // Match everything. for _, m := range r.matchers { if matched := m.Match(req, match); !matched { return false } } if match.Route == nil { match.Route = r } if match.Handler.IsEmpty() { match.Handler = r.handler } if match.Vars == nil { match.Vars = make(map[string]string) } // Set variables. if r.regexp != nil { r.regexp.setMatch(req, match, r) } return true } func (r *Route) Path(tpl string) *Route { r.addRegexpMatcher(tpl, false, false, false) return r } // methodMatcher matches the request against HTTP methods. type methodMatcher []string func (m methodMatcher) Match(r *Request, match *RouteMatch) bool { return matchInArray(m, r.Method) } // Methods adds a matcher for HTTP methods. // It accepts a sequence of one or more methods to be matched, e.g.: // "GET", "POST", "PUT". func (r *Route) Methods(methods ...string) *Route { for k, v := range methods { methods[k] = strings.ToUpper(v) } return r.addMatcher(methodMatcher(methods)) } func (r *Route) Handler(v Handler) *Route { r.handler = v return r } // addMatcher adds a matcher to the route. func (r *Route) addMatcher(m matcher) *Route { if r.err == nil { r.matchers = append(r.matchers, m) } return r } // addRegexpMatcher adds a host or path matcher and builder to a route. func (r *Route) addRegexpMatcher(tpl string, matchHost, matchPrefix, matchQuery bool) error { if r.err != nil { return r.err } r.regexp = new(routeRegexpGroup) // r.regexp = r.getRegexpGroup() if !matchHost && !matchQuery { if len(tpl) == 0 || tpl[0] != '/' { return fmt.Errorf("mux: path must start with a slash, got %q", tpl) } if r.regexp.path != nil { tpl = strings.TrimRight(r.regexp.path.template, "/") + tpl } } rr, err := newRouteRegexp(tpl, matchHost, matchPrefix, matchQuery, r.strictSlash) if err != nil { return err } for _, q := range r.regexp.queries { if err = uniqueVars(rr.varsN, q.varsN); err != nil { return err } } if matchHost { if r.regexp.path != nil { if err = uniqueVars(rr.varsN, r.regexp.path.varsN); err != nil { return err } } r.regexp.host = rr } else { if r.regexp.host != nil { if err = uniqueVars(rr.varsN, r.regexp.host.varsN); err != nil { return err } } if matchQuery { r.regexp.queries = append(r.regexp.queries, rr) } else { r.regexp.path = rr } } r.addMatcher(rr) return nil } type Router struct { NotFoundHandler Handler routes []*Route namedRoutes map[string]*Route } func NewRouter() *Router { return &Router{namedRoutes: make(map[string]*Route)} } func (r *Router) NewRoute() *Route { route := &Route{} r.routes = append(r.routes, route) return route } func (r *Router) Handle(path string, h Handler) *Route { return r.NewRoute().Path(path).Handler(h) } func (r *Router) Match(req *Request, match *RouteMatch) bool { for _, route := range r.routes { if route.Match(req, match) { return true } } if !r.NotFoundHandler.IsEmpty() { match.Handler = r.NotFoundHandler return true } return false }
true
774a244f62c691d4e3d933699aad816722ff2f5f
Go
willshang/go-leetcode
/source/lcci/面试题16.07.最大数值/2-内置函数.go
UTF-8
167
2.921875
3
[]
no_license
[]
no_license
package main import ( "fmt" "math" ) func main() { fmt.Println(maximum(1, 2)) } func maximum(a int, b int) int { return int(math.Max(float64(a), float64(b))) }
true
85e532fadc5b254fd69b2c41318e389bc0676d37
Go
rqg0717/LeetCode
/77. Combinations/main.go
UTF-8
581
3.453125
3
[]
no_license
[]
no_license
package main import "fmt" func combine(n int, k int) [][]int { results := [][]int{} backtracking(1, k, n, []int{}, &results) return results } func backtracking(start, k, n int, subset []int, results *[][]int) { if len(subset) == k { combination := make([]int, k) copy(combination, subset) *results = append(*results, combination) return // results } for i := start; i <= n; i++ { subset = append(subset, i) backtracking(i+1, k, n, subset, results) subset = subset[:len(subset)-1] } } func main() { n := 4 k := 2 fmt.Println("Output: ", combine(n, k)) }
true
876a88e96d6aa5a06ce7bd3a23a41d9d32bbc945
Go
kushao1267/go-tools
/funcs/regxp.go
UTF-8
497
3.171875
3
[ "MIT" ]
permissive
[ "MIT" ]
permissive
package funcs import "regexp" // MatchOneOf match one of the patterns func MatchOneOf(text string, patterns ...string) []string { var ( re *regexp.Regexp value []string ) for _, pattern := range patterns { // (?flags): set flags within current group; non-capturing // s: let . match \n (default false) // https://github.com/google/re2/wiki/Syntax re = regexp.MustCompile(pattern) value = re.FindStringSubmatch(text) if len(value) > 0 { return value } } return nil }
true
c95d7a688d5f84339dd4ebd98a39a2772ae2e2ee
Go
RuNpiXelruN/secrets_cli
/cmd/cobra/get.go
UTF-8
833
2.578125
3
[]
no_license
[]
no_license
package cobra import ( "fmt" secret "github.com/RuNpiXelruN/secrets-cli-app" "github.com/spf13/cobra" ) var getCmd = &cobra.Command{ Use: "get", Short: "Decrypts and returns a secret from your secret storage", Run: func(cmd *cobra.Command, args []string) { if len(encodingKey) == 0 { fmt.Print("\nYou need to pass your secure encoding key.\neg,\n'secrets get -k <your enc key> some_api_key'\n\n") return } v := secret.NewFileVault(encodingKey, secretsPath()) key := args[0] val, err := v.Get(key) if err != nil { fmt.Printf("Something went wrong retrieving your secret - %v\n\nPlease ensure you passed the correct encryption key.\neg,\n'secrets get -k <your enc key> some_api_key'\n\n", err) return } fmt.Printf("\n\t%v: %v\n\n", key, val) }, } func init() { RootCmd.AddCommand(getCmd) }
true
5fae3919a91a5f4085a481383bfe4ffad047d754
Go
THE108/requestcounter
/utils/log/devnull.go
UTF-8
1,603
2.9375
3
[ "MIT" ]
permissive
[ "MIT" ]
permissive
package log type devNullLogger struct{} func NewDevNullLogger() ILogger { return &devNullLogger{} } // Debug calls l.Output to print to the logger. // Arguments are handled in the manner of fmt.Print. func (l *devNullLogger) Debug(v ...interface{}) { } // Debugf calls l.Output to print to the logger. // Arguments are handled in the manner of fmt.Printf. func (l *devNullLogger) Debugf(format string, v ...interface{}) { } // Info calls l.Output to print to the logger. // Arguments are handled in the manner of fmt.Print. func (l *devNullLogger) Info(v ...interface{}) { } // Infof calls l.Output to print to the logger. // Arguments are handled in the manner of fmt.Printf. func (l *devNullLogger) Infof(format string, v ...interface{}) { } // Warn calls l.Output to print to the logger. // Arguments are handled in the manner of fmt.Print. func (l *devNullLogger) Warning(v ...interface{}) { } // Warnf calls l.Output to print to the logger. // Arguments are handled in the manner of fmt.Printf. func (l *devNullLogger) Warningf(format string, v ...interface{}) { } // Error calls l.Output to print to the logger. // Arguments are handled in the manner of fmt.Print. func (l *devNullLogger) Error(v ...interface{}) { } // Errorf calls l.Output to print to the logger. // Arguments are handled in the manner of fmt.Printf. func (l *devNullLogger) Errorf(format string, v ...interface{}) { } // ErrorIfNotNil calls l.Output to print to the logger if err is not nil. // Arguments are handled in the manner of fmt.Printf. func (l *devNullLogger) ErrorIfNotNil(message string, err error) { }
true
0610676f7113e24fc49e744cdca0a58600460bc5
Go
haohanyuzmx/second
/后端暑假培训第二次课代码/service/sec_kill.go
UTF-8
2,910
3.15625
3
[]
no_license
[]
no_license
package service import ( "log" "summerCourse/model" "sync" "time" ) type User struct { UserId string GoodsId uint } var OrderChan = make(chan User, 1024) var ItemMap = make(map[uint]*Item) type Item struct { ID uint // 商品id Name string // 名字 Total int // 商品总量 Left int // 商品剩余数量 IsSoldOut bool // 是否售罄 leftCh chan int sellCh chan int done chan struct{} Lock sync.Mutex } // TODO 写一个定时任务,每天定时从数据库加载数据到Map func InitMap() { t := time.NewTimer(time.Hour * 24) for { <-t.C for _, i2 := range ItemMap { some := model.Goods{ Name: i2.Name, Num: i2.Left, } if err:=some.UpdateGoods();err!=nil{ log.Println(err) return } } some := SelectGoods() for _, i2 := range some { item := &Item{ ID: i2.ID, Name: i2.Name, Total: i2.Num, Left: i2.Num, IsSoldOut: false, leftCh: make(chan int), sellCh: make(chan int), } ItemMap[item.ID] = item } t.Reset(time.Hour * 24) } } func getItem(itemId uint) *Item { return ItemMap[itemId] } func order() { user := <-OrderChan item := getItem(user.GoodsId) item.SecKilling(user.UserId) } func (item *Item) SecKilling(userId string) { item.Lock.Lock() defer item.Lock.Unlock() // 等价 // var lock = make(chan struct{}, 1} // lock <- struct{}{} // defer func() { // <- lock // } if item.IsSoldOut { return } item.BuyGoods(1) MakeOrder(userId, item.ID, 1) } // 定时下架 func (item *Item) OffShelve() { beginTime := time.Now() // 获取第二天时间 //nextTime := beginTime.Add(time.Hour * 24) // 计算次日零点,即商品下架的时间 //offShelveTime := time.Date(nextTime.Year(), nextTime.Month(), nextTime.Day(), 0, 0, 0, 0, nextTime.Location()) offShelveTime := beginTime.Add(time.Second * 5) timer := time.NewTimer(offShelveTime.Sub(beginTime)) <-timer.C delete(ItemMap, item.ID) close(item.done) } // 出售商品 func (item *Item) SalesGoods() { for { select { case num := <-item.sellCh: if item.Left -= num; item.Left <= 0 { item.IsSoldOut = true } case item.leftCh <- item.Left: case <-item.Done(): log.Println("我自闭了") return } } } //当关闭通道后可以读出信息满足case func (item *Item) Done() <-chan struct{} { if item.done == nil { item.done = make(chan struct{}) } d := item.done return d } //监控请求 func (item *Item) Monitor() { go item.SalesGoods() } // 获取剩余库存 func (item *Item) GetLeft() int { var left int left = <-item.leftCh return left } // 购买商品 func (item *Item) BuyGoods(num int) { item.sellCh <- num } //开启服务 func InitService() { go InitMap() for _, item := range ItemMap { item.Monitor() go item.OffShelve() } for i := 0; i < 10; i++ { go order() } }
true
544ebe73a8f42cafaea9601b974adda2434fc37b
Go
ProjectBorealis/go7z
/reader_test.go
UTF-8
1,269
2.75
3
[ "MIT" ]
permissive
[ "MIT" ]
permissive
package go7z import ( "io" "io/ioutil" "testing" "github.com/saracen/go7z-fixtures" ) func TestOpenReader(t *testing.T) { fs, closeall := fixtures.Fixtures([]string{"empty", "delta"}, nil) defer closeall.Close() for _, f := range fs { sz, err := OpenReader(f.Name) if err == io.EOF { if f.Archive == "empty" { continue } t.Fatal(err) } if err != nil { t.Fatal(err) } for { _, err := sz.Next() if err == io.EOF { break } if err != nil { t.Fatal(err) } if _, err = io.Copy(ioutil.Discard, sz); err != nil { t.Fatal(err) } } if err := sz.Close(); err != nil { t.Fatal(err) } } } func TestReader(t *testing.T) { fs, closeall := fixtures.Fixtures([]string{"executable", "random"}, []string{"ppmd", "ppc", "arm"}) defer closeall.Close() for _, f := range fs { sz, err := NewReader(f, f.Size) if err != nil { t.Fatalf("error reading %v: %v\n", f.Archive, err) } count := 0 for { _, err := sz.Next() if err == io.EOF { break } if err != nil { panic(err) } if _, err = io.Copy(ioutil.Discard, sz); err != nil { t.Fatal(err) } count++ } if count != f.Entries { t.Fatalf("expected %v entries, got %v\n", f.Entries, count) } } }
true
b69c53995b5fda357b958d52b1925ee94a157d5d
Go
aprasolova/neo-go
/pkg/internal/keytestcases/testcases.go
UTF-8
1,385
2.65625
3
[ "LicenseRef-scancode-free-unknown", "MIT" ]
permissive
[ "LicenseRef-scancode-free-unknown", "MIT" ]
permissive
package keytestcases // Ktype represents key testcase values (different encodings of the key). type Ktype struct { Address, PrivateKey, PublicKey, Wif, Passphrase, EncryptedWif string Invalid bool } // Arr contains a set of known keys in Ktype format. var Arr = []Ktype{ { Address: "NNWAo5vdVJz1oyCuNiaTBA3amBHnWCF4Yk", PrivateKey: "7d128a6d096f0c14c3a25a2b0c41cf79661bfcb4a8cc95aaaea28bde4d732344", PublicKey: "02028a99826edc0c97d18e22b6932373d908d323aa7f92656a77ec26e8861699ef", Wif: "L1QqQJnpBwbsPGAuutuzPTac8piqvbR1HRjrY5qHup48TBCBFe4g", Passphrase: "city of zion", EncryptedWif: "6PYSeMMbJtfMRD81eHzriwrRKquu2dgLNurYcAbmJa7YqAiThgA2vGQu5o", }, { Address: "NiwvMyWYeNghLG8tDyKkWwuZV3wS8CPrrV", PrivateKey: "9ab7e154840daca3a2efadaf0df93cd3a5b51768c632f5433f86909d9b994a69", PublicKey: "031d8e1630ce640966967bc6d95223d21f44304133003140c3b52004dc981349c9", Wif: "L2QTooFoDFyRFTxmtiVHt5CfsXfVnexdbENGDkkrrgTTryiLsPMG", Passphrase: "我的密码", EncryptedWif: "6PYKWKaq5NMyjt8cjvnJnvmV13inhFuePpWZMkddFAMCgjC3ETt7kX16V9", }, { Address: "NTWHAzB82LRGWNuuqjVyyzpGvF3WxbbPoG", PrivateKey: "3edee7036b8fd9cef91de47386b191dd76db2888a553e7736bb02808932a915b", PublicKey: "02232ce8d2e2063dce0451131851d47421bfc4fc1da4db116fca5302c0756462fa", Wif: "KyKvWLZsNwBJx5j9nurHYRwhYfdQUu9tTEDsLCUHDbYBL8cHxMiG", Passphrase: "MyL33tP@33w0rd", EncryptedWif: "6PYSzKoJBQMj9uHUv1Sc2ZhMrydqDF8ZCTeE9FuPiNdEx7Lo9NoEuaXeyk", }, { Address: "xdf4UGKevVrMR1j3UkPsuoYKSC4ocoAkKx", PrivateKey: "zzdee7036b8fd9cef91de47386b191dd76db2888a553e7736bb02808932a915b", PublicKey: "zz232ce8d2e2063dce0451131851d47421bfc4fc1da4db116fca5302c0756462fa", Wif: "zzKvWLZsNwBJx5j9nurHYRwhYfdQUu9tTEDsLCUHDbYBL8cHxMiG", Passphrase: "zzL33tP@33w0rd", EncryptedWif: "6PYSzKoJBQMj9uHUv1Sc2ZhMrydqDF8ZCTeE9FuPiNdEx7Lo9NoEuaXeyk", Invalid: true, }, }
true
435d6c4e7b6e6680c9f80c23f0bcb53893f4e3c7
Go
makazeu/leetcode-solutions
/golang/1054.DistantBarcodes.go
UTF-8
1,048
3.578125
4
[]
no_license
[]
no_license
type Item struct { num, count int } type Heap struct { items []*Item } func (h Heap) Len() int { return len(h.items) } func (h Heap) Less(i, j int) bool { return h.items[i].count > h.items[j].count } func (h Heap) Swap(i, j int) { h.items[i], h.items[j] = h.items[j], h.items[i] } func (h *Heap) Pop() interface{} { l := h.Len() - 1 e := h.items[l] h.items = h.items[:l] return e } func (h *Heap) Push(x interface{}) { h.items = append(h.items, x.(*Item)) } func rearrangeBarcodes(barcodes []int) []int { var h Heap m := make(map[int]int) for _, e := range barcodes { m[e]++ } for k, v := range m { heap.Push(&h, &Item{k, v}) } last := 0 var ans []int for h.Len() > 0 { e1 := heap.Pop(&h).(*Item) if e1.num != last { ans = append(ans, e1.num) last = e1.num e1.count-- if e1.count != 0 { heap.Push(&h, e1) } continue } e2 := heap.Pop(&h).(*Item) ans = append(ans, e2.num) last = e2.num e2.count-- if e2.count != 0 { heap.Push(&h, e2) } heap.Push(&h, e1) } return ans }
true
96472606647dc98287d1e08266b5519f6e38919d
Go
tmluthfiana/hackerrank
/mini-max-sum.go
UTF-8
813
2.859375
3
[]
no_license
[]
no_license
package main import ( "bufio" "fmt" "os" "sort" "strconv" "strings" ) func main() { //Mini-Max Sum //Enter your code here. Read input from STDIN. Print output to STDOUT scanner := bufio.NewScanner(os.Stdin) lines := make([]string, 0) for scanner.Scan() { lines = append(lines, scanner.Text()) } if err := scanner.Err(); err != nil { fmt.Fprintln(os.Stderr, "reading standard input:", err) } var in []int <<<<<<< HEAD for _, a := range aa { ======= aaa := strings.Split(lines[0], " ") for _, a := range aaa { >>>>>>> 056adb0a7913cb8bdb5abbae4a24f775999c5e82 num, _ := strconv.Atoi(a) in = append(in, num) } var a = make([]int, 5) var sum int sum = 0 for i := 0; i < len(a); i++ { a[i] = in[i] sum += a[i] } sort.Ints(a) fmt.Println((sum - a[len(a)-1]), (sum - a[0])) }
true
4b8f8d6973d0ba4f2c563bde63d664168fdc7758
Go
camil0palacios/Assignment_problem
/AssingOrder.go
UTF-8
1,486
2.953125
3
[]
no_license
[]
no_license
package main import ( "sort" ) // this function assign in order of de input // complexity: O(n) or in the worst case O(n^2) func Asign(orders []Order, drivers []Driver) []Pair { n, m := len(orders), len(drivers) var ans []Pair cap := make([]int, n) for i, j := 0, 0; i < n; i++ { // x = n / m // iterate all the array if the driver does not have enough capacity for it := 0; it < n && cap[j]+1 > Get_cap(drivers[j].Vehicle); it++ { j = (j + 1) % m } if cap[j]+1 <= Get_cap(drivers[j].Vehicle) { cap[j]++ ans = append(ans, Pair{j, i}) } } return ans } // this function assign a driver to an order depending of their radius distance // complexity: O(n*m*log(n*m)) func Asign_by_aprox(orders []Order, drivers []Driver) []Pair { n := len(orders) var dist []Pair_dist for i, D := range drivers { lat1 := D.Latitude lon1 := D.Longitude vehicle := D.Vehicle for j, O := range orders { lat2 := O.Latitude lon2 := O.Longitude d := Get_dist(lat1, lon1, lat2, lon2) if d <= Get_rad(vehicle) { dist = append(dist, Pair_dist{d, Pair{i, j}}) } } } cap := make([]int, n) var ans []Pair sort.Slice(dist, func(i, j int) bool { return dist[i].Dist < dist[j].Dist }) match := make([]int, n) for i := 0; i < len(dist); i++ { dri := dist[i].Match.Ft ord := dist[i].Match.Sd if match[ord] == 0 && cap[dri]+1 <= Get_cap(drivers[dri].Vehicle) { match[ord] = 1 cap[dri]++ ans = append(ans, dist[i].Match) } } return ans }
true
bde2321f4e579a4571c1af61e1dda837bc7f3dcd
Go
aryaky/evergreen
/subprocess/remote_command.go
UTF-8
2,931
2.859375
3
[ "Apache-2.0" ]
permissive
[ "Apache-2.0" ]
permissive
package subprocess import ( "fmt" "io" "os/exec" "strings" "github.com/mongodb/grip" "github.com/mongodb/grip/message" "github.com/pkg/errors" "golang.org/x/net/context" ) type RemoteCommand struct { Id string CmdString string Stdout io.Writer Stderr io.Writer // info necessary for sshing into the remote host RemoteHostName string User string Options []string Background bool // optional flag for hiding sensitive commands from log output LoggingDisabled bool EnvVars []string // set after the command is started Cmd *exec.Cmd } func (rc *RemoteCommand) Run(ctx context.Context) error { grip.Debugf("RemoteCommand(%s) beginning Run()", rc.Id) err := rc.Start() if err != nil { return err } if rc.Cmd != nil && rc.Cmd.Process != nil { grip.Debugf("RemoteCommand(%s) started process %d", rc.Id, rc.Cmd.Process.Pid) } else { grip.Warningf("RemoteCommand(%s) has nil Cmd or Cmd.Process in Run()", rc.Id) } errChan := make(chan error) go func() { errChan <- rc.Cmd.Wait() }() select { case <-ctx.Done(): err = rc.Cmd.Process.Kill() return errors.Wrapf(err, "operation '%s' was canceled and terminated.", rc.CmdString) case err = <-errChan: return errors.WithStack(err) } } func (rc *RemoteCommand) Wait() error { return rc.Cmd.Wait() } func (rc *RemoteCommand) Start() error { // build the remote connection, in user@host format remote := rc.RemoteHostName if rc.User != "" { remote = fmt.Sprintf("%v@%v", rc.User, remote) } // build the command cmdArray := append(rc.Options, remote) if len(rc.EnvVars) > 0 { cmdArray = append(cmdArray, strings.Join(rc.EnvVars, " ")) } // set to the background, if necessary cmdString := rc.CmdString if rc.Background { cmdString = fmt.Sprintf("nohup %s > /tmp/start 2>&1 &", cmdString) } cmdArray = append(cmdArray, cmdString) loggedCommand := fmt.Sprintf("ssh %s", strings.Join(cmdArray, " ")) loggedCommand = strings.Replace(loggedCommand, "%!h(MISSING)", "%h", -1) loggedCommand = strings.Replace(loggedCommand, "%!p(MISSING)", "%p", -1) grip.InfoWhen(!rc.LoggingDisabled, message.Fields{ "message": rc.Id, "host": rc.RemoteHostName, "user": rc.User, "cmd": loggedCommand, "background": rc.Background, }) // set up execution cmd := exec.Command("ssh", cmdArray...) cmd.Stdout = rc.Stdout cmd.Stderr = rc.Stderr // cache the command running rc.Cmd = cmd return cmd.Start() } func (rc *RemoteCommand) Stop() error { if rc.Cmd != nil && rc.Cmd.Process != nil { grip.Debugf("RemoteCommand(%s) killing process %d", rc.Id, rc.Cmd.Process.Pid) err := rc.Cmd.Process.Kill() if err == nil || strings.Contains(err.Error(), "process already finished") { return nil } return errors.WithStack(err) } grip.Warningf("RemoteCommand(%s) Trying to stop command but Cmd / Process was nil", rc.Id) return nil }
true
5bc401b7d230da75db81bbeff4ea9ad981303d8c
Go
letientai299/leetcode
/go/275.h-index-ii.go
UTF-8
1,514
3.640625
4
[]
no_license
[]
no_license
package main import "sort" /* * @lc app=leetcode id=275 lang=golang * * [275] H-Index II * * https://leetcode.com/problems/h-index-ii/description/ * * algorithms * Medium (35.89%) * Total Accepted: 135.5K * Total Submissions: 374.6K * Testcase Example: '[0,1,3,5,6]' * * Given an array of citations sorted in ascending order (each citation is a * non-negative integer) of a researcher, write a function to compute the * researcher's h-index. * * According to the definition of h-index on Wikipedia: "A scientist has index * h if h of his/her N papers have at least h citations each, and the other N − * h papers have no more than h citations each." * * Example: * * * Input: citations = [0,1,3,5,6] * Output: 3 * Explanation: [0,1,3,5,6] means the researcher has 5 papers in total and each * of them had * ⁠ received 0, 1, 3, 5, 6 citations respectively. * Since the researcher has 3 papers with at least 3 citations each and the * remaining * two with no more than 3 citations each, her h-index is 3. * * Note: * * If there are several possible values for h, the maximum one is taken as the * h-index. * * Follow up: * * * This is a follow up problem to H-Index, where citations is now guaranteed to * be sorted in ascending order. * Could you solve it in logarithmic time complexity? * * */ func hIndex(citations []int) int { n := len(citations) return n - sort.Search(n, func(i int) bool { return citations[i] >= n-i }) }
true
ad17d4674d5468a61329103ba4d768a8bc542b8b
Go
thedrhax-dockerfiles/acra-go
/cli/cmd/install.go
UTF-8
1,732
2.59375
3
[ "Apache-2.0" ]
permissive
[ "Apache-2.0" ]
permissive
package cmd import ( "log" "os" "github.com/kardianos/service" "github.com/spf13/cobra" ) var installFlags struct { Dir string Name string User string } // installCmd handles system installation of acra-go var installCmd = &cobra.Command{ Use: "install", Short: "Install acra-go as a system service", Long: `Installs acra-go as a system service.`, Run: func(cmd *cobra.Command, args []string) { var err error if `` == installFlags.Dir { installFlags.Dir, err = os.Getwd() if nil != err { log.Fatalln(err) } } serviceArgs := make([]string, len(args)+1) serviceArgs[0] = `serve` if 0 < len(args) { copy(serviceArgs[1:], args) } cfg := service.Config{ Name: installFlags.Name, DisplayName: `acra-go service`, Description: `acra-go service for logging and reporting on Android ACRA enabled crash reports`, UserName: installFlags.User, Arguments: serviceArgs, Executable: ``, // Execute ourselves Dependencies: []string{}, // Not supported on Linux WorkingDirectory: installFlags.Dir, ChRoot: ``, // We'l not chroot for now } s, err := service.New(nil, &cfg) if nil != err { log.Fatalln(err) } s.Uninstall() // We uninstall, but ignore any errors that might occur if err = s.Install(); nil != err { log.Fatalln(err) } }, } func init() { opsCmd.AddCommand(installCmd) opsCmd.Flags().StringVarP(&installFlags.Dir, `dir`, `d`, ``, `Directory of acra-go: default to current working dir`) opsCmd.Flags().StringVarP(&installFlags.Name, `name`, `n`, `acra-go`, `Name of the service`) opsCmd.Flags().StringVarP(&installFlags.User, `user`, `u`, `acra-go`, `User to run as`) }
true
8635dd0ba36de91f71885aae919bcffef4086dc6
Go
rsesek/go-boom
/crashhost/reporter.go
UTF-8
2,846
2.640625
3
[]
no_license
[]
no_license
// // Go Crash Reporter // Copyright 2014 Google Inc. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // package crashhost import ( "bytes" "fmt" "io" "net/http" "os" "os/exec" "strconv" "syscall" "time" ) const kGoCrashHost = "GO_CRASH_REPORTER_HOST" func EnableCrashReporting(uploadUrl string) { // Already running under crash reporter. if crashHostPid, _ := strconv.Atoi(os.Getenv(kGoCrashHost)); crashHostPid == os.Getppid() { return } cmd := exec.Command(os.Args[0], os.Args[1:]...) // Not running under crash reporter, so re-exec, specifying this as the crash host pid. cmd.Env = append(os.Environ(), fmt.Sprintf("%s=%d", kGoCrashHost, os.Getpid())) var pr ProcessRecord pr.CommandLine = os.Args start := time.Now() // Make sure that standard fds are given back to the controlling tty, // but also caputre stdout/err for uploading with the crash report. cmd.Stdin = os.Stdin cmd.Stdout = io.MultiWriter(&pr.Stdout, os.Stdout) cmd.Stderr = io.MultiWriter(&pr.Stderr, os.Stderr) cmd.Run() if cmd.ProcessState.Success() { // The actual process has finished, so exit cleanly. os.Exit(0) } // The process did not exit cleanly, so start building a crash report. pr.Timestamp = time.Now() pr.Uptime = pr.Timestamp.Sub(start) pr.Pid = cmd.ProcessState.Pid() // TODO(rsesek): Is this OK on Windows? waitpid := cmd.ProcessState.Sys().(syscall.WaitStatus) pr.StatusString = cmd.ProcessState.String() pr.ExitCode = waitpid.ExitStatus() pr.Signaled = waitpid.Signaled() if pr.Signaled { pr.Signal = int(waitpid.Signal()) } var buf bytes.Buffer if err := pr.WriteTo(&buf); err != nil { fmt.Fprintln(os.Stderr, "Failed to write crash report:", err) os.Exit(waitpid.ExitStatus()) return } if err := uploadReport(uploadUrl, &buf); err != nil { fmt.Fprintln(os.Stderr, "Failed to upload crash report:", err) os.Exit(waitpid.ExitStatus()) return } os.Exit(waitpid.ExitStatus()) } func uploadReport(uploadUrl string, body io.Reader) error { req, err := http.NewRequest("POST", uploadUrl, body) if err != nil { return err } if req.URL.Scheme != "https" { fmt.Fprintln(os.Stderr, "\n\n*** WARNING: Submitting privacy-sensitive crash report over clear-text HTTP, not secure HTTPS! ***\n\n") } _, err = http.DefaultClient.Do(req) return err }
true
fac3b89a78a0e6f3662004f82b459a65bb9282b3
Go
Chika99/go-libonebot
/comm_http.go
UTF-8
3,574
2.84375
3
[ "MIT" ]
permissive
[ "MIT" ]
permissive
package libonebot import ( "context" "encoding/json" "fmt" "io" "net/http" "strings" "sync" ) type httpComm struct { ob *OneBot latestEvents []marshaledEvent latestEventsLock sync.Mutex } func (comm *httpComm) handleGET(w http.ResponseWriter, r *http.Request) { // TODO w.WriteHeader(http.StatusOK) w.Write([]byte("<h1>It works!</h1>")) } func (comm *httpComm) handle(w http.ResponseWriter, r *http.Request) { comm.ob.Logger.Debugf("HTTP request: %v", r) // reject unsupported methods if r.Method != "POST" && r.Method != "GET" { comm.ob.Logger.Warnf("动作请求只支持通过 POST 方式请求") w.WriteHeader(http.StatusMethodNotAllowed) return } // handle GET requests if r.Method == "GET" { comm.handleGET(w, r) return } // once we got the action HTTP request, we respond "200 OK" w.Header().Set("Content-Type", "application/json; charset=utf-8") w.WriteHeader(http.StatusOK) // reject unsupported content types if !strings.HasPrefix(r.Header.Get("Content-Type"), "application/json") { comm.fail(w, RetCodeInvalidRequest, "动作请求体 MIME 类型必须是 application/json") return } // TODO: Content-Type: application/msgpack bodyBytes, err := io.ReadAll(r.Body) if err != nil { comm.fail(w, RetCodeInvalidRequest, "动作请求体读取失败: %v", err) return } request, err := parseActionRequest(bodyBytes, false) if err != nil { comm.fail(w, RetCodeInvalidRequest, "动作请求解析失败, 错误: %v", err) return } var response Response if request.Action == ActionGetLatestEvents { // special action: get_latest_events response = comm.handleGetLatestEvents(&request) } else { response = comm.ob.handleActionRequest(&request) } json.NewEncoder(w).Encode(response) } func (comm *httpComm) handleGetLatestEvents(r *Request) (resp Response) { resp.Echo = r.Echo w := ResponseWriter{resp: &resp} events := make([]AnyEvent, 0) // TODO: use condvar to wait until there are events comm.latestEventsLock.Lock() for _, event := range comm.latestEvents { events = append(events, event.raw) } comm.latestEvents = make([]marshaledEvent, 0) comm.latestEventsLock.Unlock() w.WriteData(events) return } func (comm *httpComm) fail(w http.ResponseWriter, retcode int, errFormat string, args ...interface{}) { err := fmt.Errorf(errFormat, args...) comm.ob.Logger.Warn(err) json.NewEncoder(w).Encode(failedResponse(retcode, err)) } func commStartHTTP(c ConfigCommHTTP, ob *OneBot) commCloser { addr := fmt.Sprintf("%s:%d", c.Host, c.Port) ob.Logger.Infof("正在启动 HTTP (%v)...", addr) comm := &httpComm{ ob: ob, latestEvents: make([]marshaledEvent, 0), } mux := http.NewServeMux() mux.HandleFunc("/", comm.handle) server := &http.Server{ Addr: addr, Handler: mux, } eventChan := ob.openEventListenChan() wg := &sync.WaitGroup{} wg.Add(1) go func() { defer wg.Done() for event := range eventChan { comm.latestEventsLock.Lock() comm.latestEvents = append(comm.latestEvents, event) comm.latestEventsLock.Unlock() } }() go func() { if err := server.ListenAndServe(); err != nil && err != http.ErrServerClosed { ob.Logger.Errorf("HTTP (%v) 启动失败, 错误: %v", addr, err) } else { ob.Logger.Infof("HTTP (%v) 已关闭", addr) } }() return func() { ob.closeEventListenChan(eventChan) wg.Wait() if err := server.Shutdown(context.TODO() /* TODO */); err != nil { ob.Logger.Errorf("HTTP (%v) 关闭失败, 错误: %v", addr, err) } // TODO: wg.Wait() 后再输出已关闭 } }
true
f5ab98f5392df9b7fb1bd7040ca7d006255cec2e
Go
SergeAx/www-redirect
/www-redirect_test.go
UTF-8
2,326
2.921875
3
[]
no_license
[]
no_license
package main import ( "fmt" "net/http" "net/http/httptest" "testing" ) type dnsNameTest struct { name string result bool } var dnsNameTests = []dnsNameTest{ // RFC 2181, section 11. {"_xmpp-server._tcp.google.com", true}, {"foo.com", true}, {"1foo.com", true}, {"26.0.0.73.com", true}, {"fo-o.com", true}, {"fo1o.com", true}, {"foo1.com", true}, {"a.b..com", false}, {"a.b-.com", false}, {"a.b.com-", false}, {"a.b..", false}, {"b.com.", true}, } func TestIsDomainName(t *testing.T) { for _, pair := range dnsNameTests { if isDomainName(pair.name) != pair.result { t.Errorf("isDomainName(%q) = %v; want %v", pair.name, !pair.result, pair.result) } } } type transformDomainTest struct { name string result string status int } var transformDomainTests = []transformDomainTest{ {"example.com", "www.example.com", 0}, {"EXAMPLE.com", "www.example.com", 0}, {"www.example.com", "", http.StatusNotFound}, {"www.-example.com", "", http.StatusBadRequest}, {"a", "www.a", 0}, } func TestTransformDomain(t *testing.T) { for _, test := range transformDomainTests { result, status := transformDomain(test.name) if result == test.result && status == test.status { continue } t.Errorf("transformDomain(%s) = (%s, %d); want (%s, %d)", test.name, result, status, test.result, test.status) } } func TestRedirectHandler(t *testing.T) { request, err := http.NewRequest("GET", "/test-uri", nil) if err != nil { t.Fatal(err) } request.Header.Set("Host", "e.com") recorder := httptest.NewRecorder() handler := http.HandlerFunc(redirectHandler) handler.ServeHTTP(recorder, request) status := recorder.Code wantedStatus := http.StatusMovedPermanently if status != wantedStatus { t.Errorf("handler returned wrong status code: got %v want %v", status, wantedStatus) } location := recorder.HeaderMap.Get("Location") wantedLocation := "http://www.e.com/test-uri" if location != wantedLocation { t.Errorf("handler returned wrong location: got %v want %v", location, wantedLocation) } server := recorder.HeaderMap.Get("Server") wantedServer := fmt.Sprintf("%s (%s)", serverSoftware, serverVersion) if server != wantedServer { t.Errorf("handler returned wrong server header: got %v want %v", server, wantedServer) } //TODO: test 404 and 400 statuses }
true
e5aea74ac0b6d449dc7a76caa0b2d8e64cf90d1b
Go
sinkzephyr/go-util
/crypto_util.go
UTF-8
304
2.59375
3
[ "Apache-2.0" ]
permissive
[ "Apache-2.0" ]
permissive
package util import ( "crypto/md5" "crypto/sha1" "encoding/hex" ) func Sha1(source string) string { h := sha1.New() h.Write([]byte(source)) return hex.EncodeToString(h.Sum(nil)) } func Md5(source string) string { h := md5.New() h.Write([]byte(source)) return hex.EncodeToString(h.Sum(nil)) }
true
eebb6698489f71f196514999827327aea80085f1
Go
udhayprakash/GoLangMaterial
/miscellaneous/language-translation.go
UTF-8
1,553
3.375
3
[ "MIT" ]
permissive
[ "MIT" ]
permissive
package main import ( //"fmt" -- replace with message package in this example "golang.org/x/text/language" "golang.org/x/text/language/display" "golang.org/x/text/message" ) func main() { // define a direct translation from English to Dutch message.SetString(language.Dutch, "In %v people speak %v.", "In %v spreekt men %v.") fr := language.French region, _ := fr.Region() for _, tag := range []string{"en", "nl"} { p := message.NewPrinter(language.Make(tag)) p.Printf("In %v people speak %v.", display.Region(region), display.Language(fr)) p.Println() } // define a direct translation from English to Chinese message.SetString(language.Chinese, "In %v people speak %v.", "在%v说%v.") // * Must match for translation to work zh := language.Chinese region, _ = zh.Region() for _, tag := range []string{"en", "zh"} { p := message.NewPrinter(language.Make(tag)) p.Printf("In %v people speak %v.", display.Region(region), display.Language(zh)) // * Must match for translation to work p.Println() } // define a direct translation from English to Malay message.SetString(language.Malay, "In %v people speak %v.", "Orang %v berbahasa %v.") msmy := language.Malay region, _ = msmy.Region() for _, tag := range []string{"en", "ms"} { p := message.NewPrinter(language.Make(tag)) p.Printf("In %v people speak %v.", display.Region(region), display.Language(msmy)) p.Println() } } /* Ref: https://godoc.org/golang.org/x/text/message https://godoc.org/golang.org/x/text/language/display#Dictionary.Languages */
true
7ec3a94ef1fc696cbdc52d8f09827464c26ad9a7
Go
superloach/hide
/easy/packr.go
UTF-8
956
2.65625
3
[]
no_license
[]
no_license
package easy import ( "bytes" "encoding/json" "image/png" "github.com/gobuffalo/packr/v2" "github.com/hajimehoshi/ebiten" "github.com/superloach/hide/level" ) var ImageBox = packr.New("ImageBox", "./../assets/images") var LevelBox = packr.New("LevelBox", "./../assets/levels") func LoadImage(name string) (*ebiten.Image, error) { data, err := ImageBox.Find(name + ".png") if err != nil { return nil, err } read := bytes.NewReader(data) img, err := png.Decode(read) if err != nil { return nil, err } return ebiten.NewImageFromImage(img, ebiten.FilterDefault) } func LoadLevel(name string) (*level.Level, error) { data, err := LevelBox.Find(name + ".json") if err != nil { return nil, err } l := &level.Level{} err = json.Unmarshal(data, l) if err != nil { return l, err } for id, name := range l.Tiles { img, err := LoadImage(name) if err != nil { return l, err } l.TileImages[id] = img } return l, nil }
true
321440cb6c030be58953e0ae4a0ecd26a164748b
Go
hmoog/metastabilitybreaker
/consensus.go
UTF-8
2,732
2.890625
3
[]
no_license
[]
no_license
package metastabilitybreaker import ( "math" "time" ) const ( confirmationThreshold = 0.66 ) // region Consensus //////////////////////////////////////////////////////////////////////////////////////////////////// type Consensus struct { voter Voter timeOffset time.Duration } func NewConsensus(voter Voter) *Consensus { return &Consensus{ voter: voter, } } func (c *Consensus) CompetingBranches() (largestBranch, secondLargestBranch BranchID) { var largestBranchWeight, secondLargestBranchWeight float64 for branchID := range c.voter.BranchManager().BranchIDs() { branchWeight := c.voter.ApprovalWeightManager().Weight(branchID) if branchWeight >= largestBranchWeight { secondLargestBranch = largestBranch secondLargestBranchWeight = largestBranchWeight largestBranchWeight = branchWeight largestBranch = branchID } else if branchWeight >= secondLargestBranchWeight { secondLargestBranch = branchID secondLargestBranchWeight = branchWeight } } return } func (c *Consensus) FavoredBranch() BranchID { heaviestBranch, secondHeaviestBranch := c.CompetingBranches() if heaviestBranch == UndefinedBranchID || secondHeaviestBranch == UndefinedBranchID { return heaviestBranch } if c.voter.Network().MetastabilityBreakingThreshold != 0 && c.deltaWeight(heaviestBranch, secondHeaviestBranch) <= c.timeScaling(heaviestBranch, secondHeaviestBranch)*confirmationThreshold { if heaviestBranch < secondHeaviestBranch { return heaviestBranch } return secondHeaviestBranch } if c.voter.ApprovalWeightManager().Weight(heaviestBranch) > c.voter.ApprovalWeightManager().Weight(secondHeaviestBranch) { return heaviestBranch } return secondHeaviestBranch } func (c *Consensus) deltaWeight(branch1ID, branch2ID BranchID) float64 { return math.Abs(c.voter.ApprovalWeightManager().Weight(branch1ID) - c.voter.ApprovalWeightManager().Weight(branch2ID)) } func (c *Consensus) pendingTime(branch1ID, branch2ID BranchID) time.Duration { branch1SolidificationTime := c.voter.BranchManager().Metadata(branch1ID).SolidificationTime branch2SolidificationTime := c.voter.BranchManager().Metadata(branch2ID).SolidificationTime if branch1SolidificationTime.After(branch2SolidificationTime) { return time.Now().Add(c.timeOffset).Sub(branch1SolidificationTime) } return time.Now().Add(c.timeOffset).Sub(branch2SolidificationTime) } func (c *Consensus) timeScaling(branch1ID, branch2ID BranchID) float64 { return math.Min(float64(c.pendingTime(branch1ID, branch2ID).Nanoseconds())/float64(c.voter.Network().MetastabilityBreakingThreshold.Nanoseconds()), 1) } // endregion ///////////////////////////////////////////////////////////////////////////////////////////////////////////
true
bc7ab8b43f9593aac3890a100f26193c9bb7a8f6
Go
mingzhi/meta
/cmd/meta_calc_corr/calc.go
UTF-8
2,866
2.578125
3
[]
no_license
[]
no_license
package main import ( "github.com/mingzhi/gomath/stat/desc/meanvar" "github.com/mingzhi/ncbiftp/genomes/profiling" "log" "math" "runtime" ) // Calc perform calculations. func Calc(snpChan chan *SNP, profile []profiling.Pos, posType byte, maxl int) (cChan chan *Calculator) { ncpu := runtime.GOMAXPROCS(0) // create job chan // each job is a list of SNP in a gene. geneSNPChan := make(chan []*SNP, ncpu) go func() { defer close(geneSNPChan) var geneName string var storage []*SNP for snp := range snpChan { if checkPosType(posType, profile[snp.Pos-1].Type) { geneName1 := profile[snp.Pos-1].Gene if len(storage) != 0 && geneName != geneName1 { geneSNPChan <- storage storage = []*SNP{} geneName = geneName1 } storage = append(storage, snp) } } if len(storage) != 0 { geneSNPChan <- storage } log.Println("Finished generating gene SNP!") }() cChan = make(chan *Calculator) done := make(chan bool) for i := 0; i < ncpu; i++ { go func() { for storage := range geneSNPChan { c := NewCalculator(maxl) calc(c, storage, posType, profile, maxl) cChan <- c } done <- true }() } go func() { defer close(cChan) for i := 0; i < ncpu; i++ { <-done } log.Println("Finished calculation!") }() return } func calc(c *Calculator, snpArr []*SNP, t byte, profile []profiling.Pos, maxl int) { for i := 0; i < len(snpArr); i++ { s1 := snpArr[i] if checkPosType(t, profile[s1.Pos-1].Type) { for j := i; j < len(snpArr); j++ { s2 := snpArr[j] if checkPosType(t, profile[s2.Pos-1].Type) { c.Calc(s1, s2) } } } } } func Collect(maxl int, cChan chan *Calculator) (means, covs, xbars, ybars, totals []*meanvar.MeanVar) { for i := 0; i < maxl; i++ { means = append(means, meanvar.New()) covs = append(covs, meanvar.New()) totals = append(totals, meanvar.New()) xbars = append(xbars, meanvar.New()) ybars = append(ybars, meanvar.New()) } for c := range cChan { for i := 0; i < c.MaxL; i++ { cr := c.Cr.GetResult(i) cs := c.Cs.GetMean(i) ct := c.Ct.GetResult(i) xbar := c.Cr.GetMeanX(i) ybar := c.Cr.GetMeanY(i) n := c.Cr.GetN(i) if !math.IsNaN(cr) && !math.IsNaN(cs) && !math.IsNaN(ct) && n >= 50 { covs[i].Increment(cr) means[i].Increment(cs) totals[i].Increment(ct) xbars[i].Increment(xbar) ybars[i].Increment(ybar) } } } return } func checkPosType(t, t1 byte) bool { isFirstPos := t1 == profiling.FirstPos isSecondPos := t1 == profiling.SecondPos isThirdPos := t1 == profiling.ThirdPos isFourFold := t1 == profiling.FourFold if t == profiling.Coding { if isFirstPos || isSecondPos || isThirdPos || isFourFold { return true } return false } if t == profiling.ThirdPos { if isThirdPos || isFourFold { return true } return false } return t == t1 }
true
9ea2ca7063ad56e6bcfe69e38575ed5b8864883b
Go
odedlaz/tpl
/filters/getenv/getenv_test.go
UTF-8
569
2.65625
3
[ "MIT" ]
permissive
[ "MIT" ]
permissive
package GetEnvFilter import ( "os" "testing" "github.com/odedlaz/tpl/template" ) func TestGetenv(t *testing.T) { os.Setenv("SET", "OK") defer os.Unsetenv("SET") txt, err := template.Execute("{{ \"SET\"|getenv }}") if txt != "OK" || err != nil { t.Fail() } } func TestGetenvDefaultWhenMissing(t *testing.T) { txt, err := template.Execute("{{ \"NOT_SET\"|getenv:\"OK\" }}") if txt != "OK" || err != nil { t.Fail() } } func TestGetenvMissingFails(t *testing.T) { _, err := template.Execute("{{ \"NOT_SET\"|getenv }}") if err == nil { t.Fail() } }
true
69bba45e67fdb4a22465ea47673e3719236937da
Go
bartdeboer/exec
/args.go
UTF-8
2,205
2.890625
3
[ "BSD-3-Clause" ]
permissive
[ "BSD-3-Clause" ]
permissive
// Copyright 2009 Bart de Boer. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package exec import ( "fmt" "reflect" "strconv" "github.com/iancoleman/strcase" ) func BuildArgs(args ...interface{}) []string { ret := []string{} for _, arg := range args { rv := reflect.ValueOf(arg) rt := reflect.TypeOf(arg) switch rv.Kind() { case reflect.Slice, reflect.Array: if rt.Elem().Kind() == reflect.String { ret = append(ret, arg.([]string)...) } else { ret = append(ret, SliceToString(arg)...) } case reflect.String: ret = append(ret, arg.(string)) case reflect.Int: ret = append(ret, strconv.FormatInt(rv.Int(), 10)) case reflect.Struct: ret = append(ret, BuildArgsFromStruct(arg)...) default: ret = append(ret, fmt.Sprintf("%v", arg)) } } return ret } func BuildArgsFromStruct(input interface{}) []string { agrs := []string{} // https://blog.golang.org/laws-of-reflection rv := reflect.ValueOf(input) typeOfT := rv.Type() if k := rv.Kind(); k != reflect.Struct { panic("Value is not a struct") } for i := 0; i < rv.NumField(); i++ { name := typeOfT.Field(i).Name value := rv.Field(i) opt := "--" + strcase.ToKebab(name) if value.Kind() == reflect.Bool { if value.Bool() == true { agrs = append(agrs, opt) } continue } strVal := ValueToString(rv.Field(i)) // strVal := fmt.Sprintf("%v", f.Interface()) // strVal := f.Interface().(string) if strVal == "" || strVal == "0" { continue } agrs = append(agrs, opt, strVal) } return agrs } func ValueToString(val reflect.Value) string { var ret string switch val.Kind() { case reflect.String: ret = val.String() case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: ret = strconv.FormatInt(val.Int(), 10) } return ret } func SliceToString(input interface{}) []string { var ret []string v := reflect.ValueOf(input) switch v.Kind() { case reflect.Slice, reflect.Array: ret = make([]string, v.Len()) for i := 0; i < v.Len(); i++ { ret[i] = ValueToString(v.Index(i)) // ret[i] = fmt.Sprintf("%v", v.Index(i).Interface()) } } return ret }
true
5fe5f35e20ae101cf842de4b82b173bdd0374e00
Go
kbuzsaki/httpserv
/http/response.go
UTF-8
1,345
3.40625
3
[]
no_license
[]
no_license
package http import ( "io" "strconv" ) type Protocol struct { Name string Version string } var HttpOneDotOne = Protocol{"HTTP", "1.1"} func (protocol *Protocol) String() string { return protocol.Name + "/" + protocol.Version } type Status struct { Code int Name string } func (status *Status) String() string { return strconv.Itoa(status.Code) + " " + status.Name } func (status *Status) WriteTo(writer io.Writer) (int64, error) { n, err := writer.Write([]byte(status.String() + "\n")) return int64(n), err } var StatusOk Status = Status{200, "OK"} var StatusMovedTemporarily = Status{302, "Found"} var StatusNotFound Status = Status{404, "Not Found"} var StatusInternalError = Status{500, "Internal Server Error"} type ResponseHeader struct { Key string Val string } type Response struct { Protocol Protocol Status Status Headers []ResponseHeader Body string } func MakeSimpleResponse(body string) Response { return Response{HttpOneDotOne, StatusOk, nil, body} } func MakeErrorResponse(status Status, err error) Response { body := "<h1>" + status.String() + "</h1>" + err.Error() return Response{HttpOneDotOne, status, nil, body} } func MakeRedirectResponse(path string) Response { headers := []ResponseHeader{{"Location", path}} return Response{HttpOneDotOne, StatusMovedTemporarily, headers, ""} }
true
1b727c021e9d7f699299730985543707bc7fcbb9
Go
OlegElizarov/Task_for_mail
/lib/functions.go
UTF-8
916
2.875
3
[]
no_license
[]
no_license
package lib import ( "io/ioutil" "net/http" "regexp" ) func NumberInFile(path string) (int, error) { dat, err := ioutil.ReadFile(path) if err != nil { return 0, err } re := regexp.MustCompile(`([Gg])o`) //re := regexp.MustCompile(`(^| |\n|\W)Go(\n| |$|\W)`) in order if you want only "Go" string return len(re.FindAll(dat, -1)), nil //return strings.Count(string(body), "Go")+strings.Count(string(body), "go"), nil bad way } func NumberInURL(url string) (int, error) { resp, err := http.Get(url) if err != nil { return 0, err } defer resp.Body.Close() body, err := ioutil.ReadAll(resp.Body) if err != nil { return 0, err } re := regexp.MustCompile(`([Gg])o`) //re := regexp.MustCompile(`(^| |\n|\W)Go(\n| |$|\W)`) in order if you want only "Go" string return len(re.FindAll(body, -1)), nil //return strings.Count(string(body), "Go")+strings.Count(string(body), "go"), nil bad way }
true
ac051375b7888a0d412ef35cca493b035561fdd6
Go
luohl364218/golangPractice
/practice03/example05/TestSwitch.go
UTF-8
1,135
4.03125
4
[]
no_license
[]
no_license
package main import ( "fmt" "math/rand" ) //switch语句中fallthrough穿透,没有break语句跳出,默认都是跳出 func main() { a := 6 //有判断条件 switch a { case 0: fmt.Println("值为0") fallthrough case 1: fmt.Println("值为1") fallthrough case 2: fmt.Println("值为2") case 3, 4, 5, 6, 7, 8: fmt.Println("值在3, 4, 5, 6, 7, 8之间") default: fmt.Println("值未知") } //无条件判断 switch { case a > 0 && a < 5: fmt.Println("a > 0 && a < 5") case a >= 5 && a < 10: fmt.Println("a >= 5 && a < 10") default: fmt.Println("default") } //语句块判断 后面要加分号 switch a = 3 * a;{ case a > 0 && a < 5: fmt.Println("a > 0 && a < 5") case a >= 5 && a < 10: fmt.Println("a >= 5 && a < 10") default: fmt.Println("a >= 10") } //判断有没有猜对随机数 n := rand.Intn(100) for{ var input int fmt.Scanf("%d", &input) flag := false switch { case input == n: flag = true fmt.Println("you are right!!!!!") case input > n: fmt.Println("bigger") case input < n: fmt.Println("less") } if flag { break } } }
true
70123b76e6fb086231b25f97dba981d25c9682c6
Go
alexzarazuaa/Kalypso_Go-gin-gonic_Laravel_Angular
/backend/go/users/src/routers.go
UTF-8
6,176
2.65625
3
[ "MIT" ]
permissive
[ "MIT" ]
permissive
package users import ( "fmt" "strings" "errors" "goUsers/common" "github.com/gin-gonic/gin" "net/http" ) func UsersRegister(router *gin.RouterGroup) { router.POST("/", UsersRegistration) router.POST("/login", UsersLogin) } func UserRegister(router *gin.RouterGroup) { router.GET("/", UserRetrieve) router.PUT("/", UserUpdate) } func ProfileRegister(router *gin.RouterGroup) { router.GET("/:username", ProfileRetrieve) router.POST("/:username/follow", ProfileFollow) router.DELETE("/:username/follow", ProfileUnfollow) } func ProfileRetrieve(c *gin.Context) { username := c.Param("username") userModel, err := FindOneUser(&Users{Username: username}) if err != nil { c.JSON(http.StatusNotFound, common.NewError("profile", errors.New("Invalid username"))) return } profileSerializer := ProfileSerializer{c, userModel} c.JSON(http.StatusOK, gin.H{"profile": profileSerializer.Response()}) } func ProfileFollow(c *gin.Context) { username := c.Param("username") userModel, err := FindOneUser(&Users{Username: username}) if err != nil { c.JSON(http.StatusNotFound, common.NewError("profile", errors.New("Invalid username"))) return } myUsers := c.MustGet("my_user_model").(Users) err = myUsers.following(userModel) if err != nil { c.JSON(http.StatusUnprocessableEntity, common.NewError("database", err)) return } serializer := ProfileSerializer{c, userModel} c.JSON(http.StatusOK, gin.H{"profile": serializer.Response()}) } func ProfileUnfollow(c *gin.Context) { username := c.Param("username") userModel, err := FindOneUser(&Users{Username: username}) if err != nil { c.JSON(http.StatusNotFound, common.NewError("profile", errors.New("Invalid username"))) return } myUsers := c.MustGet("my_user_model").(Users) err = myUsers.unFollowing(userModel) if err != nil { c.JSON(http.StatusUnprocessableEntity, common.NewError("database", err)) return } serializer := ProfileSerializer{c, userModel} c.JSON(http.StatusOK, gin.H{"profile": serializer.Response()}) } func UsersRegistration(c *gin.Context) { userModelValidator := NewUsersValidator() if err := userModelValidator.Bind(c); err != nil { c.JSON(http.StatusUnprocessableEntity, common.NewValidatorError(err)) return } if err := SaveOne(&userModelValidator.userModel); err != nil { c.JSON(http.StatusUnprocessableEntity, common.NewError("database", err)) return } c.Set("my_user_model", userModelValidator.userModel) serializer := UserSerializer{c} mail:= strings.Split(serializer.Response().Email, "@") bearer:= strings.Split(serializer.Response().Bearer, ".") cryptbearer:=bearer[0] + `*` + mail[0] + `*` + bearer[1] + `*` + mail[1] + `*` + bearer[2] client := common.NewClient() err_redis := common.SetUser("user", cryptbearer, client) if err_redis != nil { c.JSON(http.StatusBadRequest, gin.H{"error": err_redis.Error()}) return } c.JSON(http.StatusCreated, gin.H{"user": serializer.Response()}) } func UsersLogin(c *gin.Context) { loginValidator := NewLoginValidator() if err := loginValidator.Bind(c); err != nil { c.JSON(http.StatusUnprocessableEntity, common.NewValidatorError(err)) return } userModel, err := FindOneUser(&Users{Email: loginValidator.userModel.Email}) if err != nil { c.JSON(http.StatusForbidden, common.NewError("login", errors.New("Not Registered email or invalid password"))) return } if userModel.checkPassword(loginValidator.User.Password) != nil { c.JSON(http.StatusForbidden, common.NewError("login", errors.New("Not Registered email or invalid password"))) return } if ((userModel.Type)=="client"){ //Type client -> Login UpdateContextUsers(c, userModel.ID) serializer := UserSerializer{c} mail:= strings.Split(serializer.Response().Email, "@") bearer:= strings.Split(serializer.Response().Bearer, ".") cryptbearer:=bearer[0] + `*` + mail[0] + `*` + bearer[1] + `*` + mail[1] + `*` + bearer[2] client := common.NewClient() err_redis := common.SetUser("user", cryptbearer, client) if err_redis != nil { c.JSON(http.StatusBadRequest, gin.H{"error": err_redis.Error()}) return } c.JSON(http.StatusOK, gin.H{"user": serializer.Response()}) }else if ((userModel.Type)=="admin"){ //Type admin -> show user information // create bearer serializer1 := UserSerializer{c} bearer:=serializer1.Response().Bearer // insert bearer in DB err := userModel.InsertToken(&Users{Bearer:bearer}) if err != nil { c.JSON(http.StatusNotFound, common.NewError("DB", errors.New("Error Update Login Admin"))) return } //create code to save in json redis s := strings.Split(userModel.Email, "@") code:= fmt.Sprint(userModel.ID) + userModel.Username[0:3] + s[0][len(s[0])-3:] + userModel.Username[len(userModel.Username)-2:] + bearer[0:5] //Create json to save in redis client := common.NewClient() user:=`{"username":"`+userModel.Username+`", "email":"`+userModel.Email+`", "type": "`+userModel.Type+`", "bearer":"`+bearer+`", "code":"`+code+`"}` err_redis := common.SetUser(userModel.Email, user, client) if err_redis != nil { c.JSON(http.StatusBadRequest, gin.H{"error": err_redis.Error()}) return } //all right serializer := AdminSerializer{c, userModel} c.JSON(http.StatusOK, gin.H{"user": serializer.Response()}) } else{ //No normal type -> show type c.JSON(http.StatusOK, gin.H{"Does not have a normal type": userModel.Type }) } } func UserRetrieve(c *gin.Context) { serializer := UserSerializer{c} c.JSON(http.StatusOK, gin.H{"user": serializer.Response()}) } func UserUpdate(c *gin.Context) { myUsers := c.MustGet("my_user_model").(Users) userModelValidator := NewUsersValidatorFillWith(myUsers) if err := userModelValidator.Bind(c); err != nil { c.JSON(http.StatusUnprocessableEntity, common.NewValidatorError(err)) return } userModelValidator.userModel.ID = myUsers.ID if err := myUsers.Update(userModelValidator.userModel); err != nil { c.JSON(http.StatusUnprocessableEntity, common.NewError("database", err)) return } UpdateContextUsers(c, myUsers.ID) serializer := UserSerializer{c} c.JSON(http.StatusOK, gin.H{"user": serializer.Response()}) }
true
75476f620b0a0756e9d472a4ce318ec7ed389547
Go
thiduzz/gallery
/models/services.go
UTF-8
811
2.8125
3
[]
no_license
[]
no_license
package models import ( "gorm.io/driver/postgres" "gorm.io/gorm" "gorm.io/gorm/logger" ) type Services struct { Gallery GalleryService User UserService Photo PhotoService db *gorm.DB } func NewServices(connectionInfo string) (*Services, error) { db, err := gorm.Open(postgres.Open(connectionInfo), &gorm.Config{ Logger: logger.Default.LogMode(logger.Info), }) if err != nil{ return nil, err } return &Services{ User: NewUserService(db), Gallery: NewGalleryService(db), Photo: NewPhotoService(db), db: db, }, nil } func (sv *Services) AutoMigrate() error { return sv.db.AutoMigrate(&User{}, &Gallery{}, &Photo{}) } func (sv *Services) DestructiveReset() error { if err := sv.db.Migrator().DropTable(&User{}, &Gallery{}); err != nil { return err } return sv.AutoMigrate() }
true
52ffdf8e8329a935b45ca22ce2bed952da3193b0
Go
193792768lyw/study-2021
/arithmetic/377/main.go
UTF-8
1,134
3.03125
3
[]
no_license
[]
no_license
package main import ( "fmt" "sort" ) func main() { fmt.Println(combinationSum4([]int{1, 2, 3}, 32)) } func combinationSum4(nums []int, target int) int { dp := make([]int, target+1) dp[0] = 1 for i := 1; i <= target; i++ { for _, num := range nums { if num <= i { dp[i] += dp[i-num] } } } return dp[target] } func combinationSum42(nums []int, target int) int { sort.Ints(nums) res := 0 // 181997601 var dfs func(target int) dfs = func(target int) { if target == 0 { res++ return } for i := 0; i < len(nums); i++ { if target-nums[i] < 0 { break } dfs(target - nums[i]) } } dfs(target) return res } func combinationSum41(nums []int, target int) int { //sort.Ints(nums) ans := [][]int{} comb := []int{} var dfs func(target, idx int) dfs = func(target, idx int) { if target == 0 { ans = append(ans, append([]int(nil), comb...)) return } for i := idx; i < len(nums); i++ { if target-nums[i] < 0 { break } comb = append(comb, nums[i]) dfs(target-nums[i], 0) comb = comb[:len(comb)-1] } } dfs(target, 0) fmt.Println(ans) return len(ans) }
true
694163747f2be92e4758811bc59da1c18c114cd7
Go
microsoftgraph/msgraph-beta-sdk-go
/models/mobile_threat_defense_partner_priority.go
UTF-8
1,753
2.734375
3
[ "MIT" ]
permissive
[ "MIT" ]
permissive
package models import ( "errors" ) // Determines the conflict resolution strategy, when more than one Mobile Threat Defense provider is enabled. type MobileThreatDefensePartnerPriority int const ( // Indicates use of Microsoft Defender Endpoint over 3rd party MTD connectors DEFENDEROVERTHIRDPARTYPARTNER_MOBILETHREATDEFENSEPARTNERPRIORITY MobileThreatDefensePartnerPriority = iota // Indicates use of a 3rd party MTD connector over Microsoft Defender Endpoint THIRDPARTYPARTNEROVERDEFENDER_MOBILETHREATDEFENSEPARTNERPRIORITY // Evolvable enumeration sentinel value. Do not use. UNKNOWNFUTUREVALUE_MOBILETHREATDEFENSEPARTNERPRIORITY ) func (i MobileThreatDefensePartnerPriority) String() string { return []string{"defenderOverThirdPartyPartner", "thirdPartyPartnerOverDefender", "unknownFutureValue"}[i] } func ParseMobileThreatDefensePartnerPriority(v string) (any, error) { result := DEFENDEROVERTHIRDPARTYPARTNER_MOBILETHREATDEFENSEPARTNERPRIORITY switch v { case "defenderOverThirdPartyPartner": result = DEFENDEROVERTHIRDPARTYPARTNER_MOBILETHREATDEFENSEPARTNERPRIORITY case "thirdPartyPartnerOverDefender": result = THIRDPARTYPARTNEROVERDEFENDER_MOBILETHREATDEFENSEPARTNERPRIORITY case "unknownFutureValue": result = UNKNOWNFUTUREVALUE_MOBILETHREATDEFENSEPARTNERPRIORITY default: return 0, errors.New("Unknown MobileThreatDefensePartnerPriority value: " + v) } return &result, nil } func SerializeMobileThreatDefensePartnerPriority(values []MobileThreatDefensePartnerPriority) []string { result := make([]string, len(values)) for i, v := range values { result[i] = v.String() } return result }
true
76495b3348216c45992a2fca04a57f82d3991d11
Go
rpwatkins/md2pdf
/internal/model/text_content.go
UTF-8
699
3.28125
3
[ "MIT" ]
permissive
[ "MIT" ]
permissive
package model // Text models text strings that make up a Paragraph, Blockquote, List Item, or Table Cell. type Text struct { Text string `json:"text"` Bold bool `json:"bold"` Italic bool `json:"italic"` Code bool `json:"code"` Strike bool `json:"strike"` HREF string `json:"href"` } // Copy returns a new Text struct with the same values as the Text it was called from. // Except the Content field, that's empty. func (txt Text) Copy() Text { var newText Text if txt.Bold { newText.Bold = true } if txt.Italic { newText.Italic = true } if txt.Code { newText.Code = true } if txt.Strike { newText.Strike = true } newText.HREF = txt.HREF[:] return newText }
true
9a6f610e4f117a179f81b1be57b427dabc50aac5
Go
twosixme/grpclb
/balancer/ketama.go
UTF-8
2,505
3.046875
3
[]
no_license
[]
no_license
package balancer import ( "hash/fnv" "sort" "strconv" "sync" ) type HashFunc func(data []byte) uint32 const ( defaultReplicas = 10 salt = "n*@if09g3n" ) type Uint32Slice []uint32 func (p Uint32Slice) Len() int { return len(p) } func (p Uint32Slice) Less(i, j int) bool { return p[i] < p[j] } func (p Uint32Slice) Swap(i, j int) { p[i], p[j] = p[j], p[i] } func (p Uint32Slice) Sort() { sort.Sort(p) } func sortUint32s(a []uint32) { sort.Sort(Uint32Slice(a)) } func defaultHash(data []byte) uint32 { f := fnv.New32() _, _ = f.Write(data) return f.Sum32() } type Ketama struct { mu sync.RWMutex hash HashFunc replicas int keys []uint32 buckets map[uint32]string } func NewKetama(replicas int, hash HashFunc) *Ketama { h := &Ketama{ replicas: replicas, hash: hash, buckets: make(map[uint32]string), } if h.replicas <= 0 { h.replicas = defaultReplicas } if h.hash == nil { h.hash = defaultHash } return h } func (h *Ketama) Add(nodes ...string) { h.mu.Lock() defer h.mu.Unlock() for _, node := range nodes { for i := 0; i < h.replicas; i++ { key := h.hash([]byte(salt + strconv.Itoa(i) + node)) if _, ok := h.buckets[key]; !ok { h.keys = append(h.keys, key) } h.buckets[key] = node } } sortUint32s(h.keys) } func (h *Ketama) Remove(nodes ...string) { h.mu.Lock() defer h.mu.Unlock() var deletedKeys []uint32 for _, node := range nodes { for i := 0; i < h.replicas; i++ { key := h.hash([]byte(salt + strconv.Itoa(i) + node)) if _, ok := h.buckets[key]; ok { deletedKeys = append(deletedKeys, key) delete(h.buckets, key) } } } if len(deletedKeys) > 0 { h.deleteKeys(deletedKeys) } } func (h *Ketama) deleteKeys(deletedKeys []uint32) { sortUint32s(deletedKeys) var index int var count int for _, key := range deletedKeys { for ; index < len(h.keys); index++ { h.keys[index-count] = h.keys[index] if key == h.keys[index] { count++ index++ break } } } for ; index < len(h.keys); index++ { h.keys[index-count] = h.keys[index] } h.keys = h.keys[:len(h.keys)-count] } func (h *Ketama) Get(key string) (string, bool) { h.mu.RLock() defer h.mu.RUnlock() if len(h.keys) == 0 { return "", false } hash := h.hash([]byte(key)) idx := sort.Search(len(h.keys), func(i int) bool { return h.keys[i] >= hash }) if idx == len(h.keys) { idx = 0 } value, ok := h.buckets[h.keys[idx]] return value, ok }
true
06acaafa2006c080ad5d93fbb63c08a8312d2d19
Go
antonio-decaro/Probex
/src/devices/telescope/telescope.go
UTF-8
2,030
2.875
3
[]
no_license
[]
no_license
package main import ( "encoding/json" "fmt" "strconv" mqtt "github.com/eclipse/paho.mqtt.golang" ) type TelescopeData struct { Name string Coordinate [2]float64 Distance float64 StarDistance float64 // astronomic units StarType string Mass float64 Radius float64 } func main() { fmt.Println("[*] Starting Telescope simulation device") defer fmt.Println("[.] Terminating Telescope simulation device") var data TelescopeData var x, y, distance, stardistance, mass, radius string var xfloat, yfloat float64 fmt.Println("[+] Insert Name: ") fmt.Scanln(&data.Name) fmt.Println("[+] Insert Coordinate (x y): ") fmt.Scanln(&x, &y) fmt.Println("[+] Insert Distance: ") fmt.Scanln(&distance) fmt.Println("[+] Insert StarDistance: ") fmt.Scanln(&stardistance) fmt.Println("[+] Insert StarType: ") fmt.Scanln(&data.StarType) fmt.Println("[+] Insert Mass: ") fmt.Scanln(&mass) fmt.Println("[+] Insert Radius: ") fmt.Scanln(&radius) xfloat, _ = strconv.ParseFloat(x, 64) yfloat, _ = strconv.ParseFloat(y, 64) data.Coordinate = [2]float64{xfloat, yfloat} data.Distance, _ = strconv.ParseFloat(distance, 64) data.StarDistance, _ = strconv.ParseFloat(stardistance, 64) data.Mass, _ = strconv.ParseFloat(mass, 64) data.Radius, _ = strconv.ParseFloat(mass, 64) stream, _ := json.Marshal(data) fmt.Printf("[*] Found a Planet with those specs: %s\n", string(stream)) sendData(data) fmt.Printf("[.] Data sent") } func sendData(data interface{}) { opts := mqtt.NewClientOptions() const ( username = "guest" password = "guest" ip = "localhost" ) opts.AddBroker(fmt.Sprintf("tcp://%s:1883", ip)) opts.SetClientID("telescope") opts.SetUsername(username) opts.SetPassword(password) client := mqtt.NewClient(opts) if token := client.Connect(); token.Wait() && token.Error() != nil { panic(token.Error()) } token := client.Publish("iot/telescope", 2, false, data) if !token.Wait() { panic(fmt.Errorf("error sending the message")) } }
true
ad549213ca875c1a9a948117fc59f220dc45477c
Go
xinbingwu/go
/6.go
UTF-8
265
3.234375
3
[]
no_license
[]
no_license
package main import ( "fmt" "math" ) func main(){ var c float32 = math.Pi //将常量保存为float32类型 fmt.Println(c) fmt.Println(int(c)) //转换为int类型,浮点发生精度丢失 fmt.Println(math.Pi) //注:布尔型值不能强制转换 }
true
22b5ff80ccc2a9b0aef76a99015f364f8178aa7d
Go
last9/tsl8
/commands/worker/main_test.go
UTF-8
3,855
2.703125
3
[ "MIT" ]
permissive
[ "MIT" ]
permissive
package main import ( "encoding/json" "io/ioutil" "log" "testing" "net/http" "net/http/httptest" "net/url" "github.com/stretchr/testify/assert" "github.com/tsocial/tessellate/server" "github.com/tsocial/tessellate/storage" "github.com/tsocial/tessellate/storage/types" ) var store storage.Storer func TestMainRunner(t *testing.T) { log.SetFlags(log.LstdFlags | log.Lshortfile) wID := "w123" lID := "l123" // Tree for workspace ID. tree := types.MakeTree(wID) func() { // Create a new types.Workspace instance to be returned. workspace := types.Workspace(wID) err := store.Save(&workspace, tree) assert.Nil(t, err) }() layoutSave := func(path string) { plan := map[string]json.RawMessage{} lBytes, err := ioutil.ReadFile(path) assert.Nil(t, err) plan["sleep"] = lBytes // Create layout instance to be saved for given ID and plan. layout := types.Layout{Id: lID, Plan: plan} // Save the layout. err = store.Save(&layout, tree) assert.Nil(t, err) } jID := func() string { j := types.Job{ LayoutId: lID, LayoutVersion: "latest", Op: int32(server.Operation_APPLY), } // Save this job in workspace tree. err := store.Save(&j, tree) assert.Nil(t, err) return j.Id }() t.Run("Should run successfully", func(t *testing.T) { layoutSave("../../runner/testdata/sleep.tf.json") in := &input{ jobID: jID, workspaceID: wID, layoutID: lID, tmpDir: "success-run", } collector := map[string][]*watchPacket{} s, err := hookServer(func(uv *url.URL, p *watchPacket) { u := uv.String() if _, ok := collector[u]; !ok { collector[u] = []*watchPacket{} } collector[u] = append(collector[u], p) }) if err != nil { t.Fatal(err) } defer s.Close() defaultWatch := "/default-watch" h, err := url.Parse(s.URL + defaultWatch) if err != nil { t.Fatal(err) } tree := types.MakeTree(wID, lID) if err := addWatch(tree, s.URL); err != nil { t.Fatal(err) } t.Run("without default watch", func(t *testing.T) { x := mainRunner(store, in, nil) // expect that 2 handlers are called. assert.Equal(t, 0, x) assert.Equal(t, 0, len(collector[defaultWatch])) assert.Equal(t, 1, len(collector)) }) t.Run("with default watch", func(t *testing.T) { x := mainRunner(store, in, h) // expect that 2 handlers are called. assert.Equal(t, 0, x) assert.Equal(t, 1, len(collector[defaultWatch])) assert.Equal(t, 2, len(collector)) }) }) t.Run("Should fail", func(t *testing.T) { layoutSave("../../runner/testdata/faulty.tf.json") in := &input{ jobID: jID, workspaceID: wID, layoutID: lID, tmpDir: "failed-run", } x := mainRunner(store, in, nil) assert.Equal(t, 127, x) }) } // Starts a new server for test purposes func watchMux(f func(*url.URL, *watchPacket)) (*http.ServeMux, error) { mux := http.NewServeMux() mux.Handle("/user-watch", watchHandler(f)) mux.Handle("/default-watch", watchHandler(f)) return mux, nil } func watchHandler(f func(url *url.URL, p *watchPacket)) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { s := watchPacket{} b, err := ioutil.ReadAll(r.Body) if err != nil { w.WriteHeader(http.StatusInternalServerError) return } if err := json.Unmarshal(b, &s); err != nil { w.WriteHeader(http.StatusInternalServerError) return } f(r.URL, &s) w.WriteHeader(http.StatusOK) } } func hookServer(f func(*url.URL, *watchPacket)) (*httptest.Server, error) { var err error m, err := watchMux(f) if err != nil { return nil, err } s := httptest.NewServer(m) return s, nil } func addWatch(tree *types.Tree, url string) error { uw := types.Watch{SuccessURL: url + "/user-watch"} if err := store.Save(&uw, tree); err != nil { return err } return nil }
true
8ca3f3089af3f3b4dfb3b4f54f58bb91fd46b99e
Go
bitmark-inc/data-store
/store/symptom_report.go
UTF-8
2,488
2.8125
3
[]
no_license
[]
no_license
package store import ( "context" "go.mongodb.org/mongo-driver/bson" "go.mongodb.org/mongo-driver/mongo" "go.mongodb.org/mongo-driver/mongo/options" ) type SymptomDailyReport struct { Date string `bson:"date"` Symptoms []SymptomStats `bson:"symptoms"` CheckinsNumPastThreeDays int `bson:"checkins_num_past_three_days"` } type SymptomStats struct { Name string `bson:"name"` Count int `bson:"count"` } func (m *mongoCommunityStore) AddSymptomDailyReports(ctx context.Context, reports []SymptomDailyReport) error { opts := options.Update().SetUpsert(true) for _, report := range reports { filter := bson.M{"date": report.Date} update := bson.M{ "$set": bson.M{ "symptoms": report.Symptoms, "checkins_num_past_three_days": report.CheckinsNumPastThreeDays, }, } _, err := m.Resource("symptom_reports").UpdateOne(ctx, filter, update, opts) if err != nil { return err } } return nil } type BucketAggregation struct { ID string `bson:"_id"` Buckets []Bucket `bson:"buckets"` } type Bucket struct { Name string `bson:"name" json:"name"` Value int `bson:"value" json:"value"` } // GetSymptomReportItems returns report items in the date range which starts at `limit` days ago, and ends at `end`. func (m *mongoCommunityStore) GetSymptomReportItems(ctx context.Context, end string, limit int64) (map[string][]Bucket, error) { pipeline := mongo.Pipeline{ AggregationMatch(bson.M{ "date": bson.M{ "$lte": end, }, }), AggregationSort("date", -1), AggregationLimit(limit), AggregationUnwind("$symptoms"), AggregationGroup("$symptoms.name", bson.D{ bson.E{ Key: "buckets", Value: bson.M{"$push": bson.M{ "name": "$date", "value": "$symptoms.count", }}, }, }), } cursor, err := m.Resource("symptom_reports").Aggregate(ctx, pipeline) if err != nil { return nil, err } results := make(map[string][]Bucket) for cursor.Next(ctx) { var aggItem BucketAggregation if err := cursor.Decode(&aggItem); err != nil { return nil, err } results[aggItem.ID] = aggItem.Buckets } return results, nil } func (m *mongoCommunityStore) FindLatestDailyReport(ctx context.Context) (*SymptomDailyReport, error) { var report SymptomDailyReport opts := options.FindOne().SetSort(bson.D{{"date", -1}}) err := m.Resource("symptom_reports").FindOne(ctx, bson.M{}, opts).Decode(&report) return &report, err }
true
9dd3c485425990c257697f4ef39094ddc9057587
Go
phisabella/LearingCoding
/Golang/basic/pointer.go
UTF-8
120
2.6875
3
[]
no_license
[]
no_license
package main import "fmt" func main() { a:=10 fmt.Println(&a) b:=20 ip:=&b fmt.Println(ip) fmt.Println(*ip) }
true
dea15dbc82b056204c5a4f88e234653b254b21e8
Go
hbyscx001/Fuck-Alg
/leetcode/实现-trie-前缀树/208.go
UTF-8
1,350
3.796875
4
[]
no_license
[]
no_license
package leetcode /* * @lc app=leetcode.cn id=208 lang=golang * * [208] 实现 Trie (前缀树) */ // @lc code=start type Trie struct { children map[rune]*Trie isEnd bool } /** Initialize your data structure here. */ func Constructor() Trie { instance := Trie{ isEnd: true, children: make(map[rune]*Trie), } return instance } /** Inserts a word into the trie. */ func (this *Trie) Insert(word string) { cur := this for _, r := range word { if _, ok := cur.children[r]; !ok { cur.children[r] = &Trie{ isEnd: false, children: make(map[rune]*Trie), } } cur = cur.children[r] } cur.isEnd = true } /** Returns if the word is in the trie. */ func (this *Trie) Search(word string) bool { cur := this for _, r := range word { if n, ok := cur.children[r]; ok { cur = n } else { return false } } return cur.isEnd } /** Returns if there is any word in the trie that starts with the given prefix. */ func (this *Trie) StartsWith(prefix string) bool { cur := this for _, r := range prefix { if n, ok := cur.children[r]; ok { cur = n } else { return false } } return true } /** * Your Trie object will be instantiated and called as such: * obj := Constructor(); * obj.Insert(word); * param_2 := obj.Search(word); * param_3 := obj.StartsWith(prefix); */ // @lc code=end
true
153a633abc3981b9a77299d5d37ade5f909472f8
Go
waljacq/practice-problems
/golang/ugly-numbers/main_test.go
UTF-8
696
3.0625
3
[]
no_license
[]
no_license
package main import ( "testing" ) func TestUgly(t *testing.T) { if !ugly(1) { t.Errorf("Ugly(1) returned false; wanted true") } if !ugly(6) { t.Errorf("Ugly(6) returned false; wanted true") } if ugly(7) { t.Errorf("Ugly(7) returned true; wanted false") } if !ugly(8) { t.Errorf("Ugly(8) returned false; wanted true") } if !ugly(10) { t.Errorf("Ugly(10) returned false; wanted true") } if ugly(14) { t.Errorf("Ugly(14) returned true; wanted false") } if ugly(-6) { t.Errorf("Ugly(-6) returned true; wanted false") } if ugly(33) { t.Errorf("Ugly(33) returned true; wanted false") } if ugly(42) { t.Errorf("Ugly(42) returned true; wanted false") } }
true
fc3cab402503b2737e3e64d7bdd9b39797130add
Go
sourcegraph/src-cli
/internal/batches/workspace/bind_workspace_test.go
UTF-8
10,040
2.828125
3
[ "Apache-2.0" ]
permissive
[ "Apache-2.0" ]
permissive
package workspace import ( "archive/zip" "context" "os" "path/filepath" "strings" "testing" "github.com/google/go-cmp/cmp" "github.com/sourcegraph/src-cli/internal/batches/graphql" "github.com/sourcegraph/src-cli/internal/batches/repozip" ) var repo = &graphql.Repository{ ID: "src-cli", Name: "github.com/sourcegraph/src-cli", DefaultBranch: &graphql.Branch{Name: "main", Target: graphql.Target{OID: "d34db33f"}}, } func zipUpFiles(t *testing.T, dir string, files map[string]string) string { f, err := os.CreateTemp(dir, "repo-zip-*") if err != nil { t.Fatal(err) } archivePath := f.Name() t.Cleanup(func() { os.Remove(archivePath) }) zw := zip.NewWriter(f) for name, body := range files { f, err := zw.Create(name) if err != nil { t.Fatal(err) } if _, err := f.Write([]byte(body)); err != nil { t.Fatal(err) } } zw.Close() f.Close() return archivePath } func TestDockerBindWorkspaceCreator_Create(t *testing.T) { // Create a zip file for all the other tests to use. fakeFilesTmpDir := t.TempDir() filesInZip := map[string]string{ "README.md": "# Welcome to the README\n", } archivePath := zipUpFiles(t, fakeFilesTmpDir, filesInZip) // Create "additional files" for the tests to use additionalFiles := map[string]string{ ".gitignore": "This is the gitignore\n", "another-file": "This is another file", } additionalFilePaths := map[string]string{} for name, content := range additionalFiles { f, err := os.CreateTemp(fakeFilesTmpDir, name+"-*") if err != nil { t.Fatal(err) } filePath := f.Name() t.Cleanup(func() { os.Remove(filePath) }) if _, err := f.Write([]byte(content)); err != nil { t.Fatal(err) } additionalFilePaths[name] = filePath f.Close() } t.Run("success", func(t *testing.T) { testTempDir := t.TempDir() archive := &fakeRepoArchive{mockPath: archivePath} creator := &dockerBindWorkspaceCreator{Dir: testTempDir} workspace, err := creator.Create(context.Background(), repo, nil, archive) if err != nil { t.Fatalf("unexpected error: %s", err) } haveUnzippedFiles, err := readWorkspaceFiles(workspace) if err != nil { t.Fatalf("error walking workspace: %s", err) } if !cmp.Equal(filesInZip, haveUnzippedFiles) { t.Fatalf("wrong files in workspace:\n%s", cmp.Diff(filesInZip, haveUnzippedFiles)) } }) t.Run("failure", func(t *testing.T) { testTempDir := t.TempDir() // Create an empty file (which is therefore a bad zip file). badZip, err := os.CreateTemp(testTempDir, "bad-zip-*") if err != nil { t.Fatal(err) } badZipFile := badZip.Name() t.Cleanup(func() { os.Remove(badZipFile) }) badZip.Close() badArchive := &fakeRepoArchive{mockPath: badZipFile} creator := &dockerBindWorkspaceCreator{Dir: testTempDir} if _, err := creator.Create(context.Background(), repo, nil, badArchive); err == nil { t.Error("unexpected nil error") } }) t.Run("additional files", func(t *testing.T) { testTempDir := t.TempDir() archive := &fakeRepoArchive{ mockPath: archivePath, mockAdditionalFilePaths: additionalFilePaths, } creator := &dockerBindWorkspaceCreator{Dir: testTempDir} workspace, err := creator.Create(context.Background(), repo, nil, archive) if err != nil { t.Fatalf("unexpected error: %s", err) } haveUnzippedFiles, err := readWorkspaceFiles(workspace) if err != nil { t.Fatalf("error walking workspace: %s", err) } wantFiles := map[string]string{} for name, content := range filesInZip { wantFiles[name] = content } for name, content := range additionalFiles { wantFiles[name] = content } if !cmp.Equal(wantFiles, haveUnzippedFiles) { t.Fatalf("wrong files in workspace:\n%s", cmp.Diff(wantFiles, haveUnzippedFiles)) } }) } func TestDockerBindWorkspace_ApplyDiff(t *testing.T) { // Create a zip file for all the other tests to use. fakeFilesTmpDir := t.TempDir() filesInZip := map[string]string{ "README.md": "# Welcome to the README\n", } archivePath := zipUpFiles(t, fakeFilesTmpDir, filesInZip) t.Run("success", func(t *testing.T) { diff := `diff --git README.md README.md index 02a19af..a84667f 100644 --- README.md +++ README.md @@ -1 +1,3 @@ # Welcome to the README + +This is a new line diff --git new-file.txt new-file.txt new file mode 100644 index 0000000..7bb2542 --- /dev/null +++ new-file.txt @@ -0,0 +1,2 @@ +check this out. this is a new file. +written on a computer. what a blast. ` wantFiles := map[string]string{ "README.md": "# Welcome to the README\n\nThis is a new line\n", "new-file.txt": "check this out. this is a new file.\nwritten on a computer. what a blast.\n", } testTempDir := t.TempDir() archive := &fakeRepoArchive{mockPath: archivePath} creator := &dockerBindWorkspaceCreator{Dir: testTempDir} workspace, err := creator.Create(context.Background(), repo, nil, archive) if err != nil { t.Fatalf("unexpected error: %s", err) } err = workspace.ApplyDiff(context.Background(), []byte(diff)) if err != nil { t.Fatalf("unexpected error: %s", err) } haveFiles, err := readWorkspaceFiles(workspace) if err != nil { t.Fatalf("error walking workspace: %s", err) } if !cmp.Equal(wantFiles, haveFiles) { t.Fatalf("wrong files in workspace:\n%s", cmp.Diff(wantFiles, haveFiles)) } }) t.Run("failure", func(t *testing.T) { diff := `lol this is not a diff but the computer doesn't know it yet, watch` testTempDir := t.TempDir() archive := &fakeRepoArchive{mockPath: archivePath} creator := &dockerBindWorkspaceCreator{Dir: testTempDir} workspace, err := creator.Create(context.Background(), repo, nil, archive) if err != nil { t.Fatalf("unexpected error: %s", err) } err = workspace.ApplyDiff(context.Background(), []byte(diff)) if err == nil { t.Fatalf("error is nil") } }) } func TestMkdirAll(t *testing.T) { // TestEnsureAll does most of the heavy lifting here; we're just testing the // MkdirAll scenarios here around whether the directory exists. // Create a shared workspace. base := mustCreateWorkspace(t) t.Run("directory exists", func(t *testing.T) { if err := os.MkdirAll(filepath.Join(base, "exist"), 0755); err != nil { t.Fatal(err) } if err := mkdirAll(base, "exist", 0750); err != nil { t.Errorf("unexpected non-nil error: %v", err) } if err := mustHavePerm(t, filepath.Join(base, "exist"), 0750); err != nil { t.Error(err) } if !isDir(t, filepath.Join(base, "exist")) { t.Error("not a directory") } }) t.Run("directory does not exist", func(t *testing.T) { if err := mkdirAll(base, "new", 0750); err != nil { t.Errorf("unexpected non-nil error: %v", err) } if err := mustHavePerm(t, filepath.Join(base, "new"), 0750); err != nil { t.Error(err) } if !isDir(t, filepath.Join(base, "new")) { t.Error("not a directory") } }) t.Run("directory exists, but is not a directory", func(t *testing.T) { f, err := os.Create(filepath.Join(base, "file")) if err != nil { t.Fatal(err) } f.Close() err = mkdirAll(base, "file", 0750) if _, ok := err.(errPathExistsAsFile); !ok { t.Errorf("unexpected error of type %T: %v", err, err) } }) } func TestEnsureAll(t *testing.T) { // Create a workspace. base := mustCreateWorkspace(t) // Create three nested directories with 0700 permissions. We'll use Chmod // explicitly to avoid any umask issues. if err := os.MkdirAll(filepath.Join(base, "a", "b", "c"), 0700); err != nil { t.Fatal(err) } dirs := []string{ filepath.Join(base, "a"), filepath.Join(base, "a", "b"), filepath.Join(base, "a", "b", "c"), } for _, dir := range dirs { if err := os.Chmod(dir, 0700); err != nil { t.Fatal(err) } } // Now we'll set them to 0750 and see what happens. if err := ensureAll(base, "a/b/c", 0750); err != nil { t.Errorf("unexpected non-nil error: %v", err) } for _, dir := range dirs { if err := mustHavePerm(t, dir, 0750); err != nil { t.Error(err) } } if err := mustHavePerm(t, base, 0700); err != nil { t.Error(err) } // Finally, let's ensure we get an error when we try to ensure a directory // that doesn't exist. if err := ensureAll(base, "d", 0750); err == nil { t.Errorf("unexpected nil error") } } func mustCreateWorkspace(t *testing.T) string { base := t.TempDir() // We'll explicitly set the base workspace to 0700 so we have a known // environment for testing. if err := os.Chmod(base, 0700); err != nil { t.Fatal(err) } return base } func mustGetPerm(t *testing.T, file string) os.FileMode { t.Helper() st, err := os.Stat(file) if err != nil { t.Fatal(err) } // We really only need the lower bits here. return st.Mode() & 0777 } func isDir(t *testing.T, path string) bool { t.Helper() st, err := os.Stat(path) if err != nil { t.Fatal(err) } return st.IsDir() } func readWorkspaceFiles(workspace Workspace) (map[string]string, error) { files := map[string]string{} wdir := workspace.WorkDir() err := filepath.Walk(*wdir, func(path string, info os.FileInfo, err error) error { if err != nil { return err } if info.IsDir() { return nil } content, err := os.ReadFile(path) if err != nil { return err } rel, err := filepath.Rel(*wdir, path) if err != nil { return err } if rel == ".git" || strings.HasPrefix(rel, ".git"+string(os.PathSeparator)) { return nil } files[rel] = string(content) return nil }) return files, err } var _ repozip.Archive = &fakeRepoArchive{} type fakeRepoArchive struct { mockPath string mockAdditionalFilePaths map[string]string } func (f *fakeRepoArchive) Ensure(context.Context) error { return nil } func (f *fakeRepoArchive) Close() error { return nil } func (f *fakeRepoArchive) Path() string { return f.mockPath } func (f *fakeRepoArchive) AdditionalFilePaths() map[string]string { if f.mockAdditionalFilePaths != nil { return f.mockAdditionalFilePaths } return map[string]string{} }
true
58948885f55a51c3c7cdffff77e2585a89504403
Go
azole/GoLang-Chinese
/Go Concurrency Patterns/01Generator.go
UTF-8
821
4.1875
4
[]
no_license
[]
no_license
/* Generator: 回傳 channel 的函式 * * Channels as a handle on a service * 函式回傳一個 channel,讓我可以跟它提供的服務溝通 */ package main import ( "fmt" "math/rand" "time" ) func boring(msg string) <-chan string { // 回傳一個只允許接收的channel c := make(chan string) go func() { for i := 0; ; i++ { c <- fmt.Sprintf("%s %d", msg, i) time.Sleep(time.Duration(rand.Intn(1e3)) * time.Millisecond) } }() return c } func main() { // c := boring("boring!") // for i := 0; i < 5; i++ { // fmt.Printf("You say: %q\n", <-c) // } azole := boring("azole") kate := boring("kate") for i := 0; i < 5; i++ { fmt.Println(<-azole) fmt.Println(<-kate) } // 這樣做一定是 azole, kate, azole, kate,... 的順序 fmt.Println("You're boring: I'm leaving.") }
true
54fb325eb3ac4939a2438804f33d66c093a1318f
Go
tudurom/oji_bot
/main.go
UTF-8
1,616
2.71875
3
[]
no_license
[]
no_license
package main import ( "encoding/json" "io/ioutil" "log" "net/http" "time" "github.com/sergi/go-diff/diffmatchpatch" "gopkg.in/telegram-bot-api.v4" ) type Config struct { Token string `json:"token"` ChannelName string `json:"channelName"` } var configPath = "config.json" var bot *tgbotapi.BotAPI const ojiPage = "http://olimpiada.info/oji2017/index.php?cid=rezultate" const sleepSeconds = 30 func (c *Config) readConfig(fp string) error { buf, err := ioutil.ReadFile(fp) if err != nil { return err } err = json.Unmarshal(buf, c) if err != nil { return err } return nil } func fetchWebPage(url string) string { resp, err := http.Get(url) if err == nil { buf, err := ioutil.ReadAll(resp.Body) resp.Body.Close() if err == nil { return string(buf) } else { return "" } } else { return "" } } func diffEqual(diff []diffmatchpatch.Diff) bool { for _, d := range diff { if d.Type != diffmatchpatch.DiffEqual { return false } } return true } func main() { var conf Config err := conf.readConfig(configPath) if err != nil { panic(err) } bot, err := tgbotapi.NewBotAPI(conf.Token) if err != nil { panic(err) } for true { page1 := fetchWebPage(ojiPage) log.Println("Zzz...") time.Sleep(sleepSeconds * time.Second) page2 := fetchWebPage(ojiPage) dmp := diffmatchpatch.New() diff := dmp.DiffMain(page1, page2, false) if !diffEqual(diff) { log.Println("Sending message") msg := tgbotapi.NewMessageToChannel(conf.ChannelName, "oji_bot: S-a actualizat pagina!") bot.Send(msg) } else { log.Println("Pages equal") } } }
true
947bed5bc1c8613fecec622924ed87c6025e7667
Go
heypin/learning
/service/homework_publish.go
UTF-8
1,879
2.671875
3
[]
no_license
[]
no_license
package service import ( "github.com/jinzhu/gorm" "learning/models" "time" ) type HomeworkPublishService struct { Id uint ClassId uint HomeworkLibId uint BeginTime time.Time EndTime time.Time Resubmit *uint } func (s *HomeworkPublishService) PublishHomework() (uint, error) { publish := models.HomeworkPublish{ ClassId: s.ClassId, HomeworkLibId: s.HomeworkLibId, BeginTime: s.BeginTime, EndTime: s.EndTime, Resubmit: s.Resubmit, } if ok, err := models.HasPublishHomework(s.ClassId, s.HomeworkLibId); ok { return 0, nil } else if !ok && err == nil { if id, err := models.AddHomeworkPublish(publish); err == nil { return id, nil } else { return 0, err } } else { return 0, err } } func (s *HomeworkPublishService) GetHomeworkPublishById() (publish *models.HomeworkPublish, err error) { return models.GetHomeworkPublishById(s.Id) } func (s *HomeworkPublishService) UpdateHomeworkPublishById() (err error) { publish := models.HomeworkPublish{ Model: gorm.Model{ID: s.Id}, BeginTime: s.BeginTime, EndTime: s.EndTime, Resubmit: s.Resubmit, } err = models.UpdateHomeworkPublishById(publish) return } func (s *HomeworkPublishService) GetHomeworkPublishesByClassId() (publishes []*models.HomeworkPublish, err error) { publishes, err = models.GetHomeworkPublishesByClassId(s.ClassId) if err != nil { return publishes, err } else { for _, v := range publishes { v.SubmitCount, _ = models.GetHomeworkSubmitCountByPublishId(v.ID) v.UnMarkCount, _ = models.GetHomeworkUnmarkedCountByPublishId(v.ID) } return publishes, nil } } func (s *HomeworkPublishService) GetHomeworkPublishesWithSubmitByClassId(userId uint) (publishes []*models.HomeworkPublish, err error) { publishes, err = models.GetHomeworkPublishesWithSubmitByClassId(s.ClassId, userId) return }
true
fda7452a3f86baa9a6129aa4d217cb8466be5f6e
Go
putaosuan/GolangTest
/basic/map_demo03.go
UTF-8
807
3.96875
4
[]
no_license
[]
no_license
package main import ( "fmt" ) func main40() { /* map和slice的结合使用: */ map1:=make(map[string]string) map1["name"]="王二狗" map1["age"]="30" map1["sex"]="男" map1["address"]="北京市" fmt.Println(map1) map2:=make(map[string]string) map2["name"]="李小华" map2["age"]="20" map2["sex"]="女" map2["address"]="上海市" fmt.Println(map2) map3:=map[string]string{"name":"ruby","age":"25","sex":"女","address":"天津市"} fmt.Println(map3) //将map存入slice中 s1:=make([]map[string]string,0,3) s1 = append(s1, map1) s1 = append(s1, map2) s1 = append(s1, map3) //遍历切片 for i,v:=range s1 { fmt.Printf("第%d个人的信息是:\n",i+1) fmt.Printf("\t姓名:%s,性别:%s,年龄:%s,地址:%s\n",v["name"],v["sex"],v["age"],v["address"]) } }
true
62f7990bcd3d1a8e52f54ad08f43b81c9301f952
Go
bater/golang_example
/day24/main.go
UTF-8
629
4.21875
4
[]
no_license
[]
no_license
package main import "fmt" func main() { var i *int // 宣告i是一個int的指標,目前還不知道會指向哪邊 a := 10 // a佔用了一個記憶體空間 i = &a // 將i指到a的記憶體位置 fmt.Println(i) // i所指到的記憶體位置 fmt.Println(*i) // *代表顯示該記憶體位置的值 // 宣告一個空的int n := new(int) // 直接把值指向記憶體位置 *n = 2 fmt.Println(n) fmt.Println(*n) foo_value(*n) foo_point(n) } func foo_value(x int) { fmt.Println(&x) // function內x的記憶體位置 } func foo_point(x *int) { fmt.Println(x) // function內x的記憶體位置 }
true
68f521abff8b62677a199e02ac17aa9e14013d9f
Go
cthulhu/tw-trend
/service/tokenizer/tokenizer.go
UTF-8
985
3.03125
3
[]
no_license
[]
no_license
package tokenizer import ( "sort" "strings" "gopkg.in/jdkato/prose.v2" ) func Tokenize(str string) ([]string, error) { tokens := []string{} doc, err := prose.NewDocument(str) if err != nil { return tokens, err } for _, tok := range doc.Tokens() { if isAllowedTag(tok.Tag) && isAllowedToken(tok.Text) { tokens = append(tokens, strings.ToLower(tok.Text)) } } sort.Strings(tokens) return tokens, err } var allowedTags = [...]string{"MD", "NN", "NNP", "NNPS", "NNS", "PDT", "POS", "PRP", "PRP$", "RB", "RBR", "RBS", "RP", "SYM", "TO", "UH", "VB", "VBD", "VBG", "VBN", "VBP", "VBZ", "WDT", "WP", "WP$", "WRB"} func isAllowedTag(tag string) bool { for _, aTag := range allowedTags { if tag == aTag { return true } } return false } func isAllowedToken(token string) bool { if strings.Index(token, "@") == 0 { return false } if strings.Index(token, "http") == 0 { return false } if strings.Index(token, "#") == 0 { return false } return true }
true
633f9977bf37fa8ec33db9c85b40012287533636
Go
sganderson/go-url-checker
/main.go
UTF-8
2,641
2.90625
3
[ "MIT" ]
permissive
[ "MIT" ]
permissive
package main import ( "bufio" "crypto/tls" "database/sql" "flag" "fmt" "log" "net/http" "os" "runtime" "sync" "time" _ "github.com/mattn/go-sqlite3" ) func requestWorker(domains chan string, wg *sync.WaitGroup, db *sql.DB) { defer wg.Done() //defer db.Close() //use this to disable security check validation tr := &http.Transport{ TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, } httpClient := &http.Client{Transport: tr} //httpClient := &http.Client{} for domain := range domains { response, err := httpClient.Head(domain) var statusCode int if err == nil { statusCode = response.StatusCode log.Println(fmt.Sprintf("[%s] %d", domain, response.StatusCode)) } else { statusCode = -1 log.Println(fmt.Sprintf("[%s] HTTP Error %s", domain, err.Error())) } //log.Println(fmt.Sprintf("INSERT INTO sites(id, domain, code) values(\"%s\", %d)", domain, statusCode)) _, err = db.Exec(fmt.Sprintf("INSERT INTO sites(domain, code, time) values(\"%s\", %d, \"%s\")", domain, statusCode, time.Now())) if err != nil { log.Fatalln("could not insert row:", err) } } } func initDataBase() *sql.DB { db, err := sql.Open("sqlite3", "./sites.db") if err != nil { log.Fatal(err) } rows, err := db.Query("SELECT name FROM sqlite_master WHERE type='table' AND name='sites'") if err != nil { log.Panic("%q: \n", err) os.Exit(1) } defer rows.Close() var name string for rows.Next() { rows.Scan(&name) //log.Println(name) } if name != "sites" { sqlStmt := ` DELETE FROM sites; DROP TABLE sites; ` db.Exec(sqlStmt) if err != nil { log.Panic("%q: %s\n", err, sqlStmt) os.Exit(1) } sqlStmt = ` CREATE TABLE sites (site_id INTEGER PRIMARY KEY AUTOINCREMENT, domain TEXT NOT NULL, code INTEGER, time TEXT NOT NULL); ` _, err = db.Exec(sqlStmt) if err != nil { log.Panic("%q: %s\n", err, sqlStmt) os.Exit(1) } } return db } func main() { runtime.GOMAXPROCS(runtime.NumCPU()) var threadsCount int flag.IntVar(&threadsCount, "threads", 15, "Count of used threads (goroutines)") file, err := os.Open("domains_tc") if err != nil { log.Fatal(err) } defer file.Close() scanner := bufio.NewScanner(file) taskChannel := make(chan string, 10000) go func() { for scanner.Scan() { domain := fmt.Sprintf("%s", scanner.Text()) taskChannel <- domain } if err := scanner.Err(); err != nil { log.Fatal(err) } close(taskChannel) }() db := initDataBase() wg := new(sync.WaitGroup) for i := 0; i < threadsCount; i++ { wg.Add(1) go requestWorker(taskChannel, wg, db) } wg.Wait() db.Close() }
true
800c3976bb70bca0c70be277099e66517f5c3746
Go
miromotl/gol
/gol.go
UTF-8
5,366
3.328125
3
[ "MIT" ]
permissive
[ "MIT" ]
permissive
// Implementing Conway's Game Of Life // ---------------------------------- // // Using a map for storing the current state of the world. // // We are printing the successive populations in a format that can be fed // to gnuplot and creating in this way an animated view of the population. // // This is just an exercise for using maps in go! Do not take this // too serious... // // To see the simulation in gnuplot, call the program like this: // ./gol.exe | gnuplot --persist package main import ( "flag" "fmt" "strings" "strconv" "os" "math/rand" "runtime" "time" ) // We use as many go routines as workes as there are cores/processors // in the computer. var cntWorkers = runtime.NumCPU() // We are storing the cells (alive or dead) in a map. The keys are the Cartesian // coordinates of the cells and the values are the properties of the cells, // namely their state and number of alive neighbours. // A cell has its state, and its number of life neighbours type Cell struct { alive bool n int } // The coordinates are plain 2-d cartesian coordinates type Coord struct { x int y int } // The world is a map of Coord and Cell type World map[Coord]Cell // Inflate inflates the world with dead cells surrounding // the live cells func (world World) Inflate() World { var newWorld World newWorld = make(World) for coord, cell := range world { newWorld[coord] = cell for i := -1; i < 2; i++ { for j := -1; j < 2; j++ { c := Coord{coord.x + i, coord.y + j} if _, found := newWorld[c]; !found { newWorld[c] = Cell{false, 0} } } } } return newWorld } // Deflate deflates the world: only the live cells remain func (world World) Deflate() World { var newWorld World newWorld = make(World) for coord, cell := range world { if cell.alive { newWorld[coord] = cell } } return newWorld } // CountLiveNeighbours counts for each cell in the world its neighbouring // alive cells and updates its counter func (world World) CountLiveNeighbours() World { var newWorld World newWorld = make(World) for coord, cell := range world { n := 0 for i := -1; i < 2; i++ { for j := -1; j < 2; j++ { c := Coord{coord.x + i, coord.y + j} if (i != 0 || j != 0) && world[c].alive { n = n+1 } } } newWorld[coord] = Cell{cell.alive, n} } return newWorld } // ApplyRules applies the rules to each cell of the world. This determines // the fate of the cell for the next tick. func (world World) ApplyRules() World { var newWorld World newWorld = make(World) // apply the rules of the game to each cell for coord, cell := range world { if cell.alive { if 1 < cell.n && cell.n < 4 { newWorld[coord] = Cell{true, 0} } } else { if cell.n == 3 { newWorld[coord] = Cell{true, 0} } } } return newWorld } // Tick computes the next generation of live cells in the world func (world World) Tick() World { return world.Inflate().CountLiveNeighbours().ApplyRules().Deflate() } // gnuplotHeader prints the header for gnuplot func gnuplotHeader(d int) { fmt.Printf("unset key; set xrange[-%[1]d:%[1]d]\n", d/2) fmt.Printf("set yrange[-%[1]d:%[1]d]\n", d/2) fmt.Println("set style line 1 lc rgb '#0060ad' pt 7") } // gnuplotWorld prints the coordinates of the cells in the world func gnuplotWorld(world World) { fmt.Println("plot '-' with points ls 1") for coord := range world { fmt.Printf("%d, %d\n", coord.x, coord.y) } fmt.Println("e") } func main() { // Handle the command line arguments ticks, size, pattern := handleCommandLine() // start := time.Now() // The world var world World world = make(World) for _, coord := range pattern { world[coord] = Cell{true, 0} } gnuplotHeader(size) // gnuplotWorld(world) for i := 0; i < ticks; i++ { world = world.Tick() gnuplotWorld(world) } // elapsed := time.Since(start) // fmt.Printf("Elapsed: %s", elapsed) } func handleCommandLine() (ticks, size int, pattern []Coord) { // Define our own usage message, overwriting the default one flag.Usage = func() { fmt.Fprint(os.Stderr, "Usage: cgol [flags] [pattern] | gnuplot --persist\n") flag.PrintDefaults() } // Define the command line flags flag.IntVar(&ticks, "ticks", 10, "number of iterations running the game") flag.IntVar(&size, "size", 50, "size of the visible world in x and y direction") var random *bool = flag.Bool("random", false, "generate a random pattern to start with") var coordinatesOpt *string = flag.String("coordinates", "1,0;0,1;1,1;1,2;2,2", "semi-colon-separated list of coordinates") flag.Parse() // Create a ranodm starting pattern or use the r-pentomino pattern if *random { // Generate a random pattern pattern = []Coord{} rand.Seed(time.Now().UTC().UnixNano()) for i := 0; i < size; i++ { for j := 0; j < size; j++ { if rand.Intn(100) < 20 { pattern = append(pattern, Coord{i - size/2, j - size/2}) } } } } else { coordinates := strings.Split(*coordinatesOpt, ";") pattern = make([]Coord, len(coordinates)) for idx := range coordinates { xy := strings.Split(coordinates[idx], ",") x, err := strconv.Atoi(xy[0]) if err != nil { fmt.Println(err) os.Exit(1) } y, err := strconv.Atoi(xy[1]) if err != nil { fmt.Println(err) os.Exit(1) } pattern[idx] = Coord{x, y} } } return ticks, size, pattern }
true
d4203f5a4e05b1b7c93e6799efb15f2e0778bd4d
Go
AJarombek/global-aws-infrastructure
/test-k8s/jenkins_test.go
UTF-8
8,941
2.765625
3
[]
no_license
[]
no_license
/** * Writing tests of Kubernetes infrastructure in the 'jenkins' namespace with the Go K8s client library. * Go after the one who's love you desire. You have everything you need and you should believe in yourself :) * Author: Andrew Jarombek * Date: 7/5/2020 */ package main import ( "context" "fmt" k8sfuncs "github.com/ajarombek/cloud-modules/kubernetes-test-functions" v1 "k8s.io/api/core/v1" v1meta "k8s.io/apimachinery/pkg/apis/meta/v1" "testing" ) // TestJenkinsNamespaceDeploymentCount determines if the number of 'Deployment' objects in the 'jenkins' namespace is // as expected. func TestJenkinsNamespaceDeploymentCount(t *testing.T) { k8sfuncs.ExpectedDeploymentCount(t, ClientSet, "jenkins", 1) } // TestJenkinsDeploymentExists determines if a deployment exists in the 'jenkins' namespace with the name // 'jenkins-deployment'. func TestJenkinsDeploymentExists(t *testing.T) { k8sfuncs.DeploymentExists(t, ClientSet, "jenkins-deployment", "jenkins") } // TestJenkinsDeploymentExists determines if the 'jenkins-deployment' is running error free. func TestJenkinsDeploymentErrorFree(t *testing.T) { deployment, err := ClientSet.AppsV1().Deployments("jenkins").Get(context.TODO(), "jenkins-deployment", v1meta.GetOptions{}) if err != nil { panic(err.Error()) } deploymentConditions := deployment.Status.Conditions k8sfuncs.ConditionStatusMet(t, deploymentConditions, "Available", "True") k8sfuncs.ConditionStatusMet(t, deploymentConditions, "Progressing", "True") totalReplicas := deployment.Status.Replicas var expectedTotalReplicas int32 = 1 k8sfuncs.ReplicaCountAsExpected(t, expectedTotalReplicas, totalReplicas, "total number of replicas") availableReplicas := deployment.Status.AvailableReplicas var expectedAvailableReplicas int32 = 1 k8sfuncs.ReplicaCountAsExpected(t, expectedAvailableReplicas, availableReplicas, "number of available replicas") readyReplicas := deployment.Status.ReadyReplicas var expectedReadyReplicas int32 = 1 k8sfuncs.ReplicaCountAsExpected(t, expectedReadyReplicas, readyReplicas, "number of ready replicas") unavailableReplicas := deployment.Status.UnavailableReplicas var expectedUnavailableReplicas int32 = 0 k8sfuncs.ReplicaCountAsExpected(t, expectedUnavailableReplicas, unavailableReplicas, "number of unavailable replicas") } // TestJenkinsNamespaceIngressCount determines if the number of 'Ingress' objects in the 'jenkins' namespace is // as expected. func TestJenkinsNamespaceIngressCount(t *testing.T) { expectedIngressCount := 1 ingresses, err := ClientSet.NetworkingV1().Ingresses("jenkins").List(context.TODO(), v1meta.ListOptions{}) if err != nil { panic(err.Error()) } var ingressCount = len(ingresses.Items) if ingressCount == expectedIngressCount { t.Logf( "A single Ingress object exists in the 'jenkins' namespace. Expected %v, got %v.", expectedIngressCount, ingressCount, ) } else { t.Errorf( "An unexpected number of Ingress objects exist in the 'jenkins' namespace. Expected %v, got %v.", expectedIngressCount, ingressCount, ) } } // TestJenkinsIngressExists determines if an ingress object exists in the 'jenkins' namespace with the name // 'jenkins-ingress'. func TestJenkinsIngressExists(t *testing.T) { expectedIngressName := "jenkins-ingress" ingress, err := ClientSet.NetworkingV1().Ingresses("jenkins").Get(context.TODO(), "jenkins-ingress", v1meta.GetOptions{}) if err != nil { panic(err.Error()) } if ingress.Name == expectedIngressName { t.Logf( "Jenkins Ingress exists with the expected name. Expected %v, got %v.", expectedIngressName, ingress.Name, ) } else { t.Errorf( "Jenkins Ingress does not exist with the expected name. Expected %v, got %v.", expectedIngressName, ingress.Name, ) } } // TestJenkinsIngressAnnotations determines if the 'jenkins-ingress' Ingress object contains the expected annotations. func TestJenkinsIngressAnnotations(t *testing.T) { ingress, err := ClientSet.NetworkingV1().Ingresses("jenkins").Get(context.TODO(), "jenkins-ingress", v1meta.GetOptions{}) if err != nil { panic(err.Error()) } annotations := ingress.Annotations // Kubernetes Ingress class and ExternalDNS annotations k8sfuncs.AnnotationsEqual(t, annotations, "kubernetes.io/ingress.class", "alb") k8sfuncs.AnnotationsEqual(t, annotations, "external-dns.alpha.kubernetes.io/hostname", "jenkins.jarombek.io,www.jenkins.jarombek.io") // ALB Ingress annotations k8sfuncs.AnnotationsEqual(t, annotations, "alb.ingress.kubernetes.io/actions.ssl-redirect", "{\"Type\": \"redirect\", \"RedirectConfig\": {\"Protocol\": \"HTTPS\", \"Port\": \"443\", \"StatusCode\": \"HTTP_301\"}}") k8sfuncs.AnnotationsEqual(t, annotations, "alb.ingress.kubernetes.io/backend-protocol", "HTTP") k8sfuncs.AnnotationsEqual(t, annotations, "alb.ingress.kubernetes.io/scheme", "internet-facing") k8sfuncs.AnnotationsEqual(t, annotations, "alb.ingress.kubernetes.io/listen-ports", "[{\"HTTP\":80}, {\"HTTPS\":443}]") k8sfuncs.AnnotationsEqual(t, annotations, "alb.ingress.kubernetes.io/healthcheck-path", "/login") k8sfuncs.AnnotationsEqual(t, annotations, "alb.ingress.kubernetes.io/healthcheck-protocol", "HTTP") k8sfuncs.AnnotationsEqual(t, annotations, "alb.ingress.kubernetes.io/target-type", "instance") k8sfuncs.AnnotationsEqual(t, annotations, "alb.ingress.kubernetes.io/tags", "Name=jenkins-load-balancer,Application=jenkins,Environment=production") // ALB Ingress annotations pattern matching uuidPattern := "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}" certificateArnPattern := fmt.Sprintf("arn:aws:acm:us-east-1:739088120071:certificate/%s", uuidPattern) certificatesPattern := fmt.Sprintf("^%s,%s$", certificateArnPattern, certificateArnPattern) k8sfuncs.AnnotationsMatchPattern(t, annotations, "alb.ingress.kubernetes.io/certificate-arn", certificatesPattern) sgPattern := "^sg-[0-9a-f]+$" k8sfuncs.AnnotationsMatchPattern(t, annotations, "alb.ingress.kubernetes.io/security-groups", sgPattern) subnetsPattern := "^subnet-[0-9a-f]+,subnet-[0-9a-f]+$" k8sfuncs.AnnotationsMatchPattern(t, annotations, "alb.ingress.kubernetes.io/subnets", subnetsPattern) expectedAnnotationsLength := 13 annotationLength := len(annotations) if expectedAnnotationsLength == annotationLength { t.Logf( "Jenkins Ingress has the expected number of annotations. Expected %v, got %v.", expectedAnnotationsLength, annotationLength, ) } else { t.Errorf( "Jenkins Ingress does not have the expected number of annotations. Expected %v, got %v.", expectedAnnotationsLength, annotationLength, ) } } // TestJenkinsNamespaceServiceCount determines if the expected number of Service objects exist in the 'jenkins' // namespace. func TestJenkinsNamespaceServiceCount(t *testing.T) { expectedServiceCount := 2 services, err := ClientSet.CoreV1().Services("jenkins").List(context.TODO(), v1meta.ListOptions{}) if err != nil { panic(err.Error()) } var serviceCount = len(services.Items) if serviceCount == expectedServiceCount { t.Logf( "A single Service object exists in the 'jenkins' namespace. Expected %v, got %v.", expectedServiceCount, serviceCount, ) } else { t.Errorf( "An unexpected number of Service objects exist in the 'jenkins' namespace. Expected %v, got %v.", expectedServiceCount, serviceCount, ) } } // TestJenkinsServiceExists determines if a NodePort Service with the name 'jenkins-service' exists in the 'jenkins' // namespace. func TestJenkinsServiceExists(t *testing.T) { service, err := ClientSet.CoreV1().Services("jenkins").Get(context.TODO(), "jenkins-service", v1meta.GetOptions{}) if err != nil { panic(err.Error()) } var expectedServiceType v1.ServiceType = "NodePort" if service.Spec.Type == expectedServiceType { t.Logf( "A 'jenkins-service' Service object exists of the expected type. Expected %v, got %v.", expectedServiceType, service.Spec.Type, ) } else { t.Errorf( "A 'jenkins-service' Service object does not exist of the expected type. Expected %v, got %v.", expectedServiceType, service.Spec.Type, ) } } // TestJenkinsJNLPServiceExists determines if a NodePort Service with the name 'jenkins-jnlp-service' exists in the // 'jenkins' namespace. func TestJenkinsJNLPServiceExists(t *testing.T) { service, err := ClientSet.CoreV1().Services("jenkins").Get(context.TODO(), "jenkins-jnlp-service", v1meta.GetOptions{}) if err != nil { panic(err.Error()) } var expectedServiceType v1.ServiceType = "ClusterIP" if service.Spec.Type == expectedServiceType { t.Logf( "A 'jenkins-jnlp-service' Service object exists of the expected type. Expected %v, got %v.", expectedServiceType, service.Spec.Type, ) } else { t.Errorf( "A 'jenkins-jnlp-service' Service object does not exist of the expected type. Expected %v, got %v.", expectedServiceType, service.Spec.Type, ) } }
true
1e48b3a07f83501897bf310ba82871009b2f17bd
Go
priaalamatpalsu/latihango
/src/2019-01/14-parsefloat/parsefloat.go
UTF-8
530
3.296875
3
[]
no_license
[]
no_license
package main import ( "bufio" "fmt" "os" "strconv" "strings" ) func main() { reader := bufio.NewReader(os.Stdin) fmt.Print("Enter text: ") text, _ := reader.ReadString('\n') fmt.Print(text) var point, _ = strconv.ParseFloat(strings.TrimSpace(text), 64) fmt.Printf("point is %f \n", point) if percent := point / 100; percent >= 100 { fmt.Printf("%.2f%s perfect!\n", percent, "%") } else if percent >= 70 { fmt.Printf("%.2f%s good\n", percent, "%") } else { fmt.Printf("%.2f%s not bad\n", percent, "%") } }
true
0c34dbf50fb03158fe596d0846ad833a4bc6959b
Go
hearb/hearb
/mysql/mysql.go
UTF-8
719
2.671875
3
[ "MIT" ]
permissive
[ "MIT" ]
permissive
package mysql import ( "database/sql" "io/ioutil" _ "github.com/go-sql-driver/mysql" "gopkg.in/gorp.v1" "gopkg.in/yaml.v2" ) type ( dbconfig struct { Dialect string DataSource string } config struct { Development dbconfig } ) var db *gorp.DbMap func DB() *gorp.DbMap { return db } func NewDB() error { rawConf, err := ioutil.ReadFile("dbconfig.yml") if err != nil { return err } conf := &config{} if err = yaml.Unmarshal(rawConf, conf); err != nil { return err } pdb, err := sql.Open(conf.Development.Dialect, conf.Development.DataSource) if err != nil { return err } db = &gorp.DbMap{ Db: pdb, Dialect: &gorp.MySQLDialect{}, } defer db.Db.Close() return nil }
true
3769148aaa90960e0ec59f472cf53cfeb427d131
Go
rifqi-arief/GoToyota
/model/opration.model.go
UTF-8
1,894
2.71875
3
[]
no_license
[]
no_license
package model import ( "fmt" "strings" "time" "github.com/GoToyota/object" "github.com/GoToyota/utils" ) func AddOpration(opration []*Oprasional) (map[string]interface{}, error) { utils.Logging.Println("add opration") utils.Logging.Println(opration) valueStrings := make([]string, 0, len(opration)) valueArgs := make([]interface{}, 0, len(opration)*3) dt := time.Now() for i, post := range opration { valueStrings = append(valueStrings, fmt.Sprintf("($%d, $%d, $%d, $%d, $%d)", i*5+1, i*5+2, i*5+3, i*5+4, i*5+5)) valueArgs = append(valueArgs, post.IdUser) valueArgs = append(valueArgs, dt.Format("01-02-2006 15:04:05")) valueArgs = append(valueArgs, post.Hari) valueArgs = append(valueArgs, post.Buka) valueArgs = append(valueArgs, post.Tutup) } stmt := fmt.Sprintf("insert into oprasional (id_bengkel, created_at,hari, buka, tutup) values %s", strings.Join(valueStrings, ",")) utils.Logging.Println(stmt) _, err := db.Exec(stmt, valueArgs...) if err != nil { return nil, err } response := utils.Message(true, "Success insert oprational") return response, nil } func GetOpration(idBengkel int) map[string]interface{} { query := fmt.Sprintf(` select coalesce(nullif(hari,''),' ') as hari , coalesce(nullif(buka,''),' ') as "buka", coalesce(nullif(tutup,''),' ') as "tutup" from oprasional where id_bengkel = '%v'`, idBengkel) utils.Logging.Println(query) var opr []object.Oprasional rows, err := db.Query(query) if err != nil { return utils.Message(false, "opration.model.go, line:54 "+err.Error()) } for rows.Next() { var o object.Oprasional err = rows.Scan( &o.Hari, &o.Buka, &o.Tutup, ) if err != nil { return utils.Message(false, "opratin.model.go, line:68 "+err.Error()) } opr = append(opr, o) } response := utils.Message(true, "Success") response["response"] = opr return response } //edit opration
true
fb19602250dc294cedd1214d7b2e0983f0246bc3
Go
duzhi5368/FKGoTrojan
/src/FKTrojan/client_tools/scan_dir/scan_test.go
UTF-8
2,832
2.859375
3
[]
no_license
[]
no_license
package main import ( . "FKTrojan/common" "bufio" "fmt" "io/ioutil" "os" "os/exec" "regexp" "testing" "time" ) func init() { fmt.Println("PLEASE NOTE : this test may last for a very long time") } func TestScan(t *testing.T) { f := func(dir string, depth uint) ([]Item, error) { begin := time.Now() defer func() { cost := time.Since(begin).Seconds() t.Logf("scan cost %.3f", cost) }() d, err := Scan(dir, depth) if err != nil { t.Error(err) } t.Logf("dir %s has %d items\n", dir, len(d)) //t.Log(d[:]) return d, err } f("c:/", 1) d, err := f("d:/", 1) if err == nil { for _, i := range d { if i.ItemType == DIR_ITEM { dirfiles, _ := f(i.FullPath, DEPTH_ALL) files, _ := getSubItemByFind(i.FullPath, DEPTH_ALL) if len(dirfiles) != len(files)-1 { // scan_test.go:41: dir(d:/System Volume Information) len(0) != (4) // 测试发现,上面的无法通过,find命令可以获取到,scan函数不能 t.Errorf("dir(%s) len(%d) != (%d)\n", i.FullPath, len(dirfiles), len(files)-1) fmt.Printf("dir(%s) Failed\n", i.FullPath) } else { fmt.Printf("dir(%s) OK\n", i.FullPath) } } } } } func TestGetSubItemByFind(t *testing.T) { f, err := getSubItemByFind("d:/DNSModifier - 副本", 2) t.Log(err, f) } func TestShellRunCmd(t *testing.T) { r, err := shellRunCmd("find /d/git/") //r, err := shellRunCmd("pwd") //r, err := shellRunCmd("date") if err != nil { t.Error(err) return } t.Log(r) } // 以下测试代码,使用的是shell下find命令,安装了git,就会有sh.exe func shellRunCmd(cmdString string) ([]string, error) { //fmt.Println(cmdString) shExeFullPath := "D:\\Program Files\\Git\\bin\\sh.exe" if !Exist(shExeFullPath) { fmt.Printf("%s not exist, please find and reset it\n", shExeFullPath) os.Exit(1) } tmpFile := os.Getenv("temp") + "\\find.sh" //fmt.Println(tmpFile) d1 := []byte(cmdString) err := ioutil.WriteFile(tmpFile, d1, 0644) cmd := exec.Command(shExeFullPath, "/tmp/find.sh") out, err := cmd.StdoutPipe() if err != nil { return nil, err } err = cmd.Start() if err != nil { return nil, err } defer cmd.Wait() scanner := bufio.NewScanner(out) ret := make([]string, 0) for scanner.Scan() { ret = append(ret, scanner.Text()) } return ret, nil } func dirToUnix(dir string) string { // 路径中的空格()需要转义才能在unix环境中使用 var re = regexp.MustCompile(`([\(\) ])`) dir = re.ReplaceAllString(dir, `\$1`) return "/" + dir[0:1] + dir[2:] } func getSubItemByFind(dir string, depth uint) (dirfiles []string, err error) { commonCmd := fmt.Sprintf("find %s ", dirToUnix(dir)) if depth != DEPTH_ALL { commonCmd += fmt.Sprintf(" -maxdepth %d ", depth-1) } Cmd := commonCmd //+ " -type d" dirfiles, err = shellRunCmd(Cmd) return }
true
ce72a573c5cf1b3ed60beab6b8047430f407055f
Go
kgori/mygolang
/rosalind/problems/problemHamming.go
UTF-8
974
3.15625
3
[]
no_license
[]
no_license
package main import ( "bufio" "errors" "fmt" "io" "os" "github.com/kgori/mygolang/rosalind" ) func main() { var line1, line2 string var line []byte var prefix bool var err error if len(os.Args) < 2 { fmt.Println("no filename given") return } f, err := os.Open(os.Args[1]) if err != nil { fmt.Println(err) return } defer f.Close() reader := bufio.NewReader(f) infiniteLoop: for { line, prefix, err = reader.ReadLine() switch { case err != nil: if err == io.EOF { break infiniteLoop } case prefix: err = errors.New("Line too long") fmt.Println(string(line[:100])) break infiniteLoop case len(line) == 0: continue case line1 <= "": line1 = string(line) case line1 > "" && line2 <= "": line2 = string(line) case line1 > "" && line2 > "": break infiniteLoop default: err = errors.New("No lines found") break infiniteLoop } } d := rosalind.Hamming(line1, line2) fmt.Printf("%d\n", d) }
true
553d79451b7ad41236e91173deccc23a6ad0c1ad
Go
imorte/UwdBot
/database/user.go
UTF-8
4,646
3.1875
3
[]
no_license
[]
no_license
package database import ( "context" "time" ) type User struct { ID uint64 UserID uint64 Username string Coins int Reputation int Blacklist bool IsAdmin bool WeaponsPower int ActiveDate time.Time Activity int } type Users []User func (u *User) CreateNewUser() (uint64, error) { row := db.QueryRow( context.Background(), "INSERT INTO users (username, userID, coins) VALUES ($1, $2, 100) RETURNING id", u.Username, u.UserID, ) err := row.Scan(&u.ID) if err != nil { return 0, err } return u.ID, nil } func (u *User) CountUsersWithID(id int) (int, error) { var count int row := db.QueryRow( context.Background(), "SELECT COUNT (*) FROM users WHERE userID = $1", id, ) err := row.Scan( &count, ) if err != nil { return 0, err } return count, nil } func (u *User) DeleteUser(id int) (int, error) { var count int row := db.QueryRow( context.Background(), "DELETE FROM users WHERE userID = $1", id, ) err := row.Scan( &count, ) if err != nil { return 0, err } return count, nil } func (u *User) FindUserByID(id int) (User, error) { row := db.QueryRow( context.Background(), "SELECT id, username, userid, blacklist, isadmin, coins, reputation, weapons_power, activ_date, activity FROM users WHERE userID = $1", id, ) err := row.Scan( &u.ID, &u.Username, &u.UserID, &u.Blacklist, &u.IsAdmin, &u.Coins, &u.Reputation, &u.WeaponsPower, &u.ActiveDate, &u.Activity, ) if err != nil { return User{}, err } return *u, nil } func (u *User) FindUserByUsername(username string) (User, error) { row := db.QueryRow( context.Background(), "SELECT id, username, userid, blacklist, isadmin, coins, reputation, weapons_power, activ_date, activity FROM users WHERE username = $1", username, ) err := row.Scan( &u.ID, &u.Username, &u.UserID, &u.Blacklist, &u.IsAdmin, &u.Coins, &u.Reputation, &u.WeaponsPower, &u.ActiveDate, &u.Activity, ) if err != nil { return User{}, err } return *u, nil } func (u *User) GetTopUsers(count int) (Users, error) { rows, err := db.Query( context.Background(), "SELECT id, username, userid, blacklist, isadmin, coins, reputation, weapons_power FROM users ORDER BY reputation desc, coins DESC LIMIT $1", count, ) users := make(Users, 0) if err != nil { return Users{}, err } for rows.Next() { err := rows.Scan( &u.ID, &u.Username, &u.UserID, &u.Blacklist, &u.IsAdmin, &u.Coins, &u.Reputation, &u.WeaponsPower, ) if err != nil { return Users{}, err } users = append(users, *u) } return users, nil } func (u *User) GetUserStatistics() (repStat float32, coinsStat float32, err error) { row := db.QueryRow( context.Background(), `SELECT (SELECT COUNT(*) FROM users WHERE reputation < $1) / (SELECT COUNT(*)::float FROM users) AS rep_stat, (SELECT COUNT(*) FROM users WHERE coins < $2) / (SELECT COUNT(*)::float FROM users) AS coins_stat`, u.Reputation, u.Coins, ) err = row.Scan( &repStat, &coinsStat, ) return } func (u *User) AddMoney(money int) { // for test only change it! _, _ = db.Exec( context.Background(), "UPDATE users SET coins = coins + $1 WHERE userid = $2", money, u.UserID, ) } func (u *User) AddPower(power int) { _, _ = db.Exec( context.Background(), "UPDATE users SET weapons_power = weapons_power + $1 WHERE id = $2", power, u.ID, ) } func (u *User) AddMoneyToUsers(money int, us []int) error { _, err := db.Exec( context.Background(), "UPDATE users SET coins = coins + $1 WHERE userid = ANY($2)", money, us, ) if err != nil { return err } return nil } func (u *User) AddReputationToUsers(reputation int, us []int) error { _, err := db.Exec( context.Background(), "UPDATE users SET reputation = reputation + $1 WHERE userid = ANY($2)", reputation, us, ) if err != nil { return err } return nil } func (u *User) DecreaseMoneyToUsers(money int, us []int) error { _, err := db.Exec( context.Background(), "UPDATE users SET coins = coins - $1 WHERE userid = ANY($2)", money, us, ) if err != nil { return err } return nil } func (u *User) DecreaseReputationToUsers(reputation int, us []int32) error { _, err := db.Exec( context.Background(), "UPDATE users SET reputation = reputation - $1 WHERE userid = ANY($2)", reputation, us, ) if err != nil { return err } return nil } func (u *User) DecreaseMoney(money int) { // for test only change it! _, _ = db.Exec( context.Background(), "UPDATE users SET coins = coins - $1 WHERE userid = $2", money, u.UserID, ) }
true
f51a2867dc8e735b99b5e22960a66b1133b801ae
Go
maxim2266/mvr
/mvr_test.go
UTF-8
6,084
2.859375
3
[ "BSD-3-Clause" ]
permissive
[ "BSD-3-Clause" ]
permissive
// +build !windows /* Copyright (c) 2018,2019 Maxim Konakov All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package mvr import ( "bytes" "context" "errors" "log" "math/rand" "runtime" "strconv" "sync" "sync/atomic" "testing" "time" ) func TestMain(m *testing.M) { rand.Seed(time.Now().UnixNano()) log.SetFlags(0) log.SetOutput(&loggerOutput) // to capture logger output Run(m.Run) } var loggerOutput bytes.Buffer func TestLogger(t *testing.T) { // write some log log.Println("zzz") log.Println("aaa") log.Println("bbb") // wait a moment time.Sleep(10 * time.Millisecond) // check if res := loggerOutput.String(); res != "zzz\naaa\nbbb\n" { t.Errorf("Unexpected string: %q", res) return } } func TestGo(t *testing.T) { const N = 100 var res int32 var wg sync.WaitGroup wg.Add(N) for i := 0; i < N; i++ { Go(func() { defer wg.Done() time.Sleep(time.Duration(rand.Intn(100)) * time.Millisecond) atomic.AddInt32(&res, 1) }) } wg.Wait() if atomic.LoadInt32(&res) != N { t.Error("Invalid number of iterations:", res, "instead of", N) return } } func TestAsync(t *testing.T) { const msg = "ERROR" var res int32 err := <-Async(func() error { time.Sleep(20 * time.Millisecond) atomic.AddInt32(&res, 1) return errors.New(msg) }) if err == nil { t.Error("Missing error message") return } if err.Error() != msg { t.Error("Unexpected error message:", err.Error()) return } if atomic.LoadInt32(&res) != 1 { t.Error("Unexpected result:", res, "instead of 1") return } } func TestParallel(t *testing.T) { nums := []int{1, runtime.NumCPU(), 50, rand.Intn(10) + 1} for _, nprocs := range nums { if !testParallel(nprocs, rand.Intn(nprocs*10), t) { return } } } func testParallel(nprocs, njobs int, t *testing.T) bool { var counter int32 errs, cancel := Parallel(nprocs, counterJobs(&counter, njobs)) defer cancel() for err := range errs { t.Error("nprocs:", nprocs, ", failure:", err) return false } if counter != int32(njobs) { t.Error("nprocs:", nprocs, ", failure: Invalid number of completed jobs:", counter, "instead of", njobs) return false } return true } func TestParallelForEach(t *testing.T) { input := []string{"1", "2", "3", "4"} var res int32 errs, cancel := Parallel(0, ForEachString(input, func(s string) error { val, err := strconv.Atoi(s) if err != nil { return err } atomic.AddInt32(&res, int32(val)) return nil })) defer cancel() for err := range errs { t.Error(err) return } if res != 10 { t.Error("Invalid number of completed jobs:", res, "instead of 10") return } } func TestParallelForEachError(t *testing.T) { input := []string{"1", "2", "zzz", "4"} var res int32 errs, cancel := Parallel(0, ForEachString(input, func(s string) error { val, err := strconv.Atoi(s) if err != nil { return err } atomic.AddInt32(&res, int32(val)) return nil })) defer cancel() err := <-errs if err == nil { t.Error("Missing error") return } if _, ok := err.(*strconv.NumError); !ok { t.Error("Unexpected error:", err) return } if err := <-errs; err != nil { t.Error("Unexpected second error:", err) return } if res > 7 { t.Error("Invalid number of completed jobs:", res) return } } func TestParallelCancel(t *testing.T) { ctx, stop := context.WithCancel(Context()) var res int32 errs, cancel := ParallelCtx(ctx, 0, counterJobs(&res, 5)) defer cancel() stop() err := <-errs if err == nil { t.Error("Missing error") return } if err != context.Canceled { t.Error("Unexpected error:", err) return } if err = <-errs; err != nil { t.Error("Unexpected second error:", err) return } } func counterJobs(pcnt *int32, njobs int) (jobs chan func() error) { jobs = make(chan func() error, njobs) defer close(jobs) for i := 0; i < njobs; i++ { jobs <- func() error { time.Sleep(time.Duration(rand.Intn(20)) * time.Millisecond) atomic.AddInt32(pcnt, 1) return nil } } return } func TestParallelFeed(t *testing.T) { const N = 10 var res int32 // input tasks channel inch := make(chan func() error) // start feeder Go(func() { defer close(inch) time.Sleep(10 * time.Millisecond) for i := 0; i < N; i++ { inch <- func() error { atomic.AddInt32(&res, 1) return nil } } }) // launch tasks errs, cancel := Parallel(0, inch) defer cancel() // check errors for err := range errs { t.Error(err) return } if res != 10 { t.Error("Unexpected result:", res, "instead of", N) return } } func _TestSignal(t *testing.T) { // press Ctrl+c to continue <-Done() t.Log(Err()) }
true
7d3f1b196cd992078c06e6d7abcc6e0556deb7d7
Go
slightc/ddns-go
/main.go
UTF-8
2,848
2.609375
3
[]
no_license
[]
no_license
package main import ( "flag" "fmt" "io/ioutil" "os" "os/signal" "syscall" "time" "main/aliyun" "main/common" "main/iputil" "main/qcloud" "github.com/robfig/cron" "gopkg.in/yaml.v2" ) type ddnsConfig struct { Type string `yaml:"Type"` SecretId string `yaml:"SecretId"` SecretKey string `yaml:"SecretKey"` Domain string `yaml:"Domain"` Record string `yaml:"Record"` RecordId string `yaml:"RecordId"` Cron string `yaml:"Cron"` } func main() { var configFilePath string var setting ddnsConfig var showDebugInfo bool var showRecordList bool exitSignal := make(chan os.Signal, 1) signal.Notify(exitSignal, syscall.SIGINT, syscall.SIGTERM, syscall.SIGQUIT) flag.StringVar(&configFilePath, "c", "/etc/ddns-go/config.yaml", "config file path") flag.BoolVar(&showDebugInfo, "d", false, "show debug information") flag.BoolVar(&showRecordList, "l", false, "show record list") flag.Parse() config, err := ioutil.ReadFile(configFilePath) if err != nil { configFilePath = "./config.yaml" fmt.Println("read config file err: ", err) fmt.Println("try use ", configFilePath) config, err = ioutil.ReadFile(configFilePath) } if err != nil { fmt.Println("read config file err: ", err) fmt.Println("exit with no config file") return } yaml.Unmarshal(config, &setting) var recordInfo = common.RecordInfo{Domain: setting.Domain, Name: setting.Record, Id: setting.RecordId} var accessKey = common.AccessKey{Id: setting.SecretId, Secret: setting.SecretKey} var recordHandler common.RecordHandler = nil fmt.Printf("%#v\n", recordInfo) if setting.Type == "aliyun" { recordHandler = aliyun.Aliyun{Key: accessKey} } if setting.Type == "qcloud" { recordHandler = qcloud.Qcloud{Key: accessKey} } if recordHandler == nil { fmt.Println("recordHandler create failed") return } err = iputil.Init() if err != nil { fmt.Println("create temp file err: ", err) return } defer iputil.Deinit() crontab := cron.New() task := func() { ip, err := iputil.GetIp() if err != nil { fmt.Println("get ip err: ", err) return } if showDebugInfo { fmt.Println("now ip: ", ip) } ipChanged, err := iputil.IpIsChanged(ip) if err != nil { fmt.Println("check ip changed err: ", err) return } if !ipChanged { if showDebugInfo { fmt.Println("ip not changed") } return } fmt.Println("== ", time.Now(), " ==") fmt.Println("new ip: ", ip) err = recordHandler.SetRecordIp(&recordInfo, ip) if err != nil { fmt.Println("set dns err: ", err) return } fmt.Println("ip modify success") } fmt.Println("start listen ip change") fmt.Println("cron run use: ", setting.Cron) crontab.AddFunc(setting.Cron, task) task() crontab.Start() fmt.Println("waiting") select { case s := <-exitSignal: fmt.Println("exit with :", s) break } }
true
a33ce6b94e87a5f6a831477e47712ac56f928319
Go
mokiat/preftime
/prefix/writer.go
UTF-8
980
3.390625
3
[ "Apache-2.0" ]
permissive
[ "Apache-2.0" ]
permissive
package prefix import ( "bytes" "io" ) func NewWriter(delegate io.Writer, prefixFunc Func) io.Writer { return &writer{ delegate: delegate, prefixFunc: prefixFunc, beginning: true, } } type writer struct { delegate io.Writer prefixFunc Func beginning bool } func (w *writer) Write(data []byte) (int, error) { dataCount := len(data) index := bytes.IndexByte(data, '\n') for index >= 0 { if err := w.writeSegment(data[:index+1]); err != nil { return 0, err } data = data[index+1:] index = bytes.IndexByte(data, '\n') } if len(data) > 0 { if err := w.writeSegment(data); err != nil { return 0, err } } return dataCount, nil } func (w *writer) writeSegment(data []byte) error { if w.beginning { if _, err := w.prefixFunc(w.delegate); err != nil { return err } w.beginning = false } if _, err := w.delegate.Write(data); err != nil { return err } if data[len(data)-1] == '\n' { w.beginning = true } return nil }
true
63b301e074e02b309216dee633b1c9494eaa9bda
Go
VesperHuang/blockchain_learn
/blockchainiterator.go
UTF-8
946
3.125
3
[]
no_license
[]
no_license
package main import ( "./lib/bolt" "log" ) type BlockChainIterator struct { db *bolt.DB //遊標,用於不斷索引 currentHashPointer []byte } //func NewIterator(bc *BlockChain) { // //} func (bc *BlockChain) NewIterator() *BlockChainIterator { return &BlockChainIterator{ bc.db, //最初指向區塊鏈的最後一個區塊,隨著Next的呼叫,不斷變化 bc.tail, } } //迭代器是屬於區塊鏈的 //Next方式是屬於迭代器的 //1. 返回目前的區塊 //2. 指針前移 func (it *BlockChainIterator) Next() *Block { var block Block it.db.View(func(tx *bolt.Tx) error { bucket := tx.Bucket([]byte(blockBucket)) if bucket == nil { log.Panic("迭代器遍歷時bucket不應該為空,請檢查!") } blockTmp := bucket.Get(it.currentHashPointer) //解碼動作 block = Deserialize(blockTmp) //遊標雜湊左移 it.currentHashPointer = block.PrevHash return nil }) return &block }
true
2ee2cbcdaffced750fc387291d58e63933028c23
Go
xq546247083/xq.goproject.com
/leetCode/100/main.go
UTF-8
723
3.484375
3
[]
no_license
[]
no_license
package main import "fmt" func main() { a1 := new(TreeNode) a2 := new(TreeNode) a3 := new(TreeNode) a1.Val = 1 a2.Val = 2 a3.Val = 3 a1.Left = a2 a1.Right = a3 b1 := new(TreeNode) b2 := new(TreeNode) b3 := new(TreeNode) b1.Val = 1 b2.Val = 2 b3.Val = 4 b1.Left = b2 b1.Right = b3 fmt.Println(isSameTree(a1, b1)) } type TreeNode struct { Val int Left *TreeNode Right *TreeNode } func isSameTree(p *TreeNode, q *TreeNode) bool { if p == nil && q == nil { return true } else if (p == nil && q != nil) || (p != nil && q == nil) || (p.Val != q.Val) { return false } else { if !isSameTree(p.Left, q.Left) || !isSameTree(p.Right, q.Right) { return false } else { return true } } }
true
841d8dd88f7b7a42b98f4512a5b2ff0990bab1f0
Go
tbruyelle/gostuff
/games/candy/state_test.go
UTF-8
3,104
3.15625
3
[]
no_license
[]
no_license
package main import ( "github.com/stretchr/testify/assert" "testing" ) func TestIdleState(t *testing.T) { setup() c := &Candy{} c.ChangeState(NewIdleState()) r := c.Update(g) assert.True(t, r, "Update should return true") assert.Equal(t, c.sprite._type, CandySprite) } func TestDyingState(t *testing.T) { c := &Candy{} c.ChangeState(NewDyingState()) r := c.Update(g) assert.False(t, r, "Update should return false") assert.Equal(t, c.sprite._type, DyingSprite) } func TestDyingStates(t *testing.T) { setup() c := &Candy{} c.ChangeState(NewDyingState()) for i := 0; i < DyingFrames; i++ { assert.False(t, c.Update(g), "Until DyingFrames, Update should returns false (%d)", i) } r := c.Update(g) assert.True(t, r, "After being invoked DyingFrame times, Update should return true") assert.True(t, c.IsDead(), "Candy should be dead") } func TestDyingStatesDelayed(t *testing.T) { setup() c := &Candy{} c.ChangeState(NewDyingStateDelayed(10)) for i := 0; i < DyingFrames+10; i++ { assert.False(t, c.Update(g), "Until DyingFrames+delay, Update should returns false (%d)", i) } r := c.Update(g) assert.True(t, r, "After being invoked DyingFrame+delay times, Update should return true") assert.True(t, c.IsDead(), "Candy should be dead") } func TestFallingState(t *testing.T) { setup() c := &Candy{} c.ChangeState(NewFallingState()) r := c.Update(g) assert.False(t, r, "Update should return false") } func TestFallingStates(t *testing.T) { setup() c := &Candy{x: XMin, y: YMin} c.ChangeState(NewFallingState()) for !c.Update(g) { } assert.Equal(t, c.x, XMin, "x should not change during fall") assert.Equal(t, c.y, YMax, "candy should fall until the bottom") } func TestFallingStatesMulti(t *testing.T) { setup() c1 := &Candy{x: XMin, y: YMin} c1.ChangeState(NewFallingState()) c2 := &Candy{x: XMin + BlockSize, y: YMin} c2.ChangeState(NewFallingState()) // add candy to create collisions g.candys = append(g.candys, &Candy{x: c1.x, y: YMin + 2*BlockSize}) g.candys = append(g.candys, &Candy{x: c2.x, y: YMin + 5*BlockSize}) for !c1.Update(g) || !c2.Update(g) { } assert.Equal(t, c1.y, YMin+BlockSize, "candy should fall until the bottom") assert.Equal(t, c2.y, YMin+4*BlockSize, "candy should fall until the bottom") } func TestPermuteState(t *testing.T) { c := &Candy{x: XMin, y: YMin} c2 := &Candy{x: XMin + BlockSize, y: YMin} c.ChangeState(NewPermuteState(c2)) for !c.Update(g) { } assert.Equal(t, c.x, c2.x, "Candy should permute to other candy") } func TestPermuteStateExit(t *testing.T) { c := &Candy{x: XMin, y: YMin} c2 := &Candy{x: XMin + BlockSize, y: YMin} c.ChangeState(NewPermuteState(c2)) c.ChangeState(NewIdleState()) assert.Equal(t, c.vx, 0, "Quit permute state should reset vx") assert.Equal(t, c.vy, 0, "Quit permute state should reset vy") } func TestMorphState(t *testing.T) { setup() c := &Candy{} c.ChangeState(NewIdleState()) c.ChangeState(NewMorphState(RedPackedCandy)) for !c.Update(g) { } assert.Equal(t, c._type, RedPackedCandy, "Candy should have morph to RedPackedCandy") }
true
1d5630712057e035821cf5faf7070e21c4b32ff1
Go
upfluence/cfg
/x/cli/command_test.go
UTF-8
5,368
3.03125
3
[]
no_license
[]
no_license
package cli import ( "bytes" "context" "fmt" "io" "regexp" "testing" "github.com/stretchr/testify/assert" ) type mockConfig1 struct { Example string `flag:"e,example"` } type mockConfig2 struct { Other string `flag:"o,other"` } type mockCommand struct { Command } func (mc *mockCommand) WriteHelp(w io.Writer, opts IntrospectionOptions) (int, error) { return mc.Command.WriteHelp( w, opts.withDefinition( CommandDefinition{Configs: []interface{}{&mockConfig1{}}}, ), ) } func TestRun(t *testing.T) { staticCmd := StaticCommand{ Help: StaticString("help foo"), Synopsis: SynopsisWriter(&mockConfig1{}), Execute: func(_ context.Context, cctx CommandContext) error { _, err := io.WriteString(cctx.Stdout, "success") return err }, } eh := EnhancedHelp{ Short: "enhanced short help", Long: "enhanced long help", Config: &mockConfig2{}, } subCmd := SubCommand{Commands: map[string]Command{"foo": staticCmd}} nestedCmd := SubCommand{ Commands: map[string]Command{ "foo": subCmd, "bar": &mockCommand{ Command: StaticCommand{ Help: HelpWriter(&mockConfig2{}), Synopsis: SynopsisWriter(&mockConfig2{}), Execute: func(_ context.Context, cctx CommandContext) error { _, err := io.WriteString(cctx.Stdout, "success") return err }, }, }, "buz": &mockCommand{ Command: StaticCommand{ Help: eh.WriteHelp, Synopsis: eh.WriteSynopsis, Execute: func(_ context.Context, cctx CommandContext) error { _, err := io.WriteString(cctx.Stdout, "success") return err }, }, }, }, } argCmd := ArgumentCommand{ Variable: "buz", Command: StaticCommand{ Execute: func(ctx context.Context, cctx CommandContext) error { var c = struct { Buz string `arg:"buz"` }{} if err := cctx.Configurator.Populate(ctx, &c); err != nil { return err } _, err := fmt.Fprintf(cctx.Stdout, "<%s>", c.Buz) return err }, }, } for _, tt := range []struct { opts []Option args []string wantOut string wantErr string err error }{ { wantErr: `unknown command "", available commands: help Print this message version Print the app version `, }, { args: []string{"subcommand"}, wantErr: `unknown command "subcommand", available commands: help Print this message version Print the app version `, }, { args: []string{"-h"}, wantErr: defaultHelp, }, { args: []string{"-v"}, opts: []Option{WithName("testapp")}, wantOut: "testapp/dirty\n", }, { opts: []Option{WithCommand(staticCmd)}, wantOut: "success", }, { opts: []Option{WithCommand(argCmd)}, args: []string{"foo", "-y"}, wantOut: "<foo>", }, { opts: []Option{WithCommand(argCmd)}, args: []string{"-y"}, wantErr: `no argument found for variable "buz", follow the synopsis: cli-test <buz> `, }, { opts: []Option{WithCommand(argCmd)}, args: []string{"-h"}, wantErr: "usage: cli-test <buz> ", }, { args: []string{"foo"}, opts: []Option{WithCommand(subCmd)}, wantOut: "success", }, { args: []string{"buz"}, opts: []Option{WithCommand(subCmd)}, wantErr: `unknown command "buz", available commands: foo help foo help Print this message version Print the app version `, }, { args: []string{"-h"}, opts: []Option{WithCommand(subCmd)}, wantErr: `usage: cli-test <arg_1> Available sub commands: foo help foo help Print this message version Print the app version `, }, { args: []string{"-h"}, opts: []Option{WithCommand(nestedCmd)}, wantErr: `usage: cli-test <arg_1> Available sub commands: bar usage: [-e, --example] [-o, --other] buz enhanced short help foo usage: <arg_1> help Print this message version Print the app version `, }, { args: []string{"foo", "-h"}, opts: []Option{WithCommand(nestedCmd)}, wantErr: `usage: cli-test <arg_1> <arg_2> Available sub commands: foo help foo help Print this message version Print the app version `, }, { args: []string{"bar", "-h"}, opts: []Option{WithCommand(nestedCmd)}, wantErr: `usage: cli-test <arg_1> [-e, --example] [-o, --other] Arguments: - Example: string (env: EXAMPLE, flag: -e, --example) - Other: string (env: OTHER, flag: -o, --other) `, }, { args: []string{"buz", "-h"}, opts: []Option{WithCommand(nestedCmd)}, wantErr: `Description: enhanced long help Usage: cli-test <arg_1> [-e, --example] [-o, --other] Arguments: - Example: string (env: EXAMPLE, flag: -e, --example) - Other: string (env: OTHER, flag: -o, --other) `, }, { args: []string{"foo", "foo", "-h"}, opts: []Option{WithCommand(nestedCmd)}, wantErr: `usage: cli-test <arg_1> <arg_2> help foo`, }, } { var ( outBuf bytes.Buffer errBuf bytes.Buffer a = NewApp(append([]Option{WithName("cli-test")}, tt.opts...)...) ) a.args = tt.args cctx := a.commandContext() cctx.Stdout = &outBuf cctx.Stderr = &errBuf err := a.cmd.Run(context.Background(), cctx) assert.Equal(t, canonicalString(outBuf.String()), canonicalString(tt.wantOut)) assert.Equal(t, canonicalString(errBuf.String()), canonicalString(tt.wantErr)) assert.Equal(t, err, tt.err) } } func canonicalString(v string) string { return regexp.MustCompile(`\s+`).ReplaceAllString(v, " ") }
true
ab57049fba12c6459c76b55216165b84c4c0e307
Go
tailnode/Heimdallr
/error.go
UTF-8
1,150
2.84375
3
[]
no_license
[]
no_license
package main import ( "encoding/json" "fmt" ) const ( ERR_OK = iota ERR_MONNAME_NOT_EXIST ERR_BEYOND_LIMIT ERR_IN_PRISON ERR_INVALIDE_PARAM ERR_INTERAL ) var errMap = map[int]string{ ERR_OK: "OK", ERR_MONNAME_NOT_EXIST: "monitor name not exist", ERR_BEYOND_LIMIT: "beyond limit", ERR_IN_PRISON: "in prison", ERR_INVALIDE_PARAM: "invalide parameter", ERR_INTERAL: "internal error", } type myError struct { code int msg string extra int64 } type myErrorJson struct { Code int `json:"code"` Msg string `json:"msg"` Extra int64 `json:"extra"` } func (e myError) String() string { if e.code == ERR_IN_PRISON { return fmt.Sprintf("err code[%v] err msg[%v] prisonNanoSec[%v]", e.code, e.msg, e.extra) } else { return fmt.Sprintf("err code[%v] err msg[%v]", e.code, e.msg) } } func newError(code int, remainNanoSec int64) myError { if _, ok := errMap[code]; !ok { code = ERR_INTERAL } return myError{code, errMap[code], remainNanoSec} } func (e myError) toJson() []byte { eJson := myErrorJson{ e.code, e.msg, e.extra, } b, _ := json.Marshal(eJson) return b }
true
01a153945914d70f677df0a5a8784535c473b862
Go
ChimeraCoder/golang-stuff
/github.com/tumblr/gocircuit/src/circuit/sys/lang/vrewrite.go
UTF-8
4,894
2.859375
3
[ "Apache-2.0" ]
permissive
[ "Apache-2.0" ]
permissive
// Copyright 2013 Tumblr, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package lang import ( "reflect" "sync" ) // rewriteFunc can selectively rewrite a src value by writing // the new value into dst and returning true. // rewriteFunc MUST rewrite map values. type rewriteFunc func(src, dst reflect.Value) bool func rewriteInterface(rewrite rewriteFunc, src interface{}) interface{} { v := reflect.ValueOf(src) if isTerminalKind(v.Type()) { return src } pz := reflect.New(v.Type()) if rewriteValue(rewrite, v, pz.Elem()) { return pz.Elem().Interface() } return src } type rewriteGroup struct { sync.WaitGroup sync.Mutex Change bool } // dst must be addressable. func rewriteValue(rewrite rewriteFunc, src, dst reflect.Value) bool { if rewrite(src, dst) { return true } // Recursive step var g rewriteGroup t := src.Type() switch src.Kind() { case reflect.Array: if isTerminalKind(t) { return false } for i := 0; i < src.Len(); i++ { src__, dst__ := src.Index(i), dst.Index(i) g.Add(1) go func() { defer g.Done() if rewriteValue(rewrite, src__, dst__) { g.Lock() g.Change = true g.Unlock() } else { dst__.Set(src__) } }() } g.Wait() return g.Change case reflect.Slice: if src.IsNil() || isTerminalKind(t) { return false } dst.Set(reflect.MakeSlice(t, src.Len(), src.Len())) for i := 0; i < src.Len(); i++ { src__, dst__ := src.Index(i), dst.Index(i) g.Add(1) go func() { defer g.Done() if rewriteValue(rewrite, src__, dst__) { g.Lock() g.Change = true g.Unlock() } else { dst__.Set(src__) } }() } g.Wait() return g.Change case reflect.Map: // For now, we do not rewrite map key values if src.IsNil() || isTerminalKind(t) { return false } dst.Set(reflect.MakeMap(t)) for _, mk := range src.MapKeys() { src__ := src.MapIndex(mk) dst__ := reflect.New(t.Elem()).Elem() g.Add(1) go func() { defer g.Done() if rewriteValue(rewrite, src__, dst__) { dst.SetMapIndex(mk, dst__) g.Lock() g.Change = true g.Unlock() } else { dst.SetMapIndex(mk, src__) } }() } g.Wait() return g.Change case reflect.Ptr: if src.IsNil() || isTerminalKind(t) { return false } pz := reflect.New(t.Elem()) if rewriteValue(rewrite, src.Elem(), pz.Elem()) { dst.Set(pz) return true } return false case reflect.Interface: if !src.IsNil() { if src.Elem().Kind() == reflect.Ptr && src.Elem().IsNil() { // Rewrite src to be a <nil,nil> interface value, instead of <*int,nil> dst.Set(reflect.Zero(t)) return true } } // If value is nil of type *T, collapse to absolute nil if src.IsNil() || isTerminalKind(src.Elem().Type()) { return false } // Recursive interface value unflattening would happen here; // We don't use it, however, since there is no source of // type-information for the actual passed values. pz := reflect.New(src.Elem().Type()) if rewriteValue(rewrite, src.Elem(), pz.Elem()) { dst.Set(pz.Elem()) return true } return false case reflect.Struct: if isTerminalKind(t) { return false } for i := 0; i < src.NumField(); i++ { if t.Field(i).PkgPath == "" { // If field is public src__, dst__ := src.Field(i), dst.Field(i) g.Add(1) go func() { defer g.Done() if rewriteValue(rewrite, src__, dst__) { g.Lock() g.Change = true g.Unlock() } else { dst__.Set(src__) } }() } } g.Wait() return g.Change case reflect.Chan: panic("rewrite chan, not supported yet") case reflect.Func: panic("rewrite func") case reflect.UnsafePointer: panic("rewrite unsafe pointer") } // All remaining types are primitive and therefore terminal return false } func isTerminalKind(t reflect.Type) bool { switch t.Kind() { case reflect.Array, reflect.Slice, reflect.Ptr: return isTerminalKind(t.Elem()) case reflect.Map: // For now, we do not rewrite map key values return isTerminalKind(t.Elem()) case reflect.Interface: return false case reflect.Struct: terminal := true for i := 0; i < t.NumField(); i++ { if t.Field(i).PkgPath == "" { // If field is public if !isTerminalKind(t.Field(i).Type) { terminal = false break } } } return terminal } return true }
true
a95016f3b46414b48d645cc335bc9da2b9eb7e32
Go
ChrisRx/myriad
/cmd/main.go
UTF-8
1,363
2.609375
3
[ "MIT" ]
permissive
[ "MIT" ]
permissive
package main import ( "fmt" "log" "time" "github.com/ChrisRx/myriad" ) func main() { addrs := []string{":12345", ":12346", ":12347"} nodes := make([]*myriad.Node, 0) for i, addr := range addrs { n, err := myriad.New(&myriad.Config{ Dir: "data", Addr: addr, EnableSingle: i == 0, RaftTimeout: 10 * time.Second, RetainSnapshotCount: 2, InitialPeers: addrs, }) if err != nil { log.Fatal(err) } nodes = append(nodes, n) } addrs2 := []string{":12348", ":12349", ":12350"} for i, addr := range addrs2 { n, err := myriad.New(&myriad.Config{ Dir: "data", Addr: addr, EnableSingle: i == 0, RaftTimeout: 10 * time.Second, RetainSnapshotCount: 2, InitialPeers: addrs, }) if err != nil { log.Fatal(err) } nodes = append(nodes, n) } s := nodes[0] for i, addr := range addrs[1:] { if err := s.Raft.Join(nodes[i+1].LocalID(), addr); err != nil { log.Fatal(err) } } if err := nodes[1].Set("raftkey", "raftvalue"); err != nil { log.Fatal(err) } v, err := nodes[2].Get("raftkey") if err != nil { log.Fatal(err) } fmt.Printf("v = %+v\n", v) for { time.Sleep(5 * time.Second) for _, server := range s.Config().Servers { fmt.Printf("server = %+v\n", server) } } }
true
8bf94ff01f6f7334ff69799bc9286aa51c744d0c
Go
with-go/standard
/object/presenter_test.go
UTF-8
1,233
3.4375
3
[ "BSD-3-Clause" ]
permissive
[ "BSD-3-Clause" ]
permissive
package object import ( "fmt" "testing" ) type detailStructure struct { Name string `json:"name"` Description string `json:"description"` } type dataStructure struct { Pkg string `json:"pkg"` Detail detailStructure `json:"detail"` Version float64 `json:"version"` Year int64 `json:"year"` IsPublic bool `json:"isPublic"` } func TestPresenter_AsStruct(t *testing.T) { pkg := "standard" detailName := "Go with Standard" detailDescription := "Standard objects in Go, redesigned." detail := New(). Set("name", detailName). Set("description", detailDescription) version := 1.5 year := 2020 object := New(). Set("pkg", pkg). Set("detail", detail). Set("version", version). Set("year", year). Set("isPublic", true) var data dataStructure err := object.Present().AsStruct(&data) if err != nil { t.Error("object.Present().AsStruct(v) parsing error") t.Errorf("Reason: %v", err) return } strShouldBe := "{standard {Go with Standard Standard objects in Go, redesigned.} 1.5 2020 true}" if fmt.Sprint(data) != strShouldBe { t.Error("object.Present().AsStruct(v) String() value not match") t.Errorf("Expecting %s, got %s", strShouldBe, fmt.Sprint(data)) return } }
true
0fe8f10760a5464fd5d586e712617f2c88a1ce23
Go
abserari/librarian
/modules/theme/github.go
UTF-8
17,356
2.578125
3
[]
no_license
[]
no_license
package theme import "html/template" type Github struct { Base } func (g *Github) CSS() template.CSS { return g.Base.CSS() + ` .markdown-viewer { padding-top: 30px; } .markdown-viewer .octicon { display: inline-block; fill: currentColor; vertical-align: text-bottom; } .markdown-viewer .anchor { float: left; line-height: 1; margin-left: -20px; padding-right: 4px; } .markdown-viewer .anchor:focus { outline: none; } .markdown-viewer blockquote { font-size: 1.5rem; } .markdown-viewer h1 .octicon-link, .markdown-viewer h2 .octicon-link, .markdown-viewer h3 .octicon-link, .markdown-viewer h4 .octicon-link, .markdown-viewer h5 .octicon-link, .markdown-viewer h6 .octicon-link { color: #1b1f23; vertical-align: middle; visibility: hidden; } .markdown-viewer h1:hover .anchor, .markdown-viewer h2:hover .anchor, .markdown-viewer h3:hover .anchor, .markdown-viewer h4:hover .anchor, .markdown-viewer h5:hover .anchor, .markdown-viewer h6:hover .anchor { text-decoration: none; } .markdown-viewer h1:hover .anchor .octicon-link, .markdown-viewer h2:hover .anchor .octicon-link, .markdown-viewer h3:hover .anchor .octicon-link, .markdown-viewer h4:hover .anchor .octicon-link, .markdown-viewer h5:hover .anchor .octicon-link, .markdown-viewer h6:hover .anchor .octicon-link { visibility: visible; } .markdown-viewer h1:hover .anchor .octicon-link:before, .markdown-viewer h2:hover .anchor .octicon-link:before, .markdown-viewer h3:hover .anchor .octicon-link:before, .markdown-viewer h4:hover .anchor .octicon-link:before, .markdown-viewer h5:hover .anchor .octicon-link:before, .markdown-viewer h6:hover .anchor .octicon-link:before { width: 16px; height: 16px; content: ' '; display: inline-block; background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16' version='1.1' width='16' height='16' aria-hidden='true'%3E%3Cpath fill-rule='evenodd' d='M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z'%3E%3C/path%3E%3C/svg%3E"); }.markdown-viewer { -ms-text-size-adjust: 100%; -webkit-text-size-adjust: 100%; line-height: 1.5; color: #24292e; font-family: -apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif,Apple Color Emoji,Segoe UI Emoji; font-size: 16px; line-height: 1.5; word-wrap: break-word; } .markdown-viewer details { display: block; } .markdown-viewer summary { display: list-item; } .markdown-viewer a { background-color: initial; } .markdown-viewer a:active, .markdown-viewer a:hover { outline-width: 0; } .markdown-viewer strong { font-weight: inherit; font-weight: bolder; } .markdown-viewer h1 { font-size: 2em; margin: .67em 0; } .markdown-viewer img { border-style: none; } .markdown-viewer code, .markdown-viewer kbd, .markdown-viewer pre { font-family: monospace,monospace; font-size: 1em; } .markdown-viewer hr { box-sizing: initial; height: 0; overflow: visible; } .markdown-viewer input { font: inherit; margin: 0; } .markdown-viewer input { overflow: visible; } .markdown-viewer [type=checkbox] { box-sizing: border-box; padding: 0; } .markdown-viewer * { box-sizing: border-box; } .markdown-viewer input { font-family: inherit; font-size: inherit; line-height: inherit; } .markdown-viewer a { color: #0366d6; text-decoration: none; } .markdown-viewer a:hover { text-decoration: underline; } .markdown-viewer strong { font-weight: 600; } .markdown-viewer hr { height: 0; margin: 15px 0; overflow: hidden; background: transparent; border: 0; border-bottom: 1px solid #dfe2e5; } .markdown-viewer hr:after, .markdown-viewer hr:before { display: table; content: ""; } .markdown-viewer hr:after { clear: both; } .markdown-viewer table { border-spacing: 0; border-collapse: collapse; } .markdown-viewer td, .markdown-viewer th { padding: 0; } .markdown-viewer details summary { cursor: pointer; } .markdown-viewer kbd { display: inline-block; padding: 3px 5px; font: 11px SFMono-Regular,Consolas,Liberation Mono,Menlo,monospace; line-height: 10px; color: #444d56; vertical-align: middle; background-color: #fafbfc; border: 1px solid #d1d5da; border-radius: 3px; box-shadow: inset 0 -1px 0 #d1d5da; } .markdown-viewer h1, .markdown-viewer h2, .markdown-viewer h3, .markdown-viewer h4, .markdown-viewer h5, .markdown-viewer h6 { margin-top: 0; margin-bottom: 0; } .markdown-viewer h1 { font-size: 32px; } .markdown-viewer h1, .markdown-viewer h2 { font-weight: 600; } .markdown-viewer h2 { font-size: 24px; } .markdown-viewer h3 { font-size: 20px; } .markdown-viewer h3, .markdown-viewer h4 { font-weight: 600; } .markdown-viewer h4 { font-size: 16px; } .markdown-viewer h5 { font-size: 14px; } .markdown-viewer h5, .markdown-viewer h6 { font-weight: 600; } .markdown-viewer h6 { font-size: 12px; } .markdown-viewer p { margin-top: 0; margin-bottom: 10px; } .markdown-viewer blockquote { margin: 0; } .markdown-viewer ol, .markdown-viewer ul { padding-left: 0; margin-top: 0; margin-bottom: 0; } .markdown-viewer ol ol, .markdown-viewer ul ol { list-style-type: lower-roman; } .markdown-viewer ol ol ol, .markdown-viewer ol ul ol, .markdown-viewer ul ol ol, .markdown-viewer ul ul ol { list-style-type: lower-alpha; } .markdown-viewer dd { margin-left: 0; } .markdown-viewer code, .markdown-viewer pre { font-family: SFMono-Regular,Consolas,Liberation Mono,Menlo,monospace; font-size: 12px; } .markdown-viewer pre { margin-top: 0; margin-bottom: 0; } .markdown-viewer input::-webkit-inner-spin-button, .markdown-viewer input::-webkit-outer-spin-button { margin: 0; -webkit-appearance: none; appearance: none; } .markdown-viewer :checked+.radio-label { position: relative; z-index: 1; border-color: #0366d6; } .markdown-viewer .border { border: 1px solid #e1e4e8!important; } .markdown-viewer .border-0 { border: 0!important; } .markdown-viewer .border-bottom { border-bottom: 1px solid #e1e4e8!important; } .markdown-viewer .rounded-1 { border-radius: 3px!important; } .markdown-viewer .bg-white { background-color: #fff!important; } .markdown-viewer .bg-gray-light { background-color: #fafbfc!important; } .markdown-viewer .text-gray-light { color: #6a737d!important; } .markdown-viewer .mb-0 { margin-bottom: 0!important; } .markdown-viewer .my-2 { margin-top: 8px!important; margin-bottom: 8px!important; } .markdown-viewer .pl-0 { padding-left: 0!important; } .markdown-viewer .py-0 { padding-top: 0!important; padding-bottom: 0!important; } .markdown-viewer .pl-1 { padding-left: 4px!important; } .markdown-viewer .pl-2 { padding-left: 8px!important; } .markdown-viewer .py-2 { padding-top: 8px!important; padding-bottom: 8px!important; } .markdown-viewer .pl-3, .markdown-viewer .px-3 { padding-left: 16px!important; } .markdown-viewer .px-3 { padding-right: 16px!important; } .markdown-viewer .pl-4 { padding-left: 24px!important; } .markdown-viewer .pl-5 { padding-left: 32px!important; } .markdown-viewer .pl-6 { padding-left: 40px!important; } .markdown-viewer .f6 { font-size: 12px!important; } .markdown-viewer .lh-condensed { line-height: 1.25!important; } .markdown-viewer .text-bold { font-weight: 600!important; } .markdown-viewer .pl-c { color: #6a737d; } .markdown-viewer .pl-c1, .markdown-viewer .pl-s .pl-v { color: #005cc5; } .markdown-viewer .pl-e, .markdown-viewer .pl-en { color: #6f42c1; } .markdown-viewer .pl-s .pl-s1, .markdown-viewer .pl-smi { color: #24292e; } .markdown-viewer .pl-ent { color: #22863a; } .markdown-viewer .pl-k { color: #d73a49; } .markdown-viewer .pl-pds, .markdown-viewer .pl-s, .markdown-viewer .pl-s .pl-pse .pl-s1, .markdown-viewer .pl-sr, .markdown-viewer .pl-sr .pl-cce, .markdown-viewer .pl-sr .pl-sra, .markdown-viewer .pl-sr .pl-sre { color: #032f62; } .markdown-viewer .pl-smw, .markdown-viewer .pl-v { color: #e36209; } .markdown-viewer .pl-bu { color: #b31d28; } .markdown-viewer .pl-ii { color: #fafbfc; background-color: #b31d28; } .markdown-viewer .pl-c2 { color: #fafbfc; background-color: #d73a49; } .markdown-viewer .pl-c2:before { content: "^M"; } .markdown-viewer .pl-sr .pl-cce { font-weight: 700; color: #22863a; } .markdown-viewer .pl-ml { color: #735c0f; } .markdown-viewer .pl-mh, .markdown-viewer .pl-mh .pl-en, .markdown-viewer .pl-ms { font-weight: 700; color: #005cc5; } .markdown-viewer .pl-mi { font-style: italic; color: #24292e; } .markdown-viewer .pl-mb { font-weight: 700; color: #24292e; } .markdown-viewer .pl-md { color: #b31d28; background-color: #ffeef0; } .markdown-viewer .pl-mi1 { color: #22863a; background-color: #f0fff4; } .markdown-viewer .pl-mc { color: #e36209; background-color: #ffebda; } .markdown-viewer .pl-mi2 { color: #f6f8fa; background-color: #005cc5; } .markdown-viewer .pl-mdr { font-weight: 700; color: #6f42c1; } .markdown-viewer .pl-ba { color: #586069; } .markdown-viewer .pl-sg { color: #959da5; } .markdown-viewer .pl-corl { text-decoration: underline; color: #032f62; } .markdown-viewer .mb-0 { margin-bottom: 0!important; } .markdown-viewer .my-2 { margin-bottom: 8px!important; } .markdown-viewer .my-2 { margin-top: 8px!important; } .markdown-viewer .pl-0 { padding-left: 0!important; } .markdown-viewer .py-0 { padding-top: 0!important; padding-bottom: 0!important; } .markdown-viewer .pl-1 { padding-left: 4px!important; } .markdown-viewer .pl-2 { padding-left: 8px!important; } .markdown-viewer .py-2 { padding-top: 8px!important; padding-bottom: 8px!important; } .markdown-viewer .pl-3 { padding-left: 16px!important; } .markdown-viewer .pl-4 { padding-left: 24px!important; } .markdown-viewer .pl-5 { padding-left: 32px!important; } .markdown-viewer .pl-6 { padding-left: 40px!important; } .markdown-viewer .pl-7 { padding-left: 48px!important; } .markdown-viewer .pl-8 { padding-left: 64px!important; } .markdown-viewer .pl-9 { padding-left: 80px!important; } .markdown-viewer .pl-10 { padding-left: 96px!important; } .markdown-viewer .pl-11 { padding-left: 112px!important; } .markdown-viewer .pl-12 { padding-left: 128px!important; } .markdown-viewer hr { border-bottom-color: #eee; } .markdown-viewer kbd { display: inline-block; padding: 3px 5px; font: 11px SFMono-Regular,Consolas,Liberation Mono,Menlo,monospace; line-height: 10px; color: #444d56; vertical-align: middle; background-color: #fafbfc; border: 1px solid #d1d5da; border-radius: 3px; box-shadow: inset 0 -1px 0 #d1d5da; } .markdown-viewer:after, .markdown-viewer:before { display: table; content: ""; } .markdown-viewer:after { clear: both; } .markdown-viewer>:first-child { margin-top: 0!important; } .markdown-viewer>:last-child { margin-bottom: 0!important; } .markdown-viewer a:not([href]) { color: inherit; text-decoration: none; } .markdown-viewer blockquote, .markdown-viewer details, .markdown-viewer dl, .markdown-viewer ol, .markdown-viewer p, .markdown-viewer pre, .markdown-viewer table, .markdown-viewer ul { margin-top: 0; margin-bottom: 16px; } .markdown-viewer hr { height: .25em; padding: 0; margin: 24px 0; background-color: #e1e4e8; border: 0; } .markdown-viewer blockquote { padding: 0 1em; color: #6a737d; border-left: .25em solid #dfe2e5; } .markdown-viewer blockquote>:first-child { margin-top: 0; } .markdown-viewer blockquote>:last-child { margin-bottom: 0; } .markdown-viewer h1, .markdown-viewer h2, .markdown-viewer h3, .markdown-viewer h4, .markdown-viewer h5, .markdown-viewer h6 { margin-top: 24px; margin-bottom: 16px; font-weight: 600; line-height: 1.25; } .markdown-viewer h1 { font-size: 2em; } .markdown-viewer h1, .markdown-viewer h2 { padding-bottom: .3em; border-bottom: 1px solid #eaecef; } .markdown-viewer h2 { font-size: 1.5em; } .markdown-viewer h3 { font-size: 1.25em; } .markdown-viewer h4 { font-size: 1em; } .markdown-viewer h5 { font-size: .875em; } .markdown-viewer h6 { font-size: .85em; color: #6a737d; } .markdown-viewer ol, .markdown-viewer ul { padding-left: 2em; } .markdown-viewer ol ol, .markdown-viewer ol ul, .markdown-viewer ul ol, .markdown-viewer ul ul { margin-top: 0; margin-bottom: 0; } .markdown-viewer li { word-wrap: break-all; } .markdown-viewer li>p { margin-top: 16px; } .markdown-viewer li+li { margin-top: .25em; } .markdown-viewer dl { padding: 0; } .markdown-viewer dl dt { padding: 0; margin-top: 16px; font-size: 1em; font-style: italic; font-weight: 600; } .markdown-viewer dl dd { padding: 0 16px; margin-bottom: 16px; } .markdown-viewer table { display: block; width: 100%; overflow: auto; } .markdown-viewer table th { font-weight: 600; } .markdown-viewer table td, .markdown-viewer table th { padding: 6px 13px; border: 1px solid #dfe2e5; } .markdown-viewer table tr { background-color: #fff; border-top: 1px solid #c6cbd1; } .markdown-viewer table tr:nth-child(2n) { background-color: #f6f8fa; } .markdown-viewer img { max-width: 100%; box-sizing: initial; background-color: #fff; } .markdown-viewer img[align=right] { padding-left: 20px; } .markdown-viewer img[align=left] { padding-right: 20px; } .markdown-viewer code { padding: .2em .4em; margin: 0; font-size: 85%; background-color: rgba(27,31,35,.05); border-radius: 3px; } .markdown-viewer pre { word-wrap: normal; } .markdown-viewer pre>code { padding: 0; margin: 0; font-size: 100%; word-break: normal; white-space: pre; background: transparent; border: 0; } .markdown-viewer .highlight { margin-bottom: 16px; } .markdown-viewer .highlight pre { margin-bottom: 0; word-break: normal; } .markdown-viewer .highlight pre, .markdown-viewer pre { padding: 16px; overflow: auto; font-size: 85%; line-height: 1.45; background-color: #f6f8fa; border-radius: 3px; } .markdown-viewer pre code { display: inline; max-width: auto; padding: 0; margin: 0; overflow: visible; line-height: inherit; word-wrap: normal; background-color: initial; border: 0; } .markdown-viewer .commit-tease-sha { display: inline-block; font-family: SFMono-Regular,Consolas,Liberation Mono,Menlo,monospace; font-size: 90%; color: #444d56; } .markdown-viewer .full-commit .btn-outline:not(:disabled):hover { color: #005cc5; border-color: #005cc5; } .markdown-viewer .blob-wrapper { overflow-x: auto; overflow-y: hidden; } .markdown-viewer .blob-wrapper-embedded { max-height: 240px; overflow-y: auto; } .markdown-viewer .blob-num { width: 1%; min-width: 50px; padding-right: 10px; padding-left: 10px; font-family: SFMono-Regular,Consolas,Liberation Mono,Menlo,monospace; font-size: 12px; line-height: 20px; color: rgba(27,31,35,.3); text-align: right; white-space: nowrap; vertical-align: top; cursor: pointer; -webkit-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none; } .markdown-viewer .blob-num:hover { color: rgba(27,31,35,.6); } .markdown-viewer .blob-num:before { content: attr(data-line-number); } .markdown-viewer .blob-code { position: relative; padding-right: 10px; padding-left: 10px; line-height: 20px; vertical-align: top; } .markdown-viewer .blob-code-inner { overflow: visible; font-family: SFMono-Regular,Consolas,Liberation Mono,Menlo,monospace; font-size: 12px; color: #24292e; word-wrap: normal; white-space: pre; } .markdown-viewer .pl-token.active, .markdown-viewer .pl-token:hover { cursor: pointer; background: #ffea7f; } .markdown-viewer .tab-size[data-tab-size="1"] { -moz-tab-size: 1; tab-size: 1; } .markdown-viewer .tab-size[data-tab-size="2"] { -moz-tab-size: 2; tab-size: 2; } .markdown-viewer .tab-size[data-tab-size="3"] { -moz-tab-size: 3; tab-size: 3; } .markdown-viewer .tab-size[data-tab-size="4"] { -moz-tab-size: 4; tab-size: 4; } .markdown-viewer .tab-size[data-tab-size="5"] { -moz-tab-size: 5; tab-size: 5; } .markdown-viewer .tab-size[data-tab-size="6"] { -moz-tab-size: 6; tab-size: 6; } .markdown-viewer .tab-size[data-tab-size="7"] { -moz-tab-size: 7; tab-size: 7; } .markdown-viewer .tab-size[data-tab-size="8"] { -moz-tab-size: 8; tab-size: 8; } .markdown-viewer .tab-size[data-tab-size="9"] { -moz-tab-size: 9; tab-size: 9; } .markdown-viewer .tab-size[data-tab-size="10"] { -moz-tab-size: 10; tab-size: 10; } .markdown-viewer .tab-size[data-tab-size="11"] { -moz-tab-size: 11; tab-size: 11; } .markdown-viewer .tab-size[data-tab-size="12"] { -moz-tab-size: 12; tab-size: 12; } .markdown-viewer .task-list-item { list-style-type: none; } .markdown-viewer .task-list-item+.task-list-item { margin-top: 3px; } .markdown-viewer .task-list-item input { margin: 0 .2em .25em -1.6em; vertical-align: middle; } ` }
true
cb76308c910776680ac3da289391738bc415b96d
Go
tohutohu/traQ
/repository/stamp.go
UTF-8
2,690
2.90625
3
[ "MIT", "CC-BY-4.0" ]
permissive
[ "MIT", "CC-BY-4.0" ]
permissive
package repository import ( "github.com/gofrs/uuid" "github.com/traPtitech/traQ/model" "gopkg.in/guregu/null.v3" ) // UpdateStampArgs スタンプ情報更新引数 type UpdateStampArgs struct { Name null.String FileID uuid.NullUUID CreatorID uuid.NullUUID } // StampRepository スタンプリポジトリ type StampRepository interface { // CreateStamp スタンプを作成します // // 成功した場合、スタンプとnilを返します。 // 引数に問題がある場合、ArgumentErrorを返します。 // 既にNameが使われている場合、ErrAlreadyExistsを返します。 // DBによるエラーを返すことがあります。 CreateStamp(name string, fileID, creatorID uuid.UUID) (s *model.Stamp, err error) // UpdateStamp 指定したスタンプの情報を更新します // // 成功した場合、nilを返します。 // 存在しないスタンプの場合、ErrNotFoundを返します。 // idにuuid.Nilを指定した場合、ErrNilIDを返します。 // 更新内容に問題がある場合、ArgumentErrorを返します。 // 変更後のNameが既に使われている場合、ErrAlreadyExistsを返します。 // DBによるエラーを返すことがあります。 UpdateStamp(id uuid.UUID, args UpdateStampArgs) error // GetStamp 指定したIDのスタンプを取得します // // 成功した場合、スタンプとnilを返します。 // 存在しなかった場合、ErrNotFoundを返します。 // DBによるエラーを返すことがあります。 GetStamp(id uuid.UUID) (s *model.Stamp, err error) // DeleteStamp 指定したIDのスタンプを削除します // // 成功した場合、nilを返します。 // 既に存在しない場合、ErrNotFoundを返します。 // 引数にuuid.Nilを指定した場合、ErrNilIDを返します。 // DBによるエラーを返すことがあります。 DeleteStamp(id uuid.UUID) (err error) // GetAllStamps 全てのスタンプを取得します // // 成功した場合、スタンプの配列とnilを返します。 // DBによるエラーを返すことがあります。 GetAllStamps() (stamps []*model.Stamp, err error) // StampExists 指定したIDのスタンプが存在するかどうかを返します // // 存在する場合、trueとnilを返します。 // DBによるエラーを返すことがあります。 StampExists(id uuid.UUID) (bool, error) // StampNameExists 指定した名前のスタンプが存在するかどうかを返します // // 存在する場合、trueとnilを返します。 // DBによるエラーを返すことがあります。 StampNameExists(name string) (bool, error) }
true
4ca38f7eb62496403be3d35622c354621efeac0b
Go
Sm1Le55/codewars
/solutions/7 kyu/18 Count the Digit.go
UTF-8
252
2.8125
3
[]
no_license
[]
no_license
package kata import ( "fmt" "strconv" "strings" ) func NbDig(n int, d int) int { fmt.Println("n", n, "d", d) allSquares := "" for i := 0; i <= n; i++ { allSquares += strconv.Itoa(i * i) } return strings.Count(allSquares, strconv.Itoa(d)) }
true
dcaae0436ff3e503301160adc4e53a37c6e87131
Go
tkmagesh/IBM-Go-Feb-2021
/02-go-demos/utils/structs-demo.go
UTF-8
528
3.203125
3
[]
no_license
[]
no_license
package utils import "fmt" type Employee struct { Identity IsEmployed bool City string Orgs []string } func (e *Employee) ToggleEmploymentStatus() { e.IsEmployed = !e.IsEmployed fmt.Printf(" Inside toggle fn : %v\n", e) } func NewEmployee(id int, name string, isEmployed bool, city string) *Employee { return &Employee{Identity{id, name}, isEmployed, city, make([]string, 10)} } func (e *Employee) Display() { fmt.Printf("Id=%d, Name=%s, IsEmployed=%t, City=%s\n", e.Id, e.Name, e.IsEmployed, e.City) }
true
59d869eadc7a3841f6bc7c30ececa410f8897cf4
Go
woodbear92/Sanntid
/master/master_logic.go
UTF-8
2,892
2.53125
3
[]
no_license
[]
no_license
package master import ( "../config" "../elevator_control/elevio" "../queue" "../typedef" "math" ) const _numElevators int = config.NumElevators const _numFloors int = config.NumFloors const _numOrderButtons int = config.NumOrderButtons const highestPriority int = _numElevators func DistributeOrders(elevators [_numElevators]typedef.ElevatorData, orderFromElevator typedef.ElevatorData) [_numElevators]typedef.ElevatorData { elev := orderFromElevator.Number toElev := findElevator(elevators, orderFromElevator) for b := 0; b < _numOrderButtons; b++ { for f := 0; f < _numFloors; f++ { for e := 0; e < _numElevators; e++ { switch orderFromElevator.LocalOrders[b][f] { case typedef.Order_Received: for l := 0; l < _numElevators; l++ { if l == toElev { elevators[l].LocalOrders[b][f] = typedef.Order_Handle } else { elevators[l].LocalOrders[b][f] = typedef.Order_LightOn } } case typedef.Order_Executed: if b == elevio.BT_Cab { elevators[elev].LocalOrders[b][f] = typedef.Order_Empty } else { for l := 0; l < _numElevators; l++ { elevators[l].LocalOrders[b][f] = typedef.Order_Empty } } case typedef.Order_Handle: if b == elevio.BT_Cab { elevators[elev].LocalOrders[b][f] = typedef.Order_Handle } default: break } } } } return elevators } func RedistributeOrders(elevators [_numElevators]typedef.ElevatorData, orderFromElevator typedef.ElevatorData) [_numElevators]typedef.ElevatorData { redistributeOrders := orderFromElevator.LocalOrders newElev := findElevator(elevators, orderFromElevator) for b := 0; b < _numOrderButtons-1; b++ { for f := 0; f < _numFloors; f++ { if redistributeOrders[b][f] == typedef.Order_Handle { for e := 0; e < _numElevators; e++ { if e == newElev { elevators[e].LocalOrders[b][f] = typedef.Order_Handle } else { elevators[e].LocalOrders[b][f] = typedef.Order_LightOn } } } } } return elevators } func RecalculatePriorities(priorities [_numElevators]int) [_numElevators]int { list := priorities priority := 1 for i, elm := range priorities { if elm == highestPriority { continue } else if elm == -1 { continue } else { list[i] = priority priority += 1 } } return list } func findElevator(elevators [_numElevators]typedef.ElevatorData, orderFromElevator typedef.ElevatorData) int { toElev := orderFromElevator.Number lowestCost := math.MaxInt64 for e := 0; e < _numElevators; e++ { for b := 0; b < _numOrderButtons; b++ { for f := 0; f < _numFloors; f++ { if orderFromElevator.LocalOrders[b][f] == typedef.Order_Received { elevators[e].LocalOrders[b][f] = typedef.Order_Handle } } } cost := queue.TimeToIdle(elevators[e]) if cost < lowestCost { toElev = e lowestCost = cost } } return toElev }
true
4f3652b550852a225e2f6e16099e5869a392eb4f
Go
nyugoh/game-sites-scrapper
/requests/posting_forms.go
UTF-8
1,259
2.90625
3
[]
no_license
[]
no_license
package main import ( "net/http" "net/url" "log" "io/ioutil" ) func main() { api := "http://localhost:5000/users/login" response, err := http.PostForm(api, url.Values{ "email": { "[email protected]" }, "password": { "Shushume@20" }, }) if err != nil { log.Fatal(err) } else { //log.Println(response.Header) //log.Println(response.Cookies()) //log.Println(response.StatusCode) goHome(response.Cookies()) } defer response.Body.Close() // Clean after yourself :) } func goHome(authCookies []*http.Cookie) { // Make a request to home page with the cookie homeRequest, err := http.NewRequest("GET", "http://localhost:5000", nil) if err != nil { log.Fatal(err) } for _, cookie := range authCookies { homeRequest.AddCookie(cookie) } log.Println(homeRequest.Header) log.Println(homeRequest.Cookies()) // Make the request client := &http.Client{} jar := client.Jar url := &url.URL{} url.Scheme = "http" url.Host = "localhost:5000" url.Path = "/" jar.SetCookies(url.String(), authCookies) http.SetCookie() res, err := client.Do(homeRequest) if err != nil { log.Fatal(err) } defer res.Body.Close() log.Println(res.Header) log.Println(res.StatusCode) body, _ := ioutil.ReadAll(res.Body) log.Println(string(body)) }
true
f7481699d8efb17c5445761735648f99ff387e95
Go
gruntwork-io/cloud-nuke
/aws/resources/launch_template_test.go
UTF-8
2,668
2.625
3
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
package resources import ( awsgo "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/ec2" "github.com/aws/aws-sdk-go/service/ec2/ec2iface" "github.com/gruntwork-io/cloud-nuke/config" "github.com/gruntwork-io/cloud-nuke/telemetry" "github.com/stretchr/testify/require" "regexp" "testing" "time" ) type mockedLaunchTemplate struct { ec2iface.EC2API DescribeLaunchTemplatesOutput ec2.DescribeLaunchTemplatesOutput DeleteLaunchTemplateOutput ec2.DeleteLaunchTemplateOutput } func (m mockedLaunchTemplate) DescribeLaunchTemplates(input *ec2.DescribeLaunchTemplatesInput) (*ec2.DescribeLaunchTemplatesOutput, error) { return &m.DescribeLaunchTemplatesOutput, nil } func (m mockedLaunchTemplate) DeleteLaunchTemplate(input *ec2.DeleteLaunchTemplateInput) (*ec2.DeleteLaunchTemplateOutput, error) { return &m.DeleteLaunchTemplateOutput, nil } func TestLaunchTemplate_GetAll(t *testing.T) { telemetry.InitTelemetry("cloud-nuke", "") t.Parallel() now := time.Now() testName1 := "test-launch-template1" testName2 := "test-launch-template2" lt := LaunchTemplates{ Client: mockedLaunchTemplate{ DescribeLaunchTemplatesOutput: ec2.DescribeLaunchTemplatesOutput{ LaunchTemplates: []*ec2.LaunchTemplate{ { LaunchTemplateName: awsgo.String(testName1), CreateTime: awsgo.Time(now), }, { LaunchTemplateName: awsgo.String(testName2), CreateTime: awsgo.Time(now.Add(1)), }, }, }, }, } tests := map[string]struct { configObj config.ResourceType expected []string }{ "emptyFilter": { configObj: config.ResourceType{}, expected: []string{testName1, testName2}, }, "nameExclusionFilter": { configObj: config.ResourceType{ ExcludeRule: config.FilterRule{ NamesRegExp: []config.Expression{{ RE: *regexp.MustCompile(testName1), }}}, }, expected: []string{testName2}, }, "timeAfterExclusionFilter": { configObj: config.ResourceType{ ExcludeRule: config.FilterRule{ TimeAfter: awsgo.Time(now), }}, expected: []string{testName1}, }, } for name, tc := range tests { t.Run(name, func(t *testing.T) { names, err := lt.getAll(config.Config{ LaunchTemplate: tc.configObj, }) require.NoError(t, err) require.Equal(t, tc.expected, awsgo.StringValueSlice(names)) }) } } func TestLaunchTemplate_NukeAll(t *testing.T) { telemetry.InitTelemetry("cloud-nuke", "") t.Parallel() lt := LaunchTemplates{ Client: mockedLaunchTemplate{ DeleteLaunchTemplateOutput: ec2.DeleteLaunchTemplateOutput{}, }, } err := lt.nukeAll([]*string{awsgo.String("test")}) require.NoError(t, err) }
true
2172927f4000e47f0b677e49f625513fd13e503f
Go
haproxytech/client-native
/misc/reflect.go
UTF-8
1,288
2.53125
3
[ "Apache-2.0" ]
permissive
[ "Apache-2.0" ]
permissive
// Copyright 2019 HAProxy Technologies // // 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 misc import "reflect" // IsZeroValue is a helper method for reflect, checks if reflect.Value has zero value func IsZeroValue(v reflect.Value) bool { switch v.Kind() { //nolint:exhaustive case reflect.Array, reflect.String: return v.Len() == 0 case reflect.Bool: return !v.Bool() case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: return v.Int() == 0 case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: return v.Uint() == 0 case reflect.Float32, reflect.Float64: return v.Float() == 0 case reflect.Interface, reflect.Map, reflect.Ptr, reflect.Slice: return v.IsNil() } return false }
true
b1805f41ffe0dec46ac25dc65d2d6715f305fd62
Go
gregpr07/bridge-decoder
/utils/utils.go
UTF-8
683
2.65625
3
[]
no_license
[]
no_license
package utils import ( "strings" ) func MakeEtherscanLink(hash string) string { return strings.Join([]string{"https://etherscan.io/tx/", hash}, "") } // this function recursively goes through trace and checks if matching function returns true // matching function just means the correct function call to certain (bridge) smart contract func RecursivelyCheckTrace(txTrace TxTrace, checkFunc func(TxTrace, *TxTrace) bool, resultTrace *TxTrace) bool { if checkFunc(txTrace, resultTrace) { return true } for i := 0; i < len(txTrace.Calls); i++ { // txTrace.Calls[i] if RecursivelyCheckTrace(txTrace.Calls[i], checkFunc, resultTrace) { return true } } return false }
true
aee81e139ce08ed2303d23ed49efefd7dbed655e
Go
jeckbjy/test-go
/zipkin/main.go
UTF-8
1,929
2.640625
3
[]
no_license
[]
no_license
package main import ( "bytes" "log" "net/http" "github.com/gorilla/mux" "github.com/openzipkin/zipkin-go" "github.com/openzipkin/zipkin-go/model" zipkinhttp "github.com/openzipkin/zipkin-go/middleware/http" reporterhttp "github.com/openzipkin/zipkin-go/reporter/http" ) const endpointURL = "http://localhost:9411/api/v2/spans" func newTracer() (*zipkin.Tracer, error) { // The reporter sends traces to zipkin server reporter := reporterhttp.NewReporter(endpointURL) // Local endpoint represent the local service information localEndpoint := &model.Endpoint{ServiceName: "my_service", Port: 8080} // Sampler tells you which traces are going to be sampled or not. In this case we will record 100% (1.00) of traces. sampler, err := zipkin.NewCountingSampler(1) if err != nil { return nil, err } t, err := zipkin.NewTracer( reporter, zipkin.WithSampler(sampler), zipkin.WithLocalEndpoint(localEndpoint), ) if err != nil { return nil, err } return t, err } func main() { tracer, err := newTracer() if err != nil { log.Fatal(err) } r := mux.NewRouter() r.HandleFunc("/", HomeHandlerFactory(http.DefaultClient)) r.HandleFunc("/foo", FooHandler) r.Use(zipkinhttp.NewServerMiddleware( tracer, zipkinhttp.SpanName("request")), // name for request span ) log.Printf("start server") log.Fatal(http.ListenAndServe(":8080", r)) } func HomeHandlerFactory(client *http.Client) func(http.ResponseWriter, *http.Request) { return func(w http.ResponseWriter, r *http.Request) { body := bytes.NewBufferString("") res, err := client.Post("http://example.com", "application/json", body) if err != nil { w.WriteHeader(http.StatusInternalServerError) return } if res.StatusCode > 399 { w.WriteHeader(http.StatusInternalServerError) return } w.WriteHeader(http.StatusOK) } } func FooHandler(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) }
true
5d4bd3b2a838884dbaa3b7f3ba07e4804c12f89e
Go
SPANDigital/presidium
/pkg/domain/service/conversion/markdown/parse.go
UTF-8
580
2.65625
3
[]
permissive
[]
permissive
package markdown import ( "github.com/SPANDigital/presidium-hugo/pkg/filesystem" "gopkg.in/yaml.v2" ) type Markdown struct { FrontMatter FrontMatter Content string } func Parse(path string) (*Markdown, error) { b, err := filesystem.AFS.ReadFile(path) if err != nil { return nil, err } matches := MarkdownRe.FindSubmatch(b) if matches != nil { var fm FrontMatter err = yaml.Unmarshal(matches[2], &fm) if err != nil { return nil, err } return &Markdown{ FrontMatter: fm, Content: string(matches[4]), }, nil } return &Markdown{}, nil }
true
05edbbe5a8abd5b0cdc42ffc688ae8427207b6ce
Go
appconf/storage
/redis/redis.go
UTF-8
3,119
3.03125
3
[ "Apache-2.0" ]
permissive
[ "Apache-2.0" ]
permissive
package redis import ( "fmt" "time" "github.com/appconf/log" "github.com/appconf/storage" "github.com/go-redis/redis" "github.com/mitchellh/mapstructure" ) type redisStorageConfig struct { DB int Hostname string Port uint Interval int64 Password string BuffSize int64 } //DefaultBuffSize storage与engine交互的channel的默认大小 const DefaultBuffSize = 1024 //DefaultInterval 向redis取数据的默认间隔 const DefaultInterval = 300 //Driver 用于实现storage.Driver接口 type Driver struct{} //Open 创建redis 类型的storage func (d *Driver) Open(logger log.Logger, cfg map[string]interface{}) (storage.Storage, error) { var redisOpt redisStorageConfig err := mapstructure.Decode(cfg, &redisOpt) if err != nil { return nil, err } rc := redis.NewClient(&redis.Options{ Addr: fmt.Sprintf("%s:%d", redisOpt.Hostname, redisOpt.Port), DB: redisOpt.DB, Password: redisOpt.Password, }) _, err = rc.Ping().Result() if err != nil { return nil, err } var buffSize int64 if redisOpt.BuffSize <= 0 { buffSize = DefaultBuffSize } else { buffSize = redisOpt.BuffSize } var interval int64 if redisOpt.Interval < 1 { interval = DefaultInterval } else { interval = redisOpt.Interval } return &Storage{ rc: rc, buffSize: buffSize, stopCh: make(chan int), interval: time.Duration(interval) * time.Second, log: logger, }, nil } //Storage redis存储器实现 type Storage struct { rc *redis.Client isStop bool stopCh chan int buffSize int64 interval time.Duration log log.Logger } //Get 获取指定keys数据 func (s *Storage) Get(keys []string) (ch chan []storage.Data, err error) { ch = make(chan []storage.Data, s.buffSize) go s.poll(keys, ch) return ch, nil } func (s *Storage) getData(keys []string) []storage.Data { data := make([]storage.Data, 0) values, err := s.rc.MGet(keys...).Result() if err != nil { s.log.Errorf("redis storage failed to get data, error: %v", err) } else { for idx, key := range keys { if values[idx] != redis.Nil { data = append(data, storage.Data{ Key: key, Value: values[idx], }) } } } return data } func (s *Storage) poll(keys []string, ch chan []storage.Data) { go func() { ticker := time.NewTicker(s.interval) defer ticker.Stop() data := s.getData(keys) ch <- data for { select { case <-s.stopCh: _ = s.rc.Close() s.isStop = true close(ch) return case <-ticker.C: data := s.getData(keys) ch <- data } } }() } //Stop 停止从Storage获取数据 func (s *Storage) Stop() error { if s.isStop { return nil } s.stopCh <- 1 return nil } //Success 汇报渲染成功 func (s *Storage) Success(template string, kvs []map[string]interface{}) { s.log.Infof("template: %s rendering success", template) return } //Error 汇报渲染错误 func (s *Storage) Error(template string, kvs []map[string]interface{}, err error) { s.log.Errorf("template: %s rendering failure, error: %v", template, err) return } func init() { storage.Register("redis", &Driver{}) }
true
207b9f67176c2161ec036f363a27e067e09492bb
Go
omniskop/renderer
/src/renderer/camera/camera.go
UTF-8
205
2.625
3
[]
no_license
[]
no_license
package camera import ( "space/ray" "vec3" ) type Camera interface { GetRayForPixel(x float64, y float64) ray.Ray GetWidth() int GetHeight() int GetPosition() vec3.Vec3 GetDirection() vec3.Vec3 }
true
b24ef2ae0cadba6410b6aa40bde6291285844832
Go
jaxxstorm/cloud-resource-counter
/activityMonitor.go
UTF-8
3,535
3.421875
3
[ "BSD-2-Clause" ]
permissive
[ "BSD-2-Clause" ]
permissive
/****************************************************************************** Cloud Resource Counter File: activityMonitor.go Summary: The ActivityMonitor interface along with a Terminal-based monitor. ******************************************************************************/ package main import ( "fmt" "io" "strings" "github.com/aws/aws-sdk-go/aws/awserr" color "github.com/logrusorgru/aurora" ) // ActivityMonitor is an interface that shows activity to the user while // the tool runs. It handles the start of an action, checking for an error, // displaying the error or the actual result. type ActivityMonitor interface { Message(string, ...interface{}) StartAction(string, ...interface{}) CheckError(error) bool ActionError(string, ...interface{}) EndAction(string, ...interface{}) Exit(int) } // TerminalActivityMonitor is our terminal-based activity monitor. It allows // the caller to supply an io.Writer to direct output to. type TerminalActivityMonitor struct { io.Writer ExitFn func(int) } // Message constructs a simple message from the format string and arguments // and sends it to the associated io.Writer. func (tam *TerminalActivityMonitor) Message(format string, v ...interface{}) { fmt.Fprint(tam.Writer, fmt.Sprintf(format, v...)) } // StartAction constructs a structured message to the associated Writer func (tam *TerminalActivityMonitor) StartAction(format string, v ...interface{}) { tam.Message(" * %s...", fmt.Sprintf(format, v...)) } // CheckError checks the supplied error. If no error, then it returns immediately. // Otherwise, it checks for specific AWS errors (returning a specific error message). // If no specific AWS error found, it simply sends the error message to the ActionError // method. func (tam *TerminalActivityMonitor) CheckError(err error) bool { // If it is nil, get out now! if err == nil { return false } // Is this an AWS Error? if aerr, ok := err.(awserr.Error); ok { // Split the message by newline parts := strings.Split(aerr.Message(), "\n") // Switch on the error code for known error conditions... switch aerr.Code() { case "NoCredentialProviders": // TODO Can we establish this failure earlier? When the session is created? tam.ActionError("Either the profile does not exist, is misspelled or credentials are not stored there.") break case "AccessDeniedException": // Construct a message by taking the first part of the string up to a newline character tam.ActionError(parts[0]) case "InvalidClientTokenId": // Construct a message that indicates an unsupported region tam.ActionError("The region is not supported for this account.") default: tam.ActionError("%s: %s", aerr.Code(), parts[0]) } } else { tam.ActionError("%v", err) } return true } // ActionError formats the supplied format string (and associated parameters) in // RED and exits the tool. func (tam *TerminalActivityMonitor) ActionError(format string, v ...interface{}) { // Display an error message (and newline) fmt.Fprintln(tam.Writer, color.Red(fmt.Sprintf(format, v...))) fmt.Fprintln(tam.Writer) // Exit the program tam.Exit(1) } // EndAction receives a format string (and arguments) and sends to the supplied // Writer. func (tam *TerminalActivityMonitor) EndAction(format string, v ...interface{}) { fmt.Fprintln(tam.Writer, fmt.Sprintf(format, v...)) } // Exit causes the application to exit func (tam *TerminalActivityMonitor) Exit(resultCode int) { if tam.ExitFn != nil { tam.ExitFn(resultCode) } }
true
105f115bbff2a2f443ec9b4ecdedc56174a3651d
Go
DarinM223/myhumminglist
/hummingbird_test.go
UTF-8
7,138
2.625
3
[]
no_license
[]
no_license
package main import ( "reflect" "testing" ) var diffHummingbirdTests = []struct { oldList *HummingbirdAnimeList newList *HummingbirdAnimeList expectedChanges []Change }{ { oldList: &HummingbirdAnimeList{ anime: map[int]HummingbirdAnime{ 0: HummingbirdAnime{ NumEpisodesWatched: 11, AnimeStatus: "currently-watching", NumRewatchedTimes: 0, IsRewatching: false, Data: HummingbirdAnimeData{Id: 0}, }, 2: HummingbirdAnime{ NumEpisodesWatched: 5, AnimeStatus: "currently-watching", NumRewatchedTimes: 1, IsRewatching: true, Data: HummingbirdAnimeData{Id: 2}, }, }, }, newList: &HummingbirdAnimeList{ anime: map[int]HummingbirdAnime{ 1: HummingbirdAnime{ NumEpisodesWatched: 1, AnimeStatus: "currently-watching", NumRewatchedTimes: 0, IsRewatching: false, Data: HummingbirdAnimeData{Id: 1}, }, 2: HummingbirdAnime{ NumEpisodesWatched: 6, AnimeStatus: "currently-watching", NumRewatchedTimes: 1, IsRewatching: true, Data: HummingbirdAnimeData{Id: 2}, }, }, }, expectedChanges: []Change{ DeleteChange{ Anime: HummingbirdAnime{ NumEpisodesWatched: 11, AnimeStatus: "currently-watching", NumRewatchedTimes: 0, IsRewatching: false, Data: HummingbirdAnimeData{Id: 0}, }, }, EditChange{ OldAnime: HummingbirdAnime{ NumEpisodesWatched: 5, AnimeStatus: "currently-watching", NumRewatchedTimes: 1, IsRewatching: true, Data: HummingbirdAnimeData{Id: 2}, }, NewAnime: HummingbirdAnime{ NumEpisodesWatched: 6, AnimeStatus: "currently-watching", NumRewatchedTimes: 1, IsRewatching: true, Data: HummingbirdAnimeData{Id: 2}, }, }, AddChange{ Anime: HummingbirdAnime{ NumEpisodesWatched: 1, AnimeStatus: "currently-watching", NumRewatchedTimes: 0, IsRewatching: false, Data: HummingbirdAnimeData{Id: 1}, }, }, }, }, { oldList: &HummingbirdAnimeList{ anime: map[int]HummingbirdAnime{ 0: HummingbirdAnime{ NumEpisodesWatched: 11, AnimeStatus: "currently-watching", NumRewatchedTimes: 0, IsRewatching: true, Data: HummingbirdAnimeData{Id: 0}, }, 1: HummingbirdAnime{ NumEpisodesWatched: 12, AnimeStatus: "completed", NumRewatchedTimes: 1, IsRewatching: false, Data: HummingbirdAnimeData{Id: 1}, }, }, }, newList: &HummingbirdAnimeList{ anime: map[int]HummingbirdAnime{ 0: HummingbirdAnime{ NumEpisodesWatched: 11, AnimeStatus: "currently-watching", NumRewatchedTimes: 0, IsRewatching: true, Data: HummingbirdAnimeData{Id: 0}, }, 1: HummingbirdAnime{ NumEpisodesWatched: 12, AnimeStatus: "completed", NumRewatchedTimes: 1, IsRewatching: false, Data: HummingbirdAnimeData{Id: 1}, }, }, }, expectedChanges: nil, }, } func TestDiffHummingbirdLists(t *testing.T) { for _, test := range diffHummingbirdTests { changes := DiffHummingbirdLists(test.oldList, test.newList) for _, expectedChange := range test.expectedChanges { changeEqual := false for _, actualChange := range changes { if reflect.DeepEqual(actualChange, expectedChange) { changeEqual = true break } } if !changeEqual { t.Errorf("TestDiffHummingbirdLists failed: expected %+v got %+v", test.expectedChanges, changes) } } } } func TestHummingbirdAnimeList_FetchFromEmpty(t *testing.T) { list := NewHummingbirdAnimeList("darin_minamoto", "") if err := list.Fetch(); err != nil { t.Errorf("TestHummingbirdAnimeList_FetchFromEmpty failed: " + err.Error()) } if len(list.changes) <= 0 { t.Errorf("TestHummingbirdAnimeList_FetchFromEmpty failed: list changes haven't been populated") } if len(list.anime) <= 0 { t.Errorf("TestHummingbirdAnimeList_FetchFromEmpty failed: anime changes haven't been populated") } for _, change := range list.changes { switch ch := change.(type) { case AddChange: if ch.Anime.ID().Get(Hummingbird) == 0 { t.Errorf("TestHummingbirdAnimeList_FetchFromEmpty failed: anime id should not be zero") } default: t.Errorf("TestHummingbirdAnimeList_FetchFromEmpty failed: there should only be Add changes") } } } func TestHummingbirdAnimeList_AddHummingbirdAnime(t *testing.T) { list := NewHummingbirdAnimeList("darin_minamoto", "") anime := HummingbirdAnime{ NumEpisodesWatched: 12, NumRewatchedTimes: 2, AnimeStatus: "currently-watching", Data: HummingbirdAnimeData{ Id: 50, MalID: 20, Title: "Sample text", }, } list.Add(anime) if !reflect.DeepEqual(list.anime[50], anime) { t.Errorf("TestHummingbirdAnimeList_AddHummingbirdAnime failed: expected: %+v, got %+v", anime, list.anime[50]) } if !reflect.DeepEqual(list.changes[len(list.changes)-1], AddChange{anime}) { t.Errorf("TestHummingbirdAnimeList_AddHummingbirdAnime failed: expected change %+v", AddChange{anime}) } } func TestHummingbirdAnimeList_EditHummingbirdAnime(t *testing.T) { list := NewHummingbirdAnimeList("darin_minamoto", "") oldAnime := HummingbirdAnime{ NumEpisodesWatched: 11, NumRewatchedTimes: 2, AnimeStatus: "currently-watching", Data: HummingbirdAnimeData{ Id: 50, MalID: 20, Title: "Sample text", }, } newAnime := HummingbirdAnime{ NumEpisodesWatched: 12, NumRewatchedTimes: 3, AnimeStatus: "completed", Data: HummingbirdAnimeData{ Id: 50, MalID: 20, Title: "Sample text", }, } list.Add(oldAnime) list.Edit(newAnime) if !reflect.DeepEqual(list.anime[50], newAnime) { t.Errorf("TestHummingbirdAnimeList_EditHummingbirdAnime failed: expected: %+v, got %+v", newAnime, list.anime[50]) } if !reflect.DeepEqual(list.changes[len(list.changes)-1], EditChange{OldAnime: oldAnime, NewAnime: newAnime}) { t.Errorf("TestHummingbirdAnimeList_EditHummingbirdAnime failed: expected change %+v", EditChange{OldAnime: oldAnime, NewAnime: newAnime}) } } func TestHummingbirdAnimeList_RemoveHummingbirdAnime(t *testing.T) { list := NewHummingbirdAnimeList("darin_minamoto", "") anime := HummingbirdAnime{ NumEpisodesWatched: 12, NumRewatchedTimes: 2, AnimeStatus: "currently-watching", Data: HummingbirdAnimeData{ Id: 50, MalID: 20, Title: "Sample text", }, } list.Add(anime) list.Remove(anime) if _, ok := list.anime[50]; ok { t.Errorf("TestHummingbirdAnimeList_RemoveHummingbirdAnime failed: expected anime to not exist after removed") } if !reflect.DeepEqual(list.changes[len(list.changes)-1], DeleteChange{Anime: anime}) { t.Errorf("TestHummingbirdAnimeList_RemoveHummingbirdAnime failed: expected change %+v", DeleteChange{Anime: anime}) } }
true
c92e862c0f670e41b39f84d9127ab63cf3a91f2f
Go
shizuokago/blog
/app/datastore/meta.go
UTF-8
993
2.78125
3
[]
no_license
[]
no_license
package datastore import ( "time" "cloud.google.com/go/datastore" ) type Meta struct { Key *datastore.Key `datastore:"-" json:"-"` Version int `datastore:",noindex" json:"version"` Deleted bool `json:"deleted"` CreatedAt time.Time `json:"createdAt"` UpdatedAt time.Time `json:"updatedAt"` } type HasVersion interface { IncrementVersion() HasTime } type HasTime interface { SetTime() HasKey } type HasKey interface { GetKey() *datastore.Key SetKey(*datastore.Key) } func (m *Meta) GetKey() *datastore.Key { return m.Key } func (m *Meta) SetKey(key *datastore.Key) { m.Key = key } func (m *Meta) SetTime() { if m.CreatedAt.IsZero() { m.CreatedAt = time.Now() } m.UpdatedAt = time.Now() } func (m *Meta) GetCreatedAt() time.Time { return m.CreatedAt } func (m *Meta) GetUpdatedAt() time.Time { return m.UpdatedAt } func (m *Meta) GetVersion() int { return m.Version } func (m *Meta) IncrementVersion() { m.Version++ }
true
94ead8b6a61d9392e8452a2b1bca1ae5ce81122a
Go
baishuai/leetcode
/algorithms/p609/609_test.go
UTF-8
768
2.84375
3
[ "Apache-2.0" ]
permissive
[ "Apache-2.0" ]
permissive
package p609 import ( "sort" "testing" "github.com/stretchr/testify/assert" ) func Test0(t *testing.T) { exp := make(map[string]string) exp["root/a/1.txt"] = "abcd" exp["root/a/2.txt"] = "efgh" assert.Equal(t, exp, getfile("root/a 1.txt(abcd) 2.txt(efgh)")) } func Test1(t *testing.T) { exp := make(map[string][]string, 0) exp["root/a/1.txt"] = []string{"root/a/1.txt", "root/c/3.txt"} exp["root/4.txt"] = []string{"root/4.txt", "root/a/2.txt", "root/c/d/4.txt"} ans := findDuplicate([]string{ "root/a 1.txt(abcd) 2.txt(efgh)", "root/c 3.txt(abcd)", "root/c/d 4.txt(efgh)", "root 4.txt(efgh)", }) ansmap := make(map[string][]string) for _, paths := range ans { sort.Strings(paths) ansmap[paths[0]] = paths } assert.Equal(t, exp, ansmap) }
true
3242e3e932760d1762d45960feab3501e182dedc
Go
deep1310/PaymentTest
/services/payment_service.go
UTF-8
1,973
2.796875
3
[]
no_license
[]
no_license
package services import ( "payment/domain/payment" "payment/utils/errors" ) var ( PaymentService paymentServiceInterface = &paymentServiceRepo{} ) type paymentServiceRepo struct{} type paymentServiceInterface interface { CreatePaymentOrder(*payment.PaymentItemReq) (*payment.CreatePaymentResp, *errors.RestErr) UpdatePaymentOrder(*payment.PaymentUpdateReq) *errors.RestErr UpdatePaymentTransactionId(string) *errors.RestErr } func (s *paymentServiceRepo) CreatePaymentOrder(paymentReq *payment.PaymentItemReq) (*payment.CreatePaymentResp, *errors.RestErr) { paymentCreate := &payment.Payment{ PgName: "RazorPay", OrderId: paymentReq.OrderId, Amount: paymentReq.Amount, PaymentType: paymentReq.PaymentType, Status: "INITIATED", } if err := paymentCreate.PaymentSave(); err != nil { return nil, err } /* Here we now call the pg for first factor authentication and it returns the status and pgTxnId and we save the same to our payment db */ pgTransId := "123" if pgIdUpdateErr := s.UpdatePaymentTransactionId(pgTransId); pgIdUpdateErr != nil { return nil, pgIdUpdateErr } paymentResp := &payment.CreatePaymentResp{ RedirectUrl: "https://razorpay.com", } return paymentResp, nil } func (s *paymentServiceRepo) UpdatePaymentTransactionId(pgTransactionId string) *errors.RestErr { pgIdUpdate := &payment.PGIdUpdateReq{ PgId: pgTransactionId, Status: "SUCCESS", } if pgTransactionId == "" { pgIdUpdate.Status = "FAILED" } if err := pgIdUpdate.PaymentGatewayUpdate(); err != nil { return err } return nil } /* this method will be call by the pg as web-hook after the second factor is success form here the api gateway complete order will be called */ func (s *paymentServiceRepo) UpdatePaymentOrder(req *payment.PaymentUpdateReq) *errors.RestErr { paymentUpdate := &payment.Payment{ Id: req.PaymentId, Status: req.Status, } paymentUpdate.UpdatePaymentStatus() return nil }
true
689ce4c1ed3f4bbf852102e7c9dbef5b71f45470
Go
danhouldsworth/helloLanguages
/IO/Networking/TelnetServer/telnet2.go
UTF-8
670
3.453125
3
[]
no_license
[]
no_license
// 3. Done package main import ( "net" ) func main() { listener, _ := net.Listen("tcp", ":4000") for { conn, _ := listener.Accept() go handleConnection(conn) } } func handleConnection(c net.Conn) { welcome := []byte("\n\n --- Welcome to Telnet Echo & Bye in Go! --- \n\n") echo := []byte("Server echo service : ") bye := []byte("\n\n --- Bye for now!! --- \n\n") c.Write(welcome) for { messageBuffer := make([]byte, 1024) c.Read(messageBuffer) if messageBuffer[0] == 'q' && messageBuffer[1] == 'u' && messageBuffer[2] == 'i' && messageBuffer[3] == 't' { c.Write(bye) c.Close() } else { c.Write(append(echo, messageBuffer...)) } } }
true
d40744506ef76200921f261366116db4e962b3e6
Go
p-ob/go-riot
/lol/league_test.go
UTF-8
7,202
2.78125
3
[ "MIT" ]
permissive
[ "MIT" ]
permissive
package lol import ( "context" "encoding/json" "fmt" "math/rand" "net/http" "reflect" "testing" "time" ) func TestLeagueService_GetBySummoner(t *testing.T) { // set up data BaseURL = "http://example.com" region := Na s1 := rand.NewSource(time.Now().UnixNano()) r1 := rand.New(s1) league := generateLeagueDto() summonerID := r1.Int63() pathPart := fmt.Sprintf("/%s/by-summoner/%v", addRegionToString(leaguePathPart, region), summonerID) getResponse := make(map[int64]LeagueDto) getResponse[summonerID] = league jsonByteArray, _ := json.Marshal(getResponse) _, mux, server, client := mockClient(region) defer server.Close() mux.HandleFunc(pathPart, func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") w.WriteHeader(http.StatusOK) w.Write(jsonByteArray) }) ctx := context.Background() retrievedLeagueMap, err := client.League.GetBySummoner(ctx, summonerID) retrievedLeague := (*retrievedLeagueMap)[summonerID] if err != nil { t.Errorf("expected nil, got %+v", err) } if !reflect.DeepEqual(league, retrievedLeague) { t.Errorf("expected %+v, got %+v", league, retrievedLeague) } } func TestLeagueService_GetEntriesBySummoner(t *testing.T) { // set up data BaseURL = "http://example.com" region := Na s1 := rand.NewSource(time.Now().UnixNano()) r1 := rand.New(s1) league := generateLeagueDto() summonerID := r1.Int63() pathPart := fmt.Sprintf("/%s/by-summoner/%v/entry", addRegionToString(leaguePathPart, region), summonerID) getResponse := make(map[int64]LeagueDto) getResponse[summonerID] = league jsonByteArray, _ := json.Marshal(getResponse) _, mux, server, client := mockClient(region) defer server.Close() mux.HandleFunc(pathPart, func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") w.WriteHeader(http.StatusOK) w.Write(jsonByteArray) }) ctx := context.Background() retrievedLeagueMap, err := client.League.GetEntriesBySummoner(ctx, summonerID) retrievedLeague := (*retrievedLeagueMap)[summonerID] if err != nil { t.Errorf("expected nil, got %+v", err) } if !reflect.DeepEqual(league, retrievedLeague) { t.Errorf("expected %+v, got %+v", league, retrievedLeague) } } func TestLeagueService_GetBySummoner_MoreThan10(t *testing.T) { // set up data BaseURL = "http://example.com" region := Na s1 := rand.NewSource(time.Now().UnixNano()) r1 := rand.New(s1) const nSummoners = 11 getResponse := make(map[int64]LeagueDto, nSummoners) summonerIDs := make([]int64, nSummoners) for i := 0; i < nSummoners; i++ { sID := r1.Int63() l := generateLeagueDto() summonerIDs[i] = sID getResponse[sID] = l } pathPart := fmt.Sprintf( "/%s/by-summoner/%v", addRegionToString(leaguePathPart, region), int64ArrayToCommaDelimitedList(summonerIDs), ) jsonByteArray, _ := json.Marshal(getResponse) _, mux, server, client := mockClient(region) defer server.Close() mux.HandleFunc(pathPart, func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") w.WriteHeader(http.StatusOK) w.Write(jsonByteArray) }) ctx := context.Background() retrievedLeagueMap, err := client.League.GetBySummoner(ctx, summonerIDs...) if err == nil { t.Errorf("expected error, got %+v", err) } if retrievedLeagueMap != nil { t.Errorf("expected nil, got %+v", retrievedLeagueMap) } } func TestLeagueService_GetEntriesBySummoner_MoreThan10(t *testing.T) { // set up data BaseURL = "http://example.com" region := Na s1 := rand.NewSource(time.Now().UnixNano()) r1 := rand.New(s1) const nSummoners = 11 getResponse := make(map[int64]LeagueDto, nSummoners) summonerIDs := make([]int64, nSummoners) for i := 0; i < nSummoners; i++ { sID := r1.Int63() l := generateLeagueDto() summonerIDs[i] = sID getResponse[sID] = l } pathPart := fmt.Sprintf( "/%s/by-summoner/%v/entry", addRegionToString(leaguePathPart, region), int64ArrayToCommaDelimitedList(summonerIDs), ) jsonByteArray, _ := json.Marshal(getResponse) _, mux, server, client := mockClient(region) defer server.Close() mux.HandleFunc(pathPart, func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") w.WriteHeader(http.StatusOK) w.Write(jsonByteArray) }) ctx := context.Background() retrievedLeagueMap, err := client.League.GetEntriesBySummoner(ctx, summonerIDs...) if err == nil { t.Errorf("expected error, got %+v", err) } if retrievedLeagueMap != nil { t.Errorf("expected nil, got %+v", retrievedLeagueMap) } } func TestLeagueService_GetChallenger(t *testing.T) { // set up data BaseURL = "http://example.com" region := Na league := generateLeagueDto() pathPart := fmt.Sprintf("/%s/challenger", addRegionToString(leaguePathPart, region)) jsonByteArray, _ := json.Marshal(league) _, mux, server, client := mockClient(region) defer server.Close() mux.HandleFunc(pathPart, func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") w.WriteHeader(http.StatusOK) w.Write(jsonByteArray) }) ctx := context.Background() retrievedLeague, err := client.League.GetChallenger(ctx) if err != nil { t.Errorf("expected nil, got %+v", err) } if !reflect.DeepEqual(league, *retrievedLeague) { t.Errorf("expected %+v, got %+v", league, *retrievedLeague) } } func TestLeagueService_GetMaster(t *testing.T) { // set up data BaseURL = "http://example.com" region := Na league := generateLeagueDto() pathPart := fmt.Sprintf("/%s/master", addRegionToString(leaguePathPart, region)) jsonByteArray, _ := json.Marshal(league) _, mux, server, client := mockClient(region) defer server.Close() mux.HandleFunc(pathPart, func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") w.WriteHeader(http.StatusOK) w.Write(jsonByteArray) }) ctx := context.Background() retrievedLeague, err := client.League.GetMaster(ctx) if err != nil { t.Errorf("expected nil, got %+v", err) } if !reflect.DeepEqual(league, *retrievedLeague) { t.Errorf("expected %+v, got %+v", league, *retrievedLeague) } } func generateLeagueDto() LeagueDto { s1 := rand.NewSource(time.Now().UnixNano()) r1 := rand.New(s1) return LeagueDto{ Entries: []LeagueEntryDto{generateLeagueEntryDto()}, Name: randString(10), ParticipantID: r1.Int63(), Queue: randString(10), Tier: randString(10), } } func generateLeagueEntryDto() LeagueEntryDto { s1 := rand.NewSource(time.Now().UnixNano()) r1 := rand.New(s1) return LeagueEntryDto{ Division: randString(10), IsFreshBlood: false, IsHotStreak: false, IsInactive: false, IsVeteran: false, LeaguePoints: r1.Int(), MiniSeries: generateMiniSeriesDto(), PlayerOrTeamID: r1.Int63(), PlayerOrTeamName: randString(10), PlayStyle: randString(10), Wins: r1.Int(), } } func generateMiniSeriesDto() MiniSeriesDto { s1 := rand.NewSource(time.Now().UnixNano()) r1 := rand.New(s1) return MiniSeriesDto{ Losses: r1.Int(), Progress: randString(10), Target: r1.Int(), Wins: r1.Int(), } }
true
512504b6045320f8135673d809ce4b5d90a6a55d
Go
uphy/elastalert-mail-gateway
/pkgs/elastalert/alerts.go
UTF-8
3,669
2.859375
3
[]
no_license
[]
no_license
package elastalert import ( "bufio" "bytes" "encoding/json" "fmt" "io" "strings" "github.com/ghodss/yaml" "github.com/uphy/elastalert-mail-gateway/pkgs/jsonutil" ) type ( Alerts []*Alert Alert struct { Body string `json:"body"` Doc jsonutil.Object `json:"doc"` } ) const AlertSeparator = "\n----------------------------------------\n" func (a Alert) String() string { buf := new(bytes.Buffer) buf.WriteString(a.Body) buf.WriteString("\n\n") for k, v := range a.Doc { buf.WriteString(k) buf.WriteString(": ") b, err := json.MarshalIndent(v, "", " ") var value string if err != nil { value = fmt.Sprintf("<failed to marshal:%v>", err) } else { value = string(b) } buf.WriteString(value) buf.WriteString("\n") } return buf.String() } func ParseMailBody(body string) (Alerts, error) { entries := strings.Split(body, AlertSeparator) v := []*Alert{} for _, entry := range entries { entry = strings.TrimRight(entry, "\n") if len(entry) == 0 { continue } e, err := parseMailBodyEntry(entry) if err != nil { return nil, err } v = append(v, e) } return v, nil } func parseMailBodyEntry(body string) (*Alert, error) { reader := bufio.NewReader(strings.NewReader(body)) bodyText := new(bytes.Buffer) jsonBody := new(bytes.Buffer) waitForBraces := false waitForBrackets := false l: for { b, _, err := reader.ReadLine() if err != nil { if err == io.EOF { break } return nil, err } line := string(b) if waitForBraces || waitForBrackets { // json object or json array content switch line { case "]": if waitForBrackets { waitForBrackets = false jsonBody.WriteString("]") continue l } case "}": if waitForBraces { waitForBraces = false jsonBody.WriteString("}") continue l } } if waitForBraces || waitForBrackets { jsonBody.WriteString(line) jsonBody.WriteString("\n") } } else { // json key value or message body colonIndex := strings.Index(line, ":") if colonIndex > 0 { if jsonBody.Len() > 0 { if !waitForBraces && !waitForBrackets { jsonBody.WriteString(",") } jsonBody.WriteString("\n") } else { jsonBody.WriteString("{") } key := line[0:colonIndex] value := line[colonIndex+2:] switch value { case "[": waitForBrackets = true case "{": waitForBraces = true } jsonBody.WriteString(fmt.Sprintf(`"%s": %s`, key, value)) } else { if bodyText.Len() > 0 { bodyText.WriteString("\n") } bodyText.WriteString(line) } } } var v map[string]interface{} if jsonBody.Len() > 0 { jsonBody.WriteString("}") if err := yaml.Unmarshal(jsonBody.Bytes(), &v); err != nil { return nil, err } } else { v = make(map[string]interface{}, 0) } return &Alert{ Body: strings.TrimRight(bodyText.String(), "\n"), Doc: v, }, nil } func (m Alerts) equalsTo(o Alerts) (bool, string) { if len(m) != len(o) { return false, fmt.Sprintf("entry length not equals:%d,%d", len(m), len(o)) } for i, e1 := range m { e2 := o[i] equal, desc := e1.equalsTo(e2) if !equal { return false, fmt.Sprintf("entry %d not equals:%s", i, desc) } } return true, "" } func (m *Alert) equalsTo(o *Alert) (bool, string) { if m.Body != o.Body { return false, fmt.Sprintf("body not equals:\n%s\n---------------------\n%s", m.Body, o.Body) } doc1, _ := yaml.Marshal(m.Doc) doc2, _ := yaml.Marshal(o.Doc) doc1s := string(doc1) doc2s := string(doc2) if doc1s != doc2s { return false, fmt.Sprintf("doc not equals:\n%s\n----------------------\n%s", doc1s, doc2s) } return true, "" }
true
4fe11a7bb58ded0ab149cda42af689ccc25b853c
Go
grafana/tanka
/pkg/kubernetes/client/resources.go
UTF-8
3,377
2.75
3
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
package client import ( "bytes" "encoding/json" "fmt" "os" "regexp" "strings" "github.com/pkg/errors" "github.com/grafana/tanka/pkg/kubernetes/manifest" ) // Resources the Kubernetes API knows type Resources []Resource // Namespaced returns whether a resource is namespace-specific or cluster-wide func (r Resources) Namespaced(m manifest.Manifest) bool { for _, res := range r { if m.Kind() == res.Kind { return res.Namespaced } } return false } // Resource is a Kubernetes API Resource type Resource struct { APIGroup string `json:"APIGROUP"` APIVersion string `json:"APIVERSION"` Kind string `json:"KIND"` Name string `json:"NAME"` Namespaced bool `json:"NAMESPACED,string"` Shortnames string `json:"SHORTNAMES"` Verbs string `json:"VERBS"` Categories string `json:"CATEGORIES"` } func (r Resource) FQN() string { apiGroup := "" if r.APIGroup != "" { // this is only set in kubectl v1.18 and earlier apiGroup = r.APIGroup } else if pos := strings.Index(r.APIVersion, "/"); pos > 0 { apiGroup = r.APIVersion[0:pos] } return strings.TrimSuffix(r.Name+"."+apiGroup, ".") } // Resources returns all API resources known to the server func (k Kubectl) Resources() (Resources, error) { cmd := k.ctl("api-resources", "--cached", "--output=wide") var out bytes.Buffer cmd.Stdout = &out cmd.Stderr = os.Stderr if err := cmd.Run(); err != nil { return nil, err } var res Resources if err := UnmarshalTable(out.String(), &res); err != nil { return nil, errors.Wrap(err, "parsing table") } return res, nil } // UnmarshalTable unmarshals a raw CLI table into ptr. `json` package is used // for getting the dat into the ptr, `json:` struct tags can be used. func UnmarshalTable(raw string, ptr interface{}) error { raw = strings.TrimSpace(raw) lines := strings.Split(raw, "\n") if len(lines) == 0 { return ErrorNoHeader } headerStr := lines[0] // headers are ALL-CAPS if !regexp.MustCompile(`^[A-Z\s]+$`).MatchString(headerStr) { return ErrorNoHeader } lines = lines[1:] spc := regexp.MustCompile(`[A-Z]+\s*`) header := spc.FindAllString(headerStr, -1) tbl := make([]map[string]string, 0, len(lines)) for _, l := range lines { elems := splitRow(l, header) if len(elems) != len(header) { return ErrorElementsMismatch{Header: len(header), Row: len(elems)} } row := make(map[string]string) for i, e := range elems { key := strings.TrimSpace(header[i]) row[key] = strings.TrimSpace(e) } tbl = append(tbl, row) } j, err := json.Marshal(tbl) if err != nil { return err } return json.Unmarshal(j, ptr) } // ErrorNoHeader occurs when the table lacks an ALL-CAPS header var ErrorNoHeader = fmt.Errorf("table has no header") // ErrorElementsMismatch occurs when a row has a different count of elements // than it's header type ErrorElementsMismatch struct { Header, Row int } func (e ErrorElementsMismatch) Error() string { return fmt.Sprintf("header and row have different element count: %v != %v", e.Header, e.Row) } func splitRow(s string, header []string) (elems []string) { pos := 0 for i, h := range header { if i == len(header)-1 { elems = append(elems, s[pos:]) continue } lim := len(h) endPos := pos + lim if endPos >= len(s) { endPos = len(s) } elems = append(elems, s[pos:endPos]) pos = endPos } return elems }
true
9ec68ff24dd7d6638fc3d040a5f01ef3567dabb7
Go
KasimDilsiz/goLearn
/3PrograminFundamentals/BitShifting/bit1.go
UTF-8
464
2.546875
3
[]
no_license
[]
no_license
package main import "fmt" func main() { kb := 1024 mb := 1024 * kb gb := 1024 * mb fmt.Printf("%d\t\t\t%b\n", kb, kb) fmt.Printf("%d\t\t\t%b\n", mb, mb) fmt.Printf("%d\t\t%b\n", gb, gb) } /* const ( _=iota kb:=1 << (iota*10) mb:=1 << (iota*10) gb:=1 << (iota*10) ) func main () { fmt.Printf("%d\t\t\t%b\n", kb, kb) fmt.Printf("%d\t\t\t%b\n", mb, mb) fmt.Printf("%d\t\t%b\n", gb, gb)func main(){ } BU KODUMUZLA DA AYNI CIKTIYI ALABILIYORUZ . */
true
a136a1f1e1a46fff572d4d40e775b03dd266a646
Go
lupes/leetcode
/question_201_300/question_291_300/299_bulls_and_cows_test.go
UTF-8
404
2.578125
3
[]
no_license
[]
no_license
package question_291_300 import "testing" func Test_getHint(t *testing.T) { tests := []struct { secret string guess string want string }{ {"1807", "7810", "1A3B"}, {"1123", "0111", "1A1B"}, } for _, tt := range tests { t.Run("test", func(t *testing.T) { if got := getHint(tt.secret, tt.guess); got != tt.want { t.Errorf("getHint() = %v, want %v", got, tt.want) } }) } }
true
436221b8cd750f33ef9c321ba2fa291bffd5b416
Go
xfye/pebble
/internal/keyspan/seek.go
UTF-8
9,791
2.796875
3
[ "BSD-3-Clause" ]
permissive
[ "BSD-3-Clause" ]
permissive
// Copyright 2018 The LevelDB-Go and Pebble 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 keyspan import "github.com/cockroachdb/pebble/internal/base" // SeekGE seeks to the newest span that contains or is past the target key. The // snapshot parameter controls the visibility of spans (only spans older than // the snapshot sequence number are visible). The iterator must contain // fragmented spans: any overlapping spans must have the same start and end key. // The position of the iterator is undefined after calling SeekGE and may not be // pointing at the returned span. func SeekGE(cmp base.Compare, iter base.InternalIterator, key []byte, snapshot uint64) Span { // NB: We use SeekLT in order to land on the proper span for a search // key that resides in the middle of a span. Consider the scenario: // // a---e // e---i // // The spans are indexed by their start keys `a` and `e`. If the // search key is `c` we want to land on the span [a,e). If we were to // use SeekGE then the search key `c` would land on the span [e,i) and // we'd have to backtrack. The one complexity here is what happens for the // search key `e`. In that case SeekLT will land us on the span [a,e) // and we'll have to move forward. iterKey, iterValue := iter.SeekLT(key) // Invariant: key < iter.Key().UserKey if iterKey != nil && cmp(key, iterValue) < 0 { // The current spans contains or is past the search key, but SeekLT // returns the oldest entry for a key, so backup until we hit the previous // span or an entry which is not visible. for savedKey := iterKey.UserKey; ; { iterKey, iterValue = iter.Prev() if iterKey == nil || cmp(savedKey, iterValue) >= 0 || !iterKey.Visible(snapshot) { iterKey, iterValue = iter.Next() break } } } else { // The current span lies before the search key. Advance the iterator // to the next span which is guaranteed to lie at or past the search // key. iterKey, iterValue = iter.Next() if iterKey == nil { // We've run out of spans. return Span{} } } // The iter is positioned at a non-nil iterKey which is the earliest iterator // position that satisfies the requirement that it contains or is past the // target key. But it may not be visible based on the snapshot. So now we // only need to move forward and return the first span that is visible. // // Walk through the spans to find one the newest one that is visible // (i.e. has a sequence number less than the snapshot sequence number). for { if start := iterKey; start.Visible(snapshot) { // The span is visible at our read sequence number. return Span{ Start: *start, End: iterValue, } } iterKey, iterValue = iter.Next() if iterKey == nil { // We've run out of spans. return Span{} } } } // SeekLE seeks to the newest span that contains or is before the target // key. The snapshot parameter controls the visibility of spans (only // spans older than the snapshot sequence number are visible). The // iterator must contain fragmented spans: any overlapping spans must // have the same start and end key. The position of the iterator is undefined // after calling SeekLE and may not be pointing at the returned span. func SeekLE(cmp base.Compare, iter base.InternalIterator, key []byte, snapshot uint64) Span { // NB: We use SeekLT in order to land on the proper span for a search // key that resides in the middle of a span. Consider the scenario: // // a---e // e---i // // The spans are indexed by their start keys `a` and `e`. If the // search key is `c` we want to land on the span [a,e). If we were to // use SeekGE then the search key `c` would land on the span [e,i) and // we'd have to backtrack. The one complexity here is what happens for the // search key `e`. In that case SeekLT will land us on the span [a,e) // and we'll have to move forward. iterKey, iterValue := iter.SeekLT(key) // Consider the following set of fragmented spans, ordered by increasing // key and decreasing seqnum: // // 2: d---h // 1: d---h // 2: j---n // 1: j---n // 2: n---r // 1: n---r // // The cases to consider: // // 1. search-key == "a" // - The search key is fully before any span. We should return an // empty span. The initial SeekLT("a") will return iterKey==nil and // the next span [d,h) lies fully after the search key. // // 2. search-key == "d" // - The search key is contained by the span [d,h). We want to return // the newest version of the span [d,h) or the empty span if // there are no visible versions. The initial SeekLT("d") will return // iterKey==nil and the next span [d,h) contains the search key. We // iterate forward from there returning the newest visible span for // [d, h) and if there is no visible one return an empty span. // // 3. search-key == "h" or "i" // - The search key lies between the spans [d,h) and [j,n). We want to // return the newest visible version of the span [d,h) or the empty // span if there are no visible versions. The initial SeekLT("h") or // SeekLT("i") will return the span [d,h)#1. Because the end key of // this span is less than or equal to the search key we have to // check if the next span contains the search key. In this case it // does not and we need to look backwards starting from [d, h)#1, falling // into case 5. // // 4. search-key == "n" // - The search key is contained by the span [n,r). We want to return // the newest version of the span [n,r) or an earlier span if // there are no visible versions of [n,r). The initial SeekLT("n") will // return the span [j,n)#1. Because the end key of the spans // [j,n) equals the search key "n" we have to see if the next span // contains the search key (which it does). We iterate forward through // the [n,r) spans (not beyond) and return the first visible // span (since this iteration is going from newer to older). If // there are no visible [n,r) spans (due to the snapshot parameter) // we need to step back to [n,r) and look backwards, falling into case 5. // // 5. search-key == "p" // - The search key is contained by the span [n,r). We want to return // the newest visible version of the span [n,r) or an earlier // span if there are no visible versions. Because the end key of the // span [n,r) is greater than the search key "p", we do not have to // look at the next span. We iterate backwards starting with [n,r), // then [j,n) and then [d,h), returning the newest version of the first // visible span. switch { case iterKey == nil: // Cases 1 and 2. Advance the iterator until we find a visible version, we // exhaust the iterator, or we hit the next span. for { iterKey, iterValue = iter.Next() if iterKey == nil || cmp(key, iterKey.UserKey) < 0 { // The iterator is exhausted or we've hit the next span. return Span{} } if start := iterKey; start.Visible(snapshot) { return Span{ Start: *start, End: iterValue, } } } default: // Invariant: key > iterKey.UserKey if cmp(key, iterValue) >= 0 { // Cases 3 and 4 (forward search). The current span lies before the // search key. Check to see if the next span contains the search // key. If it doesn't, we'll backup and look for an earlier span. iterKey, iterValue = iter.Next() if iterKey == nil || cmp(key, iterKey.UserKey) < 0 { // Case 3. The next span is past our search key (or there is no next // span). iterKey, iterValue = iter.Prev() } else { // Case 4. Advance the iterator until we find a visible version or we hit // the next span. for { if start := iterKey; start.Visible(snapshot) { // We've found our span as we know earlier spans are // either not visible or lie before this span. return Span{ Start: *start, End: iterValue, } } iterKey, iterValue = iter.Next() if iterKey == nil || cmp(key, iterKey.UserKey) < 0 { // There is no next span, or the next span is past our // search key. Back up to the previous span. Note that we'll // immediately fall into the loop below which will keep on // iterating backwards until we find a visible span and that // span must contain or be before our search key. iterKey, iterValue = iter.Prev() break } } } } // Cases 3, 4, and 5 (backwards search). We're positioned at a span // that contains or is before the search key. Walk backward until we find a // visible span from this point. for !iterKey.Visible(snapshot) { iterKey, iterValue = iter.Prev() if iterKey == nil { // No visible spans before our search key. return Span{} } } // We're positioned at a span that contains or is before the search // key and is visible. Walk backwards until we find the latest version of // this span that is visible (i.e. has a sequence number less than the // snapshot sequence number). s := Span{Start: *iterKey, End: iterValue} // current candidate to return for { iterKey, _ = iter.Prev() if iterKey == nil { // We stepped off the end of the iterator. break } if !iterKey.Visible(snapshot) { // The previous span is not visible. break } if cmp(s.Start.UserKey, iterKey.UserKey) != 0 { // The previous span is before our candidate span. break } // Update the candidate span's seqnum. NB: The end key is guaranteed // to be the same. s.Start.Trailer = iterKey.Trailer } return s } }
true
12b289285fff737dba41e40664ec811fb1d923f2
Go
hekmon/plexwebhooks
/extract.go
UTF-8
1,786
2.921875
3
[ "MIT" ]
permissive
[ "MIT" ]
permissive
package plexwebhooks import ( "encoding/json" "errors" "fmt" "io" "io/ioutil" "mime/multipart" ) // Thumbnail contains all the relevant data about the thumbnail file (if sended). type Thumbnail struct { Filename string Data []byte } // Extract extracts the payload and the thumbnail (if present) from a multipart reader func Extract(mpr *multipart.Reader) (payload *Payload, thumbnail *Thumbnail, err error) { if mpr == nil { err = errors.New("multipart reader can't be nil") return } // Read var formPart *multipart.Part for formPart, err = mpr.NextPart(); err == nil; formPart, err = mpr.NextPart() { switch formPart.FormName() { case "payload": // Only one payload if payload != nil { err = errors.New("payload part is present more than once") return } // Extract payload payload = new(Payload) decoder := json.NewDecoder(formPart) // decoder.DisallowUnknownFields() // dev if err = decoder.Decode(payload); err != nil { err = fmt.Errorf("payload JSON decode failed: %w", err) return } case "thumb": // Only one thumb can be present if thumbnail != nil { err = errors.New("thumb part is present more than once") return } // Prepare thumb event payload & set filename thumbnail = &Thumbnail{ Filename: formPart.FileName(), } // Extract thumb data if thumbnail.Data, err = ioutil.ReadAll(formPart); err != nil { err = fmt.Errorf("error while reading thumb form part data: %w", err) return } default: err = fmt.Errorf("unexpected form part encountered: %s", formPart.FormName()) return } } // Handle errors if err == io.EOF { err = nil } if err == nil && payload == nil { err = errors.New("payload not found within request") } // Done return }
true
e45ff9cee6ecdd7b279174243f354920da81e7a2
Go
billee1011/zhibo
/queue/respQueue.go
UTF-8
1,342
3.34375
3
[]
no_license
[]
no_license
package queue import ( "net/http" "sync" "sync/atomic" ) type RespQueue struct { rlock sync.RWMutex // lock protect resp resp *http.Response head *Node tail *Node // operation by atomic size int32 done int32 del int32 } func NewRespQueue() *RespQueue { n := &Node{} n.Lock() q := &RespQueue{head: n, tail: n} q.rlock.Lock() return q } func (q *RespQueue) Del() { atomic.StoreInt32(&q.del, 1) } func (q *RespQueue) IsDone() bool { if atomic.LoadInt32(&q.done) != 0 { return true } else { return false } } func (q *RespQueue) GetSize() int { return int(atomic.LoadInt32(&q.size)) } func (q *RespQueue) Push(data []byte) bool { if atomic.LoadInt32(&q.del) == 1 { return false } tail := q.tail tail.data = data if data != nil { n := &Node{} n.Lock() tail.next = n q.tail = n atomic.AddInt32(&q.size, int32(len(data))) } else { atomic.StoreInt32(&q.done, 1) } tail.Unlock() return true } func (q *RespQueue) PushResp(resp *http.Response) { q.resp = resp q.rlock.Unlock() } func (q *RespQueue) Peek(n *Node) ([]byte, *Node) { if atomic.LoadInt32(&q.del) == 1 { return nil, nil } if n == nil { n = q.head } n.RLock() defer n.RUnlock() return n.data, n.next } func (q *RespQueue) PeekResp() *http.Response { q.rlock.RLock() defer q.rlock.RUnlock() return q.resp }
true
22162f537f51a7486f9057f98d8416ae84821ff9
Go
lkarlslund/stringsplus
/stringsplus.go
UTF-8
958
3.46875
3
[ "MIT" ]
permissive
[ "MIT" ]
permissive
package stringsplus import "strings" // EqualFoldHasSuffix returns true if s has suffix, not considering case sensitivity. func EqualFoldHasSuffix(s, suffix string) bool { return len(s) >= len(suffix) && strings.EqualFold(s[len(s)-len(suffix):], suffix) } // EqualFoldHasPrefix returns true if s has prefix, not considering case sensitivity. func EqualFoldHasPrefix(s, prefix string) bool { return len(s) >= len(prefix) && strings.EqualFold(s[:len(prefix)], prefix) } // EqualFoldStringInSlice returns true if needle is in haystack, not considering case sensitivity. func EqualFoldStringInSlice(needle string, haystack []string) bool { for _, hay := range haystack { if strings.EqualFold(hay, needle) { return true } } return false } // StringInSlice returns true if needle is in haystack. func StringInSlice(needle string, haystack []string) bool { for _, hay := range haystack { if hay == needle { return true } } return false }
true
fe13bede969c81f5d43fe768ba4787c03f3e2e36
Go
w9jds/go.esi
/main.go
UTF-8
2,517
3.109375
3
[]
no_license
[]
no_license
package esi import ( "bytes" "errors" "fmt" "io/ioutil" "log" "net/http" "time" ) // Client is a client for communication with the eve online api type Client struct { baseURI string client *http.Client } const baseURI = "https://esi.evetech.net" // CreateClient creates a new instance of the Client func CreateClient(httpClient *http.Client) *Client { return &Client{ baseURI: baseURI, client: httpClient, } } func attachHeaders(request *http.Request) *http.Request { request.Header.Add("Accept", "application/json") return request } func authHeader(request *http.Request, token string) *http.Request { request.Header.Add("Authorization", fmt.Sprintf("Bearer %s", token)) return request } func (esi Client) get(path string) ([]byte, error) { request, error := http.NewRequest("GET", baseURI+path, nil) if error != nil { return nil, error } return esi.do(attachHeaders(request)) } func (esi Client) authGet(path string, token string) ([]byte, error) { request, err := http.NewRequest("GET", baseURI+path, nil) if err != nil { return nil, err } request = authHeader(request, token) return esi.do(attachHeaders(request)) } func (esi Client) post(path string, content []byte) ([]byte, error) { request, error := http.NewRequest("POST", baseURI+path, bytes.NewBuffer(content)) if error != nil { return nil, error } return esi.do(attachHeaders(request)) } func (esi Client) do(request *http.Request) ([]byte, error) { for i := 0; i < 3; i++ { delay := 5 * time.Second response, error := esi.client.Do(request) if error != nil { log.Println(error) continue } else if response.StatusCode < 200 || response.StatusCode > 299 { // Don't bother retrying three times when you don't have permissions to make the request in the first place if response.StatusCode == 403 || response.StatusCode == 401 { log.Printf("Status %d: Unauthorized\n", response.StatusCode) break } message, error := ioutil.ReadAll(response.Body) if response.StatusCode == 420 { // on error limited wait 60 seconds before proceeding delay = 1 * time.Minute } if error != nil { log.Println(error) time.Sleep(delay) continue } else { log.Println(string(message)) time.Sleep(delay) continue } } else { return ioutil.ReadAll(response.Body) } } return nil, errors.New("failed esi requests 3 times, gave up") }
true
29f1c1fc8c6f94047580ecc02244ed0dcd7f0bba
Go
mylxsw/adanos-alert
/internal/repository/user.go
UTF-8
1,939
2.640625
3
[ "MIT" ]
permissive
[ "MIT" ]
permissive
package repository import ( "time" "go.mongodb.org/mongo-driver/bson" "go.mongodb.org/mongo-driver/bson/primitive" ) type UserStatus string const ( UserStatusEnabled UserStatus = "enabled" UserStatusDisabled UserStatus = "disabled" ) type UserMeta struct { Key string `bson:"key" json:"key" schema:"key"` Value string `bson:"value" json:"value" schema:"value"` } type UserMetas []UserMeta func (ums UserMetas) Get(key string) string { for _, v := range ums { if v.Key == key { return v.Value } } return "" } type User struct { ID primitive.ObjectID `bson:"_id,omitempty" json:"id"` Name string `bson:"name" json:"name"` Email string `bson:"email" json:"email"` Phone string `bson:"phone" json:"phone"` Password string `bson:"password" json:"password"` Role string `bson:"role" json:"role"` Metas UserMetas `bson:"metas" json:"metas"` Status UserStatus `bson:"status" json:"status"` CreatedAt time.Time `bson:"created_at" json:"created_at"` UpdatedAt time.Time `bson:"updated_at" json:"updated_at"` } type UserIDWithMeta struct { UserID string `bson:"user_id" json:"user_id"` Meta []string `bson:"meta" json:"meta"` } type UserRepo interface { Add(user User) (id primitive.ObjectID, err error) Get(id primitive.ObjectID) (user User, err error) GetByEmail(email string) (user User, err error) Find(filter bson.M) (users []User, err error) Paginate(filter bson.M, offset, limit int64) (users []User, next int64, err error) DeleteID(id primitive.ObjectID) error Delete(filter bson.M) error Update(id primitive.ObjectID, user User) error Count(filter bson.M) (int64, error) GetUserMetas(queryK, queryV, field string) ([]string, error) GetUserIDWithMetas(queryK, queryV, field string) ([]UserIDWithMeta, error) GetUserMetasRegex(queryK, queryVRegex, field string) ([]string, error) GetUserIDWithMetasRegex(queryK, queryVRegex, field string) ([]UserIDWithMeta, error) }
true
7218f232611ad6f70a125d090a44cafa8bf204db
Go
wangjiahelen/goal
/linkedlist/palindrome.go
UTF-8
2,439
3.703125
4
[]
no_license
[]
no_license
package linkedlist //回文字符串 func isPalindrome(head *SingleListNode) bool { var slow *SingleListNode = head.next var fast *SingleListNode = head.next var prev *SingleListNode = nil var temp *SingleListNode = nil if (head == nil || head.next == nil) { return false } if head.next.next == nil { return true } for (fast != nil && fast.next != nil) { fast = fast.next.next temp = slow.next slow.next = prev prev = slow slow = temp } // 快的先跑完,同时反转了一半链表,剪短 if fast != nil { slow = slow.next // 处理余数,跨过中位数 // prev 增加中 2->1->nil } var l1 *SingleListNode = prev var l2 *SingleListNode = slow for (l1 != nil && l2 != nil && l1.value == l2.value) { l1 = l1.next l2 = l2.next } return (l1 == nil && l2 == nil) } /* 思路1:开一个栈存放链表前半段 时间复杂度:O(N) 空间复杂度:O(N) */ func isPalindrome1(l *SingleLinkedList) bool { lLen := l.length if lLen == 0 { return false } if lLen == 1 { return true } s := make([]string, 0, lLen/2) cur := l.head for i := uint(1); i <= lLen; i++ { cur = cur.next if lLen%2 != 0 && i == (lLen/2+1) { //如果链表有奇数个节点,中间的直接忽略 continue } if i <= lLen/2 { //前一半入栈 s = append(s, cur.GetValue().(string)) } else { //后一半与前一半进行对比 if s[lLen-i] != cur.GetValue().(string) { return false } } } return true } /* 思路2 找到链表中间节点,将前半部分转置,再从中间向左右遍历对比 时间复杂度:O(N) */ func isPalindrome2(l *SingleLinkedList) bool { lLen := l.length if lLen == 0 { return false } if lLen == 1 { return true } var isPalindrome = true step := lLen / 2 var pre *SingleListNode = nil cur := l.head.next next := l.head.next.next for i := uint(1); i <= step; i++ { tmp := cur.GetNext() cur.next = pre pre = cur cur = tmp next = cur.GetNext() } mid := cur var left, right *SingleListNode = pre, nil if lLen%2 != 0 { right = mid.GetNext() } else { right = mid } for left != nil && right != nil { if left.GetValue().(string) != right.GetValue().(string) { isPalindrome = false break } left = left.GetNext() right = right.GetNext() } cur = pre pre = mid for cur != nil { next = cur.GetNext() cur.next = pre pre = cur cur = next } l.head.next = pre return isPalindrome }
true