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
f829464aadd611d667f4689ac2e1ff8ea0e5973d
Go
brapse/tsinkf
/run.go
UTF-8
1,114
2.671875
3
[ "BSD-2-Clause", "LicenseRef-scancode-unknown-license-reference" ]
permissive
[ "BSD-2-Clause", "LicenseRef-scancode-unknown-license-reference" ]
permissive
package main import ( "strings" ) var runFn CmdFn = func(c *Cmd, args []string) int { baseDir := c.Flags.String("d", ".tsinkf", "base directory") verbose := c.Flags.Bool("v", false, "verbose output") locking := c.Flags.Bool("l", true, "enable locking") c.Flags.Parse(args) if len(args) == 0 { c.Usage() return 1 } leftover := c.Flags.Args() store := NewStore(*baseDir) journal := NewJournal(*verbose, *baseDir+"/journal.log") if *locking { store.Lock() } defer store.Close() defer journal.Close() cmd := strings.Join(leftover, " ") job := NewJob(cmd, *store, *journal) runJob := func() int { job.SetState(RUNNING) status := job.Run() if status == 0 { job.SetState(SUCCEEDED) } else { job.SetState(FAILED) } return status } switch job.GetState() { case UNKNOWN: job.SetState(NEW) return runJob() case NEW: return runJob() case RUNNING: job.SetState(FAILED) return 1 case FAILED: return 0 case SUCCEEDED: return 0 } return 1 } func init() { cmd := NewCmd("run", "run a command", "tsinkf run [-v] cmd...", runFn) cmdList[cmd.Name] = cmd }
true
6e2457bcc26a2f34d85c100a51936688f4b6a3e3
Go
aceveggie/go-lang-programming
/c08-Goroutines/c08s07/main.go
UTF-8
819
3.75
4
[]
no_license
[]
no_license
package main import ( "fmt" "math/rand" "time" ) const N = 200000 func main() { quit := make(chan bool) c0 := chatter("Bob", quit) c1 := chatter("Joe", quit) c2 := chatter("Anne", quit) c3 := chatter("Mary", quit) go func() { for { select { case v := <-c0: fmt.Println(v) case v := <-c1: fmt.Println(v) case v := <-c2: fmt.Println(v) case v := <-c3: fmt.Println(v) } } }() time.Sleep(2 * time.Second) quit <- true quit <- true quit <- true quit <- true } func chatter(s string, quit <-chan bool) <-chan string { out := make(chan string) go func() { for { select { case <-quit: // clean up fmt.Println(s, " is quitting") break case out <- s: time.Sleep(time.Duration(rand.Intn(100)) * time.Nanosecond) } } }() return out }
true
7e1e8102cb1e72932e0d0f04a0a5f80edf1bc7b8
Go
Happy-Ferret/inversebloom-th1a
/inversebloom.go
UTF-8
2,164
3.34375
3
[]
no_license
[]
no_license
/* Inverse Bloom InverseBloomFilter (aka Opposite Of A Bloom InverseBloomFilter) - https://github.com/jmhodges/opposite_of_a_bloom_filter modified to use th1a hash algorithm */ package main import ( "bytes" "encoding/binary" "errors" "math" "sync/atomic" "unsafe" ) var ( maxInverseBloomFilterSize = 1 << 30 ) // InverseBloomFilter is an inverse bloom filter. type InverseBloomFilter struct { array []*[]byte sizeMask uint32 *TH1A } // NewInverseBloomFilter returns a new Inverse Bloom filter of provided size. func NewInverseBloomFilter(size int) (*InverseBloomFilter, error) { if size > maxInverseBloomFilterSize { return nil, errors.New("size too large to round to a power of 2") } if size <= 0 { return nil, errors.New("filter cannot have zero or negative size") } // round to the next largest power of two size = int(math.Pow(2, math.Ceil(math.Log2(float64(size))))) slice := make([]*[]byte, size) sizeMask := uint32(size - 1) tt := &TH1A{0x0102030405060788} return &InverseBloomFilter{slice, sizeMask, tt}, nil } // Contains returns true of the Inverse Bloom filter contains the given id. func (f *InverseBloomFilter) Contains(id []byte) bool { s64 := f.Sum64(id) s64b := make([]byte, 8) binary.LittleEndian.PutUint64(s64b, s64) s32 := uint32(s64b[0]) for _, val := range s64b[1:3] { s32 = s32 << 3 s32 += uint32(val) } uindex := s32 & f.sizeMask index := int32(uindex) oldId := getAndSet(f.array, index, id) return bytes.Equal(oldId, id) } // Size returns the size of the inverse bloom filter. func (f *InverseBloomFilter) Size() int { return len(f.array) } // Returns the id that was in the slice at the given index after putting the // new id in the slice at that index, atomically. func getAndSet(arr []*[]byte, index int32, id []byte) []byte { indexPtr := (*unsafe.Pointer)(unsafe.Pointer(&arr[index])) idUnsafe := unsafe.Pointer(&id) var oldId []byte for { oldIdUnsafe := atomic.LoadPointer(indexPtr) if atomic.CompareAndSwapPointer(indexPtr, oldIdUnsafe, idUnsafe) { oldIdPtr := (*[]byte)(oldIdUnsafe) if oldIdPtr != nil { oldId = *oldIdPtr } break } } return oldId }
true
c0a3339a57517df23635fffaac4e8d1ddee3ec76
Go
cloudingcity/go-leetcode
/algorithms/0017-letter-combinations-of-a-phone-number/main_test.go
UTF-8
356
2.796875
3
[]
no_license
[]
no_license
package main import ( "testing" "github.com/stretchr/testify/assert" ) func Test(t *testing.T) { tests := []struct { digits string want []string }{ { digits: "23", want: []string{"ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"}, }, } for _, tt := range tests { assert.Equal(t, tt.want, letterCombinations(tt.digits)) } }
true
865ed4777b91f54e325ababa7ba919519eb9bcfd
Go
KevinMcT/usinggo
/src/lab6/main.go
UTF-8
960
3.3125
3
[]
no_license
[]
no_license
package main import ( "fmt" "lab6/core" "os" ) var () func main() { var tot bool tot = true for tot == true { fmt.Println("*********************************************************************") fmt.Println("* Choose the function you would like to test using numbers 1 - 3 *") fmt.Println("* 1 - Paxos server *") fmt.Println("* 2 - Client *") fmt.Println("* 3 - Bank system *") fmt.Println("* 0 - Quit *") fmt.Println("*********************************************************************") var in int fmt.Scanf("%d", &in) switch in { case 1: //--Calling the Paxos replica--// core.Paxos() case 2: //--Calling the Client--// core.Client() case 3: core.NewBank() case 0: os.Exit(0) } } }
true
3b0220a2682aab5be2a741c214c46890d428fe3d
Go
pandora0667/golang-study
/chapter-09/rsa.go
UTF-8
635
2.84375
3
[ "MIT" ]
permissive
[ "MIT" ]
permissive
package main import ( "crypto/rand" "crypto/rsa" f "fmt" ) func main() { privateKey, err := rsa.GenerateKey(rand.Reader, 2048) if err != nil { f.Println(err) return } publicKey := &privateKey.PublicKey s := `동해 물과 백두산이 마르고 닳도록 하느님이 보우하사 우리나라 만세. 무궁화 삼천리 화려강산 대한 사람, 대한으로 길이 보전하세.` cipherText, err := rsa.EncryptPKCS1v15( rand.Reader, publicKey, []byte(s)) f.Printf("%x\n", cipherText) plainText, _ := rsa.DecryptPKCS1v15( rand.Reader, privateKey, cipherText, ) f.Println(string(plainText)) }
true
15b1431f3d802103e5d53ecf62c10c1d5ce197be
Go
mephis5150/baby_go
/loop/loop.go
UTF-8
596
4.53125
5
[]
no_license
[]
no_license
package loop import "fmt" func ForBasic() { fmt.Println("\t---- Loop in go ----\n") // For loop fmt.Println("** for loop **") for i := 0; i < 10; i++ { fmt.Println(i) } fmt.Println() // While loop fmt.Println("** while loop **") fmt.Println("- no while loop in go, we use `for`") k := 0 for k < 10 { fmt.Println(k) k++ } fmt.Println("- forever loop in go, use `for` but no condition\n") // loop and slice fmt.Println("** loop and slice **") langs := []string{"go", "python", "ruby", "rust"} for index, value := range langs { fmt.Println(index, " : ", value) } }
true
1250754eba2d735662599d0fa0717ef0e9a50ff9
Go
loganyu/leetcode
/problems/804_unique_morse_code_words.go
UTF-8
1,747
3.78125
4
[]
no_license
[]
no_license
/* International Morse Code defines a standard encoding where each letter is mapped to a series of dots and dashes, as follows: 'a' maps to ".-", 'b' maps to "-...", 'c' maps to "-.-.", and so on. For convenience, the full table for the 26 letters of the English alphabet is given below: [".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."] Given an array of strings words where each word can be written as a concatenation of the Morse code of each letter. For example, "cab" can be written as "-.-..--...", which is the concatenation of "-.-.", ".-", and "-...". We will call such a concatenation the transformation of a word. Return the number of different transformations among all words we have. Example 1: Input: words = ["gin","zen","gig","msg"] Output: 2 Explanation: The transformation of each word is: "gin" -> "--...-." "zen" -> "--...-." "gig" -> "--...--." "msg" -> "--...--." There are 2 different transformations: "--...-." and "--...--.". Example 2: Input: words = ["a"] Output: 1 Constraints: 1 <= words.length <= 100 1 <= words[i].length <= 12 words[i] consists of lowercase English letters. */ func uniqueMorseRepresentations(words []string) int { MORSE := [] string{".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."} seen := make(map[string]bool) for _, s := range words { code := "" runes := [] rune(s) for _, r := range runes { index := r - 'a' code += MORSE[index] } seen[code] = true } return len(seen) }
true
2d8ad4e43bdc46e6a1ecb7a04a2f6dfabd9a4d75
Go
asmahood/go_starter_project
/chapter_2/even_numbers_challenge.go
UTF-8
786
4.46875
4
[ "MIT" ]
permissive
[ "MIT" ]
permissive
/* -- Even-Ended Numbers Challenge -- A even-ended number is a number with the same first and last digits ex: 1, 11, 121 How many even-ended numbers result from multiplying two four-digit numbers? */ package main import ( "fmt" ) func main() { // Sprintf example n := 42 s := fmt.Sprintf("%d", n) fmt.Printf("s = %q (type %T)\n", s, s) // Problem starts here // counter variable count := 0 // loop through first 4 digit numbers for x := 1000; x <= 9999; x++ { // loop through second 4 digit numbers, dont double count for y := x; y <= 9999; y++ { prod := x * y // convert prod to a string s := fmt.Sprintf("%d", prod) // if its even ended, increment count if s[0] == s[len(s)-1] { count++ } } } // print count fmt.Println(count) }
true
38fbd6abb4b8f947a9f07a6f4ca71e5d1f635445
Go
cooleaf/golearn
/src/ch8/map/mapext_test.go
UTF-8
268
2.734375
3
[ "Apache-2.0" ]
permissive
[ "Apache-2.0" ]
permissive
package map_test import "testing" func TestMapWithFunValue(t *testing.T) { m1 := map[int]func(op int) int{} m1[1] = func(op int) int { return op } m1[2] = func(op int) int { return op * op } m1[3] = func(op int) int { return op ^ 3 } a := m1[2](3) t.Log(a) }
true
6bb1ab06a7b77db3e2b4ab493d57adc9f1d648c4
Go
smruti-ranjan-patra/Golang
/print_detaild_struct_fields.go
UTF-8
2,297
3.53125
4
[]
no_license
[]
no_license
package main import ( "fmt" "reflect" ) type TestSt struct { Name string `json:"name_of_employee", "custom":"xyz"` Age int `json:"age_of_employee"` Field3 TestIn } type TestIn struct { Field4 string `json:"field_4_tag"` Field5 []string `json:"field_5_tag"` Field6 TestIn2 } type TestIn2 struct { Field7 int `json:"field_7_tag"` Field8 map[string]int `json:"field_8_tag"` } func main() { obj := TestSt{ Name: "Abcd", Age: 20, Field3: TestIn{ Field4: "qq", Field5: []string{"str1", "str2", "str3"}, Field6: TestIn2{ Field7: 20, Field8: map[string]int{"abc": 60, "xyz": 80}, }, }, } fmt.Printf("\n%+v\n", obj) fmt.Println("#################################################") //printUsingStruct(obj) //printUsingStruct2(obj) printUsingInterface(obj) } func printUsingStruct(t TestSt) { fmt.Println("=================================================") s := reflect.ValueOf(&t).Elem() typeOfT := s.Type() for i := 0; i < s.NumField(); i++ { f := s.Field(i) fmt.Printf("%d: %s (%s) = %v, tag => %s\n", i, typeOfT.Field(i).Name, f.Type(), f.Interface(), typeOfT.Field(i).Tag) } } func printUsingStruct2(t TestSt) { fmt.Println("=================================================") e := reflect.ValueOf(&t).Elem() for i := 0; i < e.NumField(); i++ { varName := e.Type().Field(i).Name varType := e.Type().Field(i).Type varValue := e.Field(i).Interface() varTag := e.Type().Field(i).Tag varSize := varType.Size() fmt.Printf("%v %v %v %v %v \n", varName, varType, varValue, varSize, varTag) } } func printUsingInterface(v interface{}) { fmt.Println("=================================================") rv := reflect.ValueOf(v) rt := reflect.TypeOf(v) fmt.Println(rt) if rt.Kind() != reflect.Struct { fmt.Printf("\nError : Expecting struct, %s passed\n", rt.Kind()) return } for i := 0; i < rv.NumField(); i++ { varName := rt.Field(i).Name varType := rv.Field(i).Type() varValue := rv.Field(i).Interface() varTag := rt.Field(i).Tag varSize := rv.Field(i).Type().Size() if rt.Field(i).Type.Kind().String() == "struct" { printUsingInterface(varValue) } else { fmt.Printf("%d: %s (%s) = %+v, size => %d bytes, tag => %s\n", i, varName, varType, varValue, varSize, varTag) } } }
true
7a2ee3c21b2cc3d3c4ba08dbd549072c1e71c98e
Go
reachsudar/CharacterFrequencyTask
/program1.go
UTF-8
239
3.1875
3
[]
no_license
[]
no_license
package main import "fmt" func main() { a := []rune{'a', 'b', 'a', 'a', 'b', 'c', 'd', 'e', 'f', 'c', 'a', 'b', 'a', 'd'} count := 0 for _, v := range a { if v == 'a' { count++ } } fmt.Printf("a occurs %d times", count) }
true
b246bd25353f0aa7177a1ffb3f6d33559deec7a8
Go
alexyer/ghost
/cmd/ghost-benchmark/benchmark_embedded.go
UTF-8
1,883
2.625
3
[ "MIT" ]
permissive
[ "MIT" ]
permissive
package main import ( "sync" "time" "github.com/alexyer/ghost/ghost" ) func obtainCollection() *ghost.Collection { return ghost.GetStorage().GetCollection("main") } func benchmarkEmbeddedSet(gh *ghost.Collection) result { var wg sync.WaitGroup keys, vals := initTestData("set", requests, size, keyrange) start := time.Now() for i := requests; i >= 0; i -= clients { for j := 0; j < clients; j++ { wg.Add(1) go func(i int) { gh.Set(keys[j], vals[j]) wg.Done() }(i) } wg.Wait() } latency := time.Since(start) return result{ totTime: latency, reqSec: float64(requests) / latency.Seconds(), } } func benchmarkEmbeddedGet(gh *ghost.Collection) result { var wg sync.WaitGroup keys, vals := initTestData("get", requests, size, keyrange) populateTestDataEmbedded(gh, keys, vals) start := time.Now() for i := requests; i >= 0; i -= clients { for j := 0; j < clients; j++ { wg.Add(1) go func(i int) { gh.Get(keys[j]) wg.Done() }(i) } wg.Wait() } latency := time.Since(start) return result{ totTime: latency, reqSec: float64(requests) / latency.Seconds(), } } func benchmarkEmbeddedDel(gh *ghost.Collection) result { var wg sync.WaitGroup keys, vals := initTestData("get", requests, size, keyrange) populateTestDataEmbedded(gh, keys, vals) start := time.Now() for i := requests; i >= 0; i -= clients { for j := 0; j < clients; j++ { wg.Add(1) go func(i int) { gh.Del(keys[j]) wg.Done() }(i) } wg.Wait() } wg.Wait() latency := time.Since(start) return result{ totTime: latency, reqSec: float64(requests) / latency.Seconds(), } } func populateTestDataEmbedded(gh *ghost.Collection, keys, vals []string) { var wg sync.WaitGroup for i := 0; i < requests; i++ { wg.Add(1) go func(i int) { gh.Set(keys[i], vals[i]) wg.Done() }(i) } wg.Wait() return }
true
2d834391ae1f3f45a86fc01a0a34779f28ce37e5
Go
YaleOpenLab/opensolar-archive
/stablecoin/stablecoin.go
UTF-8
5,223
2.609375
3
[ "MIT" ]
permissive
[ "MIT" ]
permissive
package stablecoin // the idea of this stablecoin package is to issue a stablecoin on stellar testnet // so that we can test the function of something similar on mainnet. The stablecoin // provider should be stored in a different database because we will not be migrating // this. // The idea is to issue a single USD token for every USD t hat we receive on our // account, this should be automated and we must not have any kind of user interaction that is in // place here. We also need a stablecoin Code, which we shall call as "STABLEUSD" // for easy reference. Most functions would be similar to the one in assets.go, // but need to be tailored to suit our requirements // the USD token defined here is what is issued by the speciifc bank. Ideally, we // could accept a tx hash and check it as well, but since we can query balances, // much easier to do it this way. // or can be something like a stablecoin or token import ( "context" "fmt" "log" "os" assets "github.com/YaleOpenLab/opensolar/assets" consts "github.com/YaleOpenLab/opensolar/consts" oracle "github.com/YaleOpenLab/opensolar/oracle" scan "github.com/YaleOpenLab/opensolar/scan" utils "github.com/YaleOpenLab/opensolar/utils" wallet "github.com/YaleOpenLab/opensolar/wallet" xlm "github.com/YaleOpenLab/opensolar/xlm" "github.com/stellar/go/build" "github.com/stellar/go/clients/horizon" ) var StableUSD build.Asset var PublicKey string var Seed string var Code = "STABLEUSD" // InitStableCoin returns the platform structure and the seed func InitStableCoin() error { var publicKey string var seed string var err error // now we can be sure we have the directory, check for seed if _, err := os.Stat(consts.StableCoinSeedFile); !os.IsNotExist(err) { // the seed exists fmt.Println("ENTER YOUR PASSWORD TO DECRYPT THE STABLECOIN SEED FILE") password, err := scan.ScanRawPassword() if err != nil { log.Println(err) return err } publicKey, seed, err = wallet.RetrieveSeed(consts.StableCoinSeedFile, password) } else { fmt.Println("Enter a password to encrypt your stablecoin's master seed. Please store this in a very safe place. This prompt will not ask to confirm your password") password, err := scan.ScanRawPassword() if err != nil { return err } publicKey, seed, err = wallet.NewSeed(consts.StableCoinSeedFile, password) err = xlm.GetXLM(publicKey) } // the user doesn't have seed, so create a new platform if err != nil { return err } PublicKey = publicKey Seed = seed StableUSD.Issuer = PublicKey StableUSD.Code = "STABLEUSD" go ListenForPayments() return err } // ListenForPayments listens for payments to the stablecoin account and once it // gets the transaction hash from the rmeote API, calculates how much USD it owes // for the amount deposited and then transfers the StableUSD asset to the payee // Prices are retrieved from an oracle. func ListenForPayments() { // the publicKey above has to be hardcoded as a constant because stellar's API wants it like so // stupid stuff, but we need to go ahead with it. In reality, this shouldn't // be much of a problem since we expect that the platform's seed will be // constant ctx := context.Background() // start in the background context cursor := horizon.Cursor("now") fmt.Println("Waiting for a payment...") err := xlm.TestNetClient.StreamPayments(ctx, consts.StableCoinAddress, &cursor, func(payment horizon.Payment) { /* Sample Response: Payment type payment Payment Paging Token 5424212982374401 Payment From GC76MINOSNQUMDBNONBARFYFCCQA5QLNQSJOVANR5RNQVHQRB5B46B6I Payment To GBAACP6UUXZAB5ZAYAHWEYLNKORWB36WVBZBXWNPFXQTDY2AIQFM6D7Y Payment Asset Type native Payment Asset Code Payment Asset Issuer Payment Amount 10.0000000 Payment Memo Type Payment Memo */ log.Println("Stablecoin payment to/from detected") log.Println("Payment type", payment.Type) log.Println("Payment Paging Token", payment.PagingToken) log.Println("Payment From", payment.From) log.Println("Payment To", payment.To) log.Println("Payment Asset Type", payment.AssetType) log.Println("Payment Asset Code", payment.AssetCode) log.Println("Payment Asset Issuer", payment.AssetIssuer) log.Println("Payment Amount", payment.Amount) log.Println("Payment Memo Type", payment.Memo.Type) log.Println("Payment Memo", payment.Memo.Value) if payment.Type == "payment" && payment.AssetType == "native" { // store the stuff that we want here payee := payment.From amount := payment.Amount log.Printf("Received request for stablecoin from %s worth %s", payee, amount) xlmWorth := oracle.ExchangeXLMforUSD(amount) log.Println("The deposited amount is worth: ", xlmWorth) // now send the stableusd asset over to this guy _, hash, err := assets.SendAssetFromIssuer(Code, payee, utils.FtoS(xlmWorth), Seed, PublicKey) if err != nil { log.Println("Error while sending USD Assets back to payee: ", payee) log.Println(err) // don't skip here, there's technically nothing we can do } log.Println("Successful payment, hash: ", hash) } }) if err != nil { // we shouldn't ideally fatal here, but do since we're testing out stuff log.Fatal(err) } }
true
c9fe5804f4ad2bfde5c995b4f42d3c7afbc4747b
Go
johnweldon/unifi-scheduler
/pkg/nats/agent.go
UTF-8
6,065
2.65625
3
[]
no_license
[]
no_license
package nats import ( "context" "errors" "fmt" "log" "strings" "time" "github.com/johnweldon/unifi-scheduler/pkg/unifi" ) func NewAgent(s *unifi.Session, base string, opts ...ClientOpt) *Agent { addnl := []ClientOpt{ OptBuckets(DetailBucket(base), ByMACBucket(base), ByNameBucket(base)), OptStreams(EventStream(base)), } return &Agent{ client: s, publisher: NewPublisher(append(opts, addnl...)...), base: base, } } type Agent struct { client *unifi.Session publisher *Publisher base string } func (a *Agent) Start(ctx context.Context) error { if a.client == nil { return errors.New("missing unifi client") } if a.publisher == nil { return errors.New("missing publisher") } if a.base == "" { return errors.New("missing base name") } go a.serve(ctx) return nil } func (a *Agent) serve(ctx context.Context) { var err error eventInterval := time.After(1 * time.Second) lookupInterval := time.After(7 * time.Second) clientInterval := time.After(11 * time.Second) userInterval := time.After(19 * time.Second) deviceInterval := time.After(47 * time.Second) for { select { case <-ctx.Done(): return case <-eventInterval: eventInterval = time.After(37 * time.Second) if err = a.publishEvents(); err != nil { log.Printf("error: publishing events %v", err) } case <-clientInterval: clientInterval = time.After(53 * time.Second) if err = a.refreshClients(); err != nil { log.Printf("error: refreshing clients %v", err) } case <-userInterval: userInterval = time.After(337 * time.Second) if err = a.refreshUsers(); err != nil { log.Printf("error: refreshing users %v", err) } case <-deviceInterval: deviceInterval = time.After(607 * time.Second) if err = a.refreshDevices(); err != nil { log.Printf("error: refreshing devices %v", err) } case <-lookupInterval: lookupInterval = time.After(997 * time.Second) if err = a.refreshLookups(); err != nil { log.Printf("error: refreshing lookups %v", err) } } } } func (a *Agent) publishEvents() error { events, err := a.client.GetRecentEvents() if err != nil { return fmt.Errorf("get events: %w", err) } for _, evt := range events { if err = a.publishStream(EventStream(a.base), string(evt.Key), evt); err != nil { return fmt.Errorf("publish events: %w", err) } } const maxEvents = 500 if len(events) > maxEvents { events = events[len(events)-500:] } if err = a.store(DetailBucket(a.base), EventsKey, events); err != nil { return fmt.Errorf("persisting recent events: %w", err) } return nil } func (a *Agent) refreshClients() error { clients, err := a.client.GetClients() if err != nil { return fmt.Errorf("get clients: %w", err) } if err = a.publish("clients", clients); err != nil { return err } if err = a.store(DetailBucket(a.base), ActiveKey, clients); err != nil { return fmt.Errorf("persisting live clients: %w", err) } return nil } func (a *Agent) refreshUsers() error { users, err := a.client.GetAllClients() if err != nil { return fmt.Errorf("get users: %w", err) } if err = a.publish("users", users); err != nil { return err } for _, user := range users { mac := user.MAC.String() if err = a.store(DetailBucket(a.base), mac, user); err != nil { return fmt.Errorf("persisting user %q: %w", mac, err) } } return nil } func (a *Agent) refreshDevices() error { devices, err := a.client.GetDevices() if err != nil { return fmt.Errorf("get devices: %w", err) } if err = a.publish(DevicesSubject, devices); err != nil { return err } for _, device := range devices { mac := device.MAC.String() if err = a.store(DetailBucket(a.base), mac, device); err != nil { return fmt.Errorf("persisting device %q: %w", mac, err) } } if err = a.store(DetailBucket(a.base), DevicesKey, devices); err != nil { return fmt.Errorf("persisting devices: %w", err) } return nil } func (a *Agent) refreshLookups() error { macs, err := a.client.GetMACs() if err != nil { return fmt.Errorf("get MACs: %w", err) } for k, v := range macs { mac := k.String() if err = a.store(ByMACBucket(a.base), mac, v); err != nil { return fmt.Errorf("persisting MAC names %q: %w", mac, err) } } names, err := a.client.GetNames() if err != nil { return fmt.Errorf("get names: %w", err) } for k, v := range names { if err = a.store(ByNameBucket(a.base), k, v); err != nil { return fmt.Errorf("persisting name MACs %q: %w", k, err) } } return nil } func (a *Agent) publish(subject string, msg any) error { if err := a.publisher.Publish(subSubject(a.base, subject), msg); err != nil { return fmt.Errorf("publish: %w", err) } return nil } func (a *Agent) publishStream(stream, subject string, msg any) error { if err := a.publisher.PublishStream(stream, subject, msg); err != nil { return fmt.Errorf("publish stream %q: %w", stream, err) } return nil } func (a *Agent) store(bucket, key string, val any) error { norm := NormalizeKey(key) if norm == "" { return nil } if err := a.publisher.Store(bucket, norm, val); err != nil { return fmt.Errorf("storing key %q: %w", norm, err) } return nil } const ( ActiveKey = "active" DevicesKey = "devices" EventsKey = "events" DevicesSubject = "devices" ) func DetailBucket(base string) string { return base + "-details" } func ByMACBucket(base string) string { return base + "-bymac" } func ByNameBucket(base string) string { return base + "-byname" } func EventStream(base string) string { return base + "-events" } func subSubject(base, subject string) string { return base + "." + subject } func NormalizeKey(s string) string { fn := func(r rune) rune { switch { case r >= 'a' && r <= 'z': return r case r >= '0' && r <= '9': return r case r == '.': return r case r == '-': return r case r == ':': return '-' case r == ' ': return '-' default: return -1 } } return strings.Map(fn, strings.ToLower(strings.TrimSpace(s))) }
true
3795b575e11b20615f7979d5c0db1dacc86395c3
Go
anzhihe/learning
/golang/source_code/Go语言基础与提升课程资料/源码/07_常量.go
UTF-8
745
4.1875
4
[]
no_license
[]
no_license
package main import "fmt" func main() { var number int = 123 number = 456 fmt.Println(number) //const num int //num=123 错误:常量在赋值的时候就需要进行初始化操作 const num int = 123 //num = 456 错误:常量不能进行任何的更改 //小结:变量:是可以变化的量,常量的值不能进行任何的更改;常量的应用场景:主要用在程序一开始就确定好值, //后续不能进行任何的修改(比如:圆周率、游戏的等级等) const NUM = 333 //充分说明:Go语言区分大小写;多学一招;常量一般用大写字母来表示 fmt.Println(NUM) fmt.Println("常量是:", num) m := 3 + 2i fmt.Println(m) fmt.Printf("m变量的格式是:%T", m) }
true
8b43454f3be863dd22390711c399bbc76dab13c2
Go
horaciob/pla
/boomer/boomer.go
UTF-8
6,218
2.703125
3
[ "Apache-2.0" ]
permissive
[ "Apache-2.0" ]
permissive
// 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 boomer provides commands to run load tests and display results. package boomer import ( "crypto/tls" "math" "net" "runtime" "sync" "time" "github.com/Clever/leakybucket" "github.com/Clever/leakybucket/memory" "github.com/valyala/fasthttp" ) // Result keeps information of a request done by Boomer. type Result struct { Err error StatusCode int Duration time.Duration ContentLength int } // Boomer is the structure responsible for performing requests. type Boomer struct { // Request is the request to be made. Request *fasthttp.Request Addr string // Timeout in seconds. Timeout time.Duration ConnectTimeout time.Duration ReadTimeout time.Duration WriteTimeout time.Duration // C is the concurrency level, the number of concurrent workers to run. C uint // N is the total number of requests to make. N uint // F is a flag to abort execution on a request failure F bool // Duration is the amount of time the test should run. Duration time.Duration bucket leakybucket.Bucket results chan Result stop chan struct{} stopLock sync.Mutex jobs chan *fasthttp.Request running bool wg *sync.WaitGroup client *fasthttp.HostClient } // NewBoomer returns a new instance of Boomer for the specified request. func NewBoomer(addr string, req *fasthttp.Request) *Boomer { return &Boomer{ C: uint(runtime.NumCPU()), Addr: addr, Request: req, results: make(chan Result), stop: make(chan struct{}), jobs: make(chan *fasthttp.Request), wg: &sync.WaitGroup{}, } } // WithTimeout specifies the timeout for every request made by Boomer. func (b *Boomer) WithTimeout(t time.Duration) *Boomer { b.Timeout = t return b } // WithAmount specifies the total amount of requests Boomer should execute. func (b *Boomer) WithAmount(n uint) *Boomer { if n > 0 { b.Duration = 0 } b.N = n return b } // WithDuration specifies the duration of the test that Boomer will perform. func (b *Boomer) WithDuration(d time.Duration) *Boomer { if b.running { panic("Cannot modify boomer while running") } if d > 0 { b.N = 0 } b.Duration = d return b } // WithRateLimit configures Boomer to never overpass a certain rate. func (b *Boomer) WithRateLimit(n uint, rate time.Duration) *Boomer { if n > 0 { b.bucket, _ = memory.New().Create("pla", n-1, rate) } return b } // WithConcurrency determines the amount of concurrency Boomer should use. // Defaults to the amount of cores of the running machine. func (b *Boomer) WithConcurrency(c uint) *Boomer { if b.running { panic("Cannot modify boomer while running") } if c == 0 { c = uint(runtime.NumCPU()) } b.C = c b.results = make(chan Result, c) return b } // WithAbortionOnFailure determines if pla should stop if any request fails func (b *Boomer) WithAbortionOnFailure(f bool) *Boomer { if b.running { panic("Cannot modify boomer while running") } b.F = f return b } // Results returns receive-only channel of results func (b *Boomer) Results() <-chan Result { return b.results } // Stop indicates Boomer to stop processing new requests func (b *Boomer) Stop() { b.stopLock.Lock() defer b.stopLock.Unlock() if !b.running { return } b.running = false close(b.stop) } // Wait blocks until Boomer successfully finished or is fully stopped func (b *Boomer) Wait() { b.wg.Wait() close(b.results) } // Run makes all the requests, prints the summary. It blocks until // all work is done. func (b *Boomer) Run() { if b.running { return } b.client = &fasthttp.HostClient{ Addr: b.Addr, Dial: func(addr string) (net.Conn, error) { return fasthttp.DialTimeout(addr, b.ConnectTimeout) }, TLSConfig: &tls.Config{ InsecureSkipVerify: true, }, MaxConns: math.MaxInt32, ReadTimeout: b.ReadTimeout, WriteTimeout: b.WriteTimeout, } b.running = true if b.Duration > 0 { time.AfterFunc(b.Duration, func() { b.Stop() }) } b.runWorkers() } func (b *Boomer) runWorkers() { b.wg.Add(int(b.C)) var i uint for i = 0; i < b.C; i++ { go b.runWorker() } b.wg.Add(1) go b.triggerLoop() } func (b *Boomer) runWorker() { resp := fasthttp.AcquireResponse() req := fasthttp.AcquireRequest() for r := range b.jobs { req.Reset() resp.Reset() r.CopyTo(req) s := time.Now() var code int var size int var err error if b.Timeout > 0 { err = b.client.DoTimeout(req, resp, b.Timeout) } else { err = b.client.Do(req, resp) } if err == nil { size = resp.Header.ContentLength() code = resp.Header.StatusCode() } b.notifyResult(code, size, err, time.Now().Sub(s)) } fasthttp.ReleaseResponse(resp) fasthttp.ReleaseRequest(req) b.wg.Done() } func (b *Boomer) notifyResult(code int, size int, err error, d time.Duration) { b.results <- Result{ StatusCode: code, Duration: d, Err: err, ContentLength: size, } //If any request gets a 5xx status code or conn reset error, and user has specified F flag, pla execution is stopped //Why 5xx? Because it is not considered as an application business error if (code >= 500 || err != nil) && b.F { b.Stop() } } func (b *Boomer) checkRateLimit() error { if b.bucket == nil { return nil } _, err := b.bucket.Add(1) return err } func (b *Boomer) triggerLoop() { defer b.wg.Done() defer close(b.jobs) var i uint for { if b.Duration == 0 && i >= b.N { return } select { case <-b.stop: return case b.jobs <- b.Request: i++ err := b.checkRateLimit() if err != nil { time.Sleep(b.bucket.Reset().Sub(time.Now())) } } } }
true
089df887671f0a73fe74c92e00e1c5e8e79e0130
Go
junqueira/wgadmin
/pkg/api/meta_test.go
UTF-8
6,300
2.546875
3
[]
no_license
[]
no_license
package api import ( "bytes" "fmt" "net" "testing" "github.com/google/go-cmp/cmp" "golang.org/x/crypto/curve25519" ) func TestWireguardServerConfigToIni(t *testing.T) { // PrivateKey was generated using: wg genkey expOutput := []byte(`[Interface] Address = 10.100.0.10/32 ListenPort = 51820 PrivateKey = GNyaar5SFUOf3emHLP+dhyTTKT6zXlmkZB0bg2uuFHQ= PostUp = ip link set mtu 1500 dev ens4 PostUp = ip link set mtu 1500 dev %i PostUp = sysctl -w net.ipv4.ip_forward=1 PostDown = sysctl -w net.ipv4.ip_forward=0 PostDown = iptables -D FORWARD -o %i -j ACCEPT PostDown = iptables -D FORWARD -i %i -j ACCEPT `) pk, err := ParseKey("GNyaar5SFUOf3emHLP+dhyTTKT6zXlmkZB0bg2uuFHQ=") if err != nil { t.Fatalf("failed parsing key: %v", err) } w := &WireguardServerConfig{ UID: "foo", Address: ParseCIDR("10.100.0.10/32"), ListenPort: 51820, PrivateKey: &pk, PostUp: []string{ "ip link set mtu 1500 dev ens4", "ip link set mtu 1500 dev %i", "sysctl -w net.ipv4.ip_forward=1", }, PostDown: []string{ "sysctl -w net.ipv4.ip_forward=0", "iptables -D FORWARD -o %i -j ACCEPT", "iptables -D FORWARD -i %i -j ACCEPT", }, } var buf bytes.Buffer if err := HandleTemplates(string(templateWireguardServerConfig), &buf, w); err != nil { t.Fatalf("failed handling template: %v", err) } if diff := cmp.Diff(string(expOutput), buf.String()); diff != "" { t.Fatalf("unexpected ini output (-want +got):\n%s", diff) } } func TestWireguardServerPeersConfigToIni(t *testing.T) { expOutput := []byte(`[Peer] PublicKey = 8AO7DXtcu//EolOd9zevkU6Rro0DDgCbnjXm4OUWcWs= AllowedIPs = 192.168.180.2/32 [Peer] PublicKey = b/p252rtUdFg7Z7ENKsjguhBYfjsplzvWKCCWGsOCgo= AllowedIPs = 192.168.180.3/32 [Peer] PublicKey = T7WIUxjK4koRiKles/5dNUs5naOJtJf4Oq8m6IeVaxM= AllowedIPs = 192.168.180.4/32 `) // wg genkey | wg pubkey pubkey01, _ := ParseKey("8AO7DXtcu//EolOd9zevkU6Rro0DDgCbnjXm4OUWcWs=") pubkey02, _ := ParseKey("b/p252rtUdFg7Z7ENKsjguhBYfjsplzvWKCCWGsOCgo=") pubkey03, _ := ParseKey("T7WIUxjK4koRiKles/5dNUs5naOJtJf4Oq8m6IeVaxM=") w := &WireguardServerConfig{ ActivePeers: []Peer{ { PublicKey: &pubkey01, AllowedIPs: *ParseCIDR("192.168.180.2/32"), }, { PublicKey: &pubkey02, AllowedIPs: *ParseCIDR("192.168.180.3/32"), }, { PublicKey: &pubkey03, AllowedIPs: *ParseCIDR("192.168.180.4/32"), }, }, } var buf bytes.Buffer if err := HandleTemplates(string(templateWireguardServerPeersConfig), &buf, w); err != nil { t.Fatalf("failed handling template: %v", err) } if diff := cmp.Diff(string(expOutput), buf.String()); diff != "" { t.Fatalf("unexpected ini output (-want +got):\n%s", diff) } } func TestWireguardClientConfigToIni(t *testing.T) { expOutput := []byte(`[Interface] PrivateKey = +P5vXpg6yPdq5mG1KNmSamFPKvzbBEJ6OqYYidwKREo= Address = 192.168.180.2/32 DNS = 1.1.1.1, 8.8.8.8 [Peer] PublicKey = Xn9vjTRVlfm2nxVTMATZy73EJWRYWv7db2z13o2e5R4= AllowedIPs = 0.0.0.0/0, ::/0 Endpoint = wg-dev.vpn.domain.tld:51820 PersistentKeepalive = 25 `) // wg genkey privkey, _ := ParseKey("+P5vXpg6yPdq5mG1KNmSamFPKvzbBEJ6OqYYidwKREo=") w := &WireguardClientConfig{ UID: "foo", InterfaceClientConfig: InterfaceClientConfig{ PrivateKey: &privkey, Address: ParseCIDR("192.168.180.2/32"), DNS: []net.IP{net.ParseIP("1.1.1.1"), net.ParseIP("8.8.8.8")}, }, PeerClientConfig: PeerClientConfig{ PublicKey: privkey.PublicKey().String(), AllowedIPs: ParseAllowedIPs("0.0.0.0/0", "::/0"), Endpoint: "wg-dev.vpn.domain.tld:51820", PersistentKeepAlive: 25, }, } var buf bytes.Buffer if err := HandleTemplates(string(templateWireguardClientConfig), &buf, w); err != nil { t.Fatalf("failed handling template: %v", err) } if diff := cmp.Diff(string(expOutput), buf.String()); diff != "" { t.Fatalf("unexpected ini output (-want +got):\n%s", diff) } } func TestPreparedKeys(t *testing.T) { // Keys generated via "wg genkey" and "wg pubkey" for comparison // with this Go implementation. const ( private = "GHuMwljFfqd2a7cs6BaUOmHflK23zME8VNvC5B37S3k=" public = "aPxGwq8zERHQ3Q1cOZFdJ+cvJX5Ka4mLN38AyYKYF10=" ) priv, err := ParseKey(private) if err != nil { t.Fatalf("failed to parse private key: %v", err) } if diff := cmp.Diff(private, priv.String()); diff != "" { t.Fatalf("unexpected private key (-want +got):\n%s", diff) } pub := priv.PublicKey() if diff := cmp.Diff(public, pub.String()); diff != "" { t.Fatalf("unexpected public key (-want +got):\n%s", diff) } } func TestKeyExchange(t *testing.T) { privA, pubA := mustKeyPair() privB, pubB := mustKeyPair() // Perform ECDH key exhange: https://cr.yp.to/ecdh.html. var sharedA, sharedB [32]byte curve25519.ScalarMult(&sharedA, privA, pubB) curve25519.ScalarMult(&sharedB, privB, pubA) if diff := cmp.Diff(sharedA, sharedB); diff != "" { t.Fatalf("unexpected shared secret (-want +got):\n%s", diff) } } func TestBadKeys(t *testing.T) { // Adapt to fit the signature used in the test table. parseKey := func(b []byte) (Key, error) { return ParseKey(string(b)) } tests := []struct { name string b []byte fn func(b []byte) (Key, error) }{ { name: "bad base64", b: []byte("xxx"), fn: parseKey, }, { name: "short base64", b: []byte("aGVsbG8="), fn: parseKey, }, { name: "short key", b: []byte("xxx"), fn: NewKey, }, { name: "long base64", b: []byte("ZGVhZGJlZWZkZWFkYmVlZmRlYWRiZWVmZGVhZGJlZWZkZWFkYmVlZg=="), fn: parseKey, }, { name: "long bytes", b: bytes.Repeat([]byte{0xff}, 40), fn: NewKey, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { _, err := tt.fn(tt.b) if err == nil { t.Fatal("expected an error, but none occurred") } t.Logf("OK error: %v", err) }) } } // func TestSerializeWireguardServerConfig(t *testing.T) { // priv, err := GeneratePrivateKey() // if err != nil { // panicf("failed to generate private key: %v", err) // } // wgconf := WireguardServerConfig{ // UID: "foo", // Address: "192.168.150.1/32", // ListenPort: 5180, // PrivateKey: &priv, // PostUp: []string{"postup-commands"}, // PostDown: []string{"postdown-commands"}, // } // data, err := json.Marshal(wgconf) // if err != nil { // t.Fatalf("failed serializing: %v", err) // } // t.Log(string(data)) // } func mustKeyPair() (private, public *[32]byte) { priv, err := GeneratePrivateKey() if err != nil { panicf("failed to generate private key: %v", err) } return keyPtr(priv), keyPtr(priv.PublicKey()) } func keyPtr(k Key) *[32]byte { b32 := [32]byte(k) return &b32 } func panicf(format string, a ...interface{}) { panic(fmt.Sprintf(format, a...)) }
true
7f45256b2668d90ec4355ce71a37be11c3f241c0
Go
xavimoreno548/GolangFirstSteps
/structs.go
UTF-8
551
4.375
4
[]
no_license
[]
no_license
package main import "fmt" // User struct to represent users, contains a name and age type User struct { name string age int } // Function to set the name of user, that function belongs to the User struct func (user *User) setName(name string) { user.name = name } // Function to get the name of user, that function belongs to the User struct func (user User) getName() string { return user.name } func main() { // We created a variable of type User, and fill the name and age userOne := User{name: "Xavi", age: 28} fmt.Println(userOne) }
true
cfa616d57f5149aeadef8043f3a00ed1ac105b34
Go
kanosaki/dumper
/tumblr/client.go
UTF-8
1,026
2.671875
3
[]
no_license
[]
no_license
package tumblr import ( "context" "encoding/json" ) type TumblrClient struct { request *TumblrRequest } func NewTumblrClient(consumerKey, consumerSecret, oauthToken, oauthSecret, callbackUrl, host string) *TumblrClient { return &TumblrClient{ request: NewTumblrRequest(consumerKey, consumerSecret, oauthToken, oauthSecret, callbackUrl, host), } } func (tc *TumblrClient) Dashboard(ctx context.Context, dp *DashboardParams) (*DashboardResponse, error) { var base BaseResponse if err := tc.request.Get(ctx, "/v2/user/dashboard", dp.Params(), &base); err != nil { return nil, err } var dr DashboardResponse if err := json.Unmarshal(base.Response, &dr); err != nil { return nil, err } return &dr, nil } func (tc *TumblrClient) Info(ctx context.Context) (*Info, error) { var base BaseResponse if err := tc.request.Get(ctx, "/v2/user/info", nil, &base); err != nil { return nil, err } var info Info if err := json.Unmarshal(base.Response, &info); err != nil { return nil, err } return &info, nil }
true
e5d9c6fe77cbcea1a70f10d297fb064b66c9ebd8
Go
deadkrolik/godbt
/godbt.go
UTF-8
924
2.640625
3
[ "MIT" ]
permissive
[ "MIT" ]
permissive
package godbt import ( "errors" "github.com/deadkrolik/godbt/contract" "github.com/deadkrolik/godbt/installers" ) //Tester - simple DB tester type Tester struct { imageManager *ImageManager installer contract.Installer } //GetTester - tester instance func GetTester(config contract.InstallerConfig) (*Tester, error) { var installer contract.Installer var err error switch config.Type { case "mysql": installer, err = installers.GetInstallerMysql(config) if err != nil { return nil, err } default: return nil, errors.New("Unknown loader name: " + config.Type) } return &Tester{ imageManager: getImageManager(), installer: installer, }, nil } //GetImageManager - Image manager func (tester *Tester) GetImageManager() *ImageManager { return tester.imageManager } //GetInstaller - installer instance func (tester *Tester) GetInstaller() contract.Installer { return tester.installer }
true
382317e2a543bf509182d8e2266f1a8765e000de
Go
huskerona/xkcd-v2
/comic/xkcd.go
UTF-8
1,752
3.109375
3
[]
no_license
[]
no_license
package comic import ( "fmt" "xkcd2/config" "xkcd2/tools/imaging" "xkcd2/tools/logger" ) // XKCD struct that stores the data returned from the JSON document from the xkcd website. type XKCD struct { Day string `json:"day"` Month string `json:"month"` Year string `json:"year"` Number int `json:"num"` Title string `json:"title"` SafeTitle string `json:"safe_title"` Transcript string `json:"transcript"` ImageURL string `json:"img"` ImageAlt string `json:"alt"` News string `json:"news"` Link string `json:"link"` // base64 encoded image downloaded from ImageURL Image string } // Download fetches the JSON contents of the XKCD comic based on its number. If number is 0 it will // fetch the latest issue. The JSON file is unmarshalled into XKCD structure. The Image file is not downloaded // and it needs a separate call to DownloadImage func (xkcd *XKCD) Download(comicNumber int) error { defer logger.Trace("func DownloadComic")() var err error var url string if comicNumber == 0 { url = fmt.Sprintf("%s/%s", config.HomeURL, config.JSONURL) } else { url = fmt.Sprintf("%s/%d/%s", config.HomeURL, comicNumber, config.JSONURL) } temp, err := fetch(url) if temp != nil { *xkcd = *temp } return err } // DownloadImage fetches an XKCD image from imageURL. // NOTE: There are some comics whose image cannot be retrieved. It would require that we parse the HTML. // For that reason the error is ignored, but in any case, XKCD struct is returned while Image is left as empty string. func (xkcd *XKCD) DownloadImage(imageURL string) error { imageByte, err := downloadImage(imageURL) if err == nil { xkcd.Image = imaging.EncodeToBase64(imageByte) } return nil }
true
46fa7bbe8cca11666b5fbf7899780d751f606271
Go
LiamLeFey/SampleCode
/go/mudmap/MudMap.go
UTF-8
35,922
2.5625
3
[]
no_license
[]
no_license
package mudmap import ( "os" "fmt" "strings" "sort" "regexp" "container/list" "strconv" "project/tools" "project/persistence" ) // so this is the mud map. // this has most of the logic of dealing with more than one type of // map object. The specific logic of dealing with just one object // type (ike Room) is in the specific object file. This file works // with the logic of dealing with multiple types of object. The // exception to this is Path, which deals with multiple types of // object, but has it's own file, since there's so much logic // involved. //Also, this is where the objects are cached. // Rooms are cached in a limited size cache, all of the Tags and // Regions are kept in memory, and everything else is loaded from // disk when needed. // Tags and NamedRooms are also kept in memory. type MudMap struct { bin *persistence.PBin strIndex *PStringFinder siFile *os.File rmIndex *RoomFinder riFile *os.File prevRoom int64 currentRoom int64 regionsById map[int64] *Region ridsByName map[string] int64 alteredRegions map [int64] bool tagsById map[int64]*Tag tagsByName map[string]*Tag namedRooms map[string] *NamedRoom rmc *roomCache } func Create( dir *os.File ) (m *MudMap, e os.Error){ dirfi, e := dir.Stat() if e != nil { return nil, e } var bfn, sfn, rfn string if strings.HasSuffix( dirfi.Name, "/" ) { bfn = dirfi.Name + "MapData.dat" sfn = dirfi.Name + "StringIndex.dat" rfn = dirfi.Name + "RoomIndex.dat" } else { bfn = dirfi.Name + "/MapData.dat" sfn = dirfi.Name + "/StringIndex.dat" rfn = dirfi.Name + "/RoomIndex.dat" } binf, e := os.OpenFile( bfn, os.O_RDWR | os.O_CREATE, 0640 ) if e != nil { return nil, e } m = new( MudMap ) m.siFile, e = os.OpenFile( sfn, os.O_RDWR | os.O_CREATE, 0640 ) if e != nil { return nil, e } m.riFile, e = os.OpenFile( rfn, os.O_RDWR | os.O_CREATE, 0640 ) if e != nil { return nil, e } m.bin, e = persistence.NewPBin( binf ) if e != nil { return nil, e } e = m.loadIndexes() if e != nil { return nil, e } m.alteredRegions = make( map [int64] bool, 5 ) return m, nil } func (mm *MudMap) Release() (e os.Error) { mm.bin.Rollback() e = mm.bin.Close() if e != nil { return e } e = mm.siFile.Close() if e != nil { return e } e = mm.riFile.Close() if e != nil { return e } mm.bin = nil mm.strIndex = nil mm.rmIndex = nil mm.regionsById = nil mm.ridsByName = nil mm.alteredRegions = nil mm.tagsById = nil mm.tagsByName = nil mm.namedRooms = nil return nil } func (mm *MudMap) Commit() (e os.Error) { e = mm.fixAlteredRegions() if e != nil { return e } e = mm.bin.Commit() if e != nil { return e } _, e = mm.siFile.Seek( 0, 0 ) if e != nil { return e } _, e = mm.siFile.Write( mm.strIndex.Write() ) if e != nil { return e } _, e = mm.riFile.Seek( 0, 0 ) if e != nil { return e } _, e = mm.riFile.Write( mm.rmIndex.Write() ) if e != nil { return e } return nil } func (mm *MudMap) CommitAndPack() (e os.Error) { e = mm.fixAlteredRegions() if e != nil { return e } e = mm.bin.CommitAndPack() if e != nil { return e } _, e = mm.siFile.Seek( 0, 0 ) if e != nil { return e } _, e = mm.siFile.Write( mm.strIndex.Write() ) if e != nil { return e } _, e = mm.riFile.Seek( 0, 0 ) if e != nil { return e } _, e = mm.riFile.Write( mm.rmIndex.Write() ) if e != nil { return e } return nil } func (mm *MudMap) loadIndexes() (e os.Error) { _, e = mm.siFile.Seek( 0, 0 ) if e != nil { return e } mm.strIndex = new( PStringFinder ) fi, e := mm.siFile.Stat() if e != nil { return e } bs := make( []byte, int(fi.Size) ) n := 0 for n < len( bs ) { r, e := mm.siFile.Read( bs[ n: ] ) if e != nil {return e} n += r } e = mm.strIndex.Read( bs ) // an error is returned if len(bs) == 0, but the PStringFinder is // still valid (though empty) if e != nil && len( bs ) > 0 { return e } setPStringFinder( mm.bin, mm.strIndex ) _, e = mm.riFile.Seek( 0, 0 ) if e != nil { return e } mm.rmIndex = new( RoomFinder ) fi, e = mm.riFile.Stat() if e != nil { return e } bs = make( []byte, int(fi.Size) ) n = 0 for n < len( bs ) { r, e := mm.riFile.Read( bs[ n: ] ) if e != nil {return e} n += r } e = mm.rmIndex.Read( bs ) // an error is returned if len(bs) == 0, but the RoomFinder is // still valid (though empty) if e != nil && len( bs ) > 0 { return e } ids := mm.bin.IdsOfType( REGION_HASH ) mm.regionsById = make( map[int64] *Region, len( ids ) ) mm.ridsByName = make( map[string] int64, len( ids ) ) for i := range ids { r := new (Region) e = mm.bin.Load( ids[i], r ) if e != nil { return e } mm.regionsById[ids[i]] = r mm.ridsByName[ mm.regionsById[ids[i]].name ] = ids[i] } ids = mm.bin.IdsOfType( TAG_HASH ) mm.tagsById = make( map[int64]*Tag, len( ids ) ) mm.tagsByName = make( map[string]*Tag, len( ids ) ) for i := range ids { t := new (Tag) e = mm.bin.Load( ids[i], t ) if e != nil { return e } mm.tagsById[t.id] = t mm.tagsByName[t.desc] = t } ids = mm.bin.IdsOfType( NAMED_ROOM_HASH ) mm.namedRooms = make( map[ string ] *NamedRoom, len( ids ) ) for i := range ids { nr := new (NamedRoom) e = mm.bin.Load( ids[i], nr ) if e != nil{ return e } mm.namedRooms[ nr.name ] = nr } var oldSize int if mm.rmc != nil { oldSize = mm.rmc.size }else{ oldSize = 1000 } mm.rmc = new( roomCache ) mm.rmc.size = oldSize mm.rmc.id2e = make( map[int64] *list.Element, mm.rmc.size ) mm.rmc.lst = list.New() return nil } func (mm *MudMap) Rollback() (e os.Error) { mm.alteredRegions = make( map [int64] bool, 5 ) mm.bin.Rollback() if e != nil { return e } // hmm, this is probably not very efficient. // ideally we'd store a static copy of all indexes? and clone them? // on second thought, this is probably fine. e = mm.loadIndexes() if e != nil { return e } return nil } func (mm *MudMap) fixAlteredRegions() (e os.Error) { eStr := "MudMap.fixAlteredRegions: " for k, v := range mm.alteredRegions { if v { e = mm.repathRegion( k ) if e != nil { return os.NewError( eStr+e.String()) } } mm.alteredRegions[ k ] = false, false } return nil } // regionList // (name\(id\))+ || FAIL {reason} func (mm *MudMap) RegionNames() ( []string ) { names := make( []string, len( mm.ridsByName ) ) i := 0 for k, _ := range mm.ridsByName { names[i] = k i++ } sort.Strings( names ) return names } // createNewRegion [name] // regionId || FAIL {reason} func (mm *MudMap) NewRegion( name string ) ( id int64, e os.Error ) { eStr := "MudMap.NewRegion name: "+name+", error: " if _, ok := mm.ridsByName[ name ]; ok { return -1, os.NewError(eStr+"Region already exists.") } r, e := newRegion( mm.bin ) if e != nil { return -1, e } r.name = name e = mm.bin.Store( r ) if e != nil { return -1, e } mm.regionsById[ r.id ] = r mm.ridsByName[ name ] = r.id return r.id, nil } // regionName [id] // regionName || FAIL {reason} func (mm *MudMap) RegionName( id int64 ) ( name string, e os.Error ) { eStr := fmt.Sprint("MudMap.RegionName id: ",id,", error: ") if r, ok := mm.regionsById[ id ]; ok { return r.name, nil } return "", os.NewError( eStr + "no region with id " ) } // regionId [name] // regionId || FAIL {reason} func (mm *MudMap) RegionId( name string ) ( id int64, e os.Error ) { eStr := "MudMap.RegionId Name: "+name+", error: " if i, ok := mm.ridsByName[ name ]; ok { return i, nil } return -1, os.NewError( eStr+"no region with name." ) } // renameRegion [regionId] [newName] // SUCCESS Region {oldName} changed to {newName} || FAIL {reason} func (mm *MudMap) RenameRegion( id int64, name string ) ( e os.Error ) { eStr := fmt.Sprint("MudMap.RenameRegion id: ",id,", name: "+name+", error: ") if _, ok := mm.ridsByName[ name ]; ok { return os.NewError(eStr+"Region \""+name+"\" already exists.") } r, ok := mm.regionsById[ id ] if !ok { return os.NewError( fmt.Sprint(eStr+"No region with id " , id )) } mm.ridsByName[ r.name ] = 0, false r.name = name mm.ridsByName[ r.name ] = id e = mm.bin.Store( r ) if e != nil { return e } return nil } // deleteRegion [regionId] // SUCCESS || FAIL {reason} func (mm *MudMap) DeleteRegion( id int64 ) ( e os.Error ) { eStr := fmt.Sprint("MudMap.DeleteRegion id: ",id,", error: ") // make sure it's a region if _, ok := mm.regionsById[ id ]; !ok { return os.NewError( eStr+"No region with id." ) } // ensure we aren't orphaning any Rooms set, e := mm.RoomsInRegion( id ) if e != nil { return os.NewError( eStr+e.String() ) } rids := set.Values() for i := range rids { mm.DeleteRoom( rids[i] ) } e = mm.bin.Delete( id ) if e != nil { return os.NewError( eStr+e.String() ) } mm.ridsByName[ mm.regionsById[ id ].name ] = 0, false mm.regionsById[ id ] = nil, false mm.alteredRegions[ id ] = false, false return nil } func (mm *MudMap) RoomsInRegion( id int64 ) ( ids *tools.SI64Set, e os.Error ){ eStr := fmt.Sprint("MudMap.RoomsInRegion id: ",id,", error: ") // make sure it's a region if _, ok := mm.regionsById[ id ]; !ok { return nil, os.NewError( eStr+"No region with id." ) } return mm.rmIndex.Ids( id, -1, -1, nil ), nil } func (mm *MudMap) RegionOfRoom( id int64 ) ( reg string, e os.Error ){ eStr := fmt.Sprint("MudMap.RegionOfRoom id: ",id,", error: ") r, e := mm.room( id ) if e != nil { return "", os.NewError( eStr + e.String() ) } if r, ok := mm.regionsById[ r.regionId ]; ok { return r.name, nil } return "", os.NewError( eStr + "Room has bad regionId." ) } // createNewRoom <regionId> // roomId || FAIL {reason} func (mm *MudMap) NewRoom( regionId int64 ) ( id int64, e os.Error ) { eStr := fmt.Sprint("MudMap.NewRoom regionId: ",regionId,", error: ") if _, ok := mm.regionsById[ regionId ]; !ok { return -1, os.NewError(eStr+"Invalid regionId") } r, e := newRoom( mm.bin ) if e != nil { return -1, e } r.regionId = regionId mm.bin.Store( r ) mm.rmIndex.RegisterRoom( r ) // we don't add it yet. Without exits, the room doesn't make a // difference to the region. //mm.alteredRegions[regionId] = true return r.id, e } // if used willy nilly, this will almost certainly screw things up. // Unless you're very careful, you'll end up with invalid exits that // used to lead here. func (mm *MudMap) DeleteRoom( rmId int64 ) ( e os.Error ) { r, e := mm.room( rmId ) if e != nil { return e } ts, e := mm.RoomTags( rmId ) if e != nil { return e } for i := range ts { mm.tagsByName[ts[i]].rooms.Remove( rmId ) } mm.rmIndex.RemoveRoom( r ) mm.rmc.remove( rmId ) mm.alteredRegions[ r.regionId ] = true // probably forgot something. I'm not going to // run through every room in the map to delete exits // leading here. mm.bin.Delete( r.id ) return nil } // setCurrentRoom [roomId] // SUCCESS || FAIL {reason} func (mm *MudMap) SetCurrentRoom( id int64 ) ( e os.Error ) { eStr := fmt.Sprint("MudMap.SetCurrentRoom id: ",id,", error: ") if mm.bin.TypeOfId( id ) != ROOM_HASH { return os.NewError( eStr+" No Room with id." ) } mm.prevRoom = mm.currentRoom mm.currentRoom = id return nil } // currentRoom // roomid || FAIL {reason} func (mm *MudMap) CurrentRoom() ( id int64, e os.Error ) { eStr := "MudMap.CurrentRoom, error: " if mm.currentRoom < 1 { return -1, os.NewError( eStr+"Current room not set." ) } return mm.currentRoom, nil } // currentRoom // roomid || FAIL {reason} func (mm *MudMap) PreviousRoom() ( id int64, e os.Error ) { eStr := "MudMap.PreviousRoom, error: " if mm.prevRoom < 1 { return -1, os.NewError( eStr+"Previous room not set." ) } return mm.prevRoom, nil } // this can end up orphaning PStrings, but there's not much we can // do about that except scrub the bin once in a while, since we // don't keep track of reference counts. // setRoomShortDesc <roomId> [newShortDesc] // SUCCESS || FAIL {reason} func (mm *MudMap) SetRmSDesc( rmId int64, sDesc *string ) ( e os.Error ) { eStr := fmt.Sprint("MudMap.SetRmSDesc rmId: ",rmId,", sDesc: "+*sDesc+", error: ") r, e := mm.room( rmId ) if e != nil { return os.NewError( fmt.Sprint(eStr , e )) } mm.rmIndex.RemoveRoom( r ) r.SetShortDesc( sDesc, mm.bin ) mm.bin.Store( r ) mm.rmIndex.RegisterRoom( r ) return nil } // roomShortDesc <roomId> // shortDesc || FAIL {reason} func (mm *MudMap) RmSDesc( rmId int64 ) ( sDesc string, e os.Error ) { eStr := fmt.Sprint("MudMap.RmSDesc rmId: ",rmId,", error: ") r, e := mm.room( rmId ) if e != nil { return "", os.NewError( fmt.Sprint(eStr , e )) } return r.ShortDesc( mm.bin ), nil } // this can end up orphaning PStrings, but there's not much we can // do about that except scrub the bin once in a while, since we // don't keep track of reference counts. // setRoomLongDesc <roomId> [newShortDesc] // SUCCESS || FAIL {reason} func (mm *MudMap) SetRmLDesc( rmId int64, lDesc *string ) ( e os.Error ) { eStr := fmt.Sprint("MudMap.SetRmLDesc rmId: ",rmId,", lDesc: "+*lDesc+", error: ") r, e := mm.room( rmId ) if e != nil { return os.NewError( fmt.Sprint(eStr , e )) } mm.rmIndex.RemoveRoom( r ) r.SetLongDesc( lDesc, mm.bin ) mm.bin.Store( r ) mm.rmIndex.RegisterRoom( r ) return nil } // roomLongDesc <roomId> // longDesc || FAIL {reason} func (mm *MudMap) RmLDesc( rmId int64 ) ( lDesc string, e os.Error ) { eStr := fmt.Sprint("MudMap.RmLDesc rmId: ",rmId,", error: ") r, e := mm.room( rmId ) if e != nil { return "", os.NewError( eStr + e.String() ) } return r.LongDesc( mm.bin ), nil } // whereami // regionId // shortdesc // longdesc // obviousexits func (mm *MudMap) FindRmIds( regId int64, sDesc, lDesc *string, obvExits []string ) ( ids *tools.SI64Set ) { var sdId int64 var ldId int64 var b bool if sDesc == nil { sdId = -1 } else { sdId, b = findPStringId( sDesc, mm.bin ) if !b { return tools.NewSI64Set( 0 ) } } if lDesc == nil { ldId = -1 } else { ldId, b = findPStringId( lDesc, mm.bin ) if !b { return tools.NewSI64Set( 0 ) } } return mm.rmIndex.Ids( regId, sdId, ldId, obvExits ) } // checks to see if the given room is still a valid region exit. removes // it if not. func (mm *MudMap) checkRegionExit( regId int64, rmId int64 ) ( e os.Error ) { eStr :=fmt.Sprint("MudMap.checkRegionExit regId: ",regId,", rmId: ",rmId," error: ") r, e := mm.room( rmId ) if e != nil { return os.NewError( fmt.Sprint(eStr , e )) } reg := mm.regionsById[ regId ] if r.regionId == regId { mm.removeRegionExit( reg, rmId ) return nil } idSet, e := mm.RoomsInRegion( regId ) rmIds := idSet.Values() if e != nil { return os.NewError( fmt.Sprint(eStr , e )) } for i := range rmIds { r, e := mm.room( rmIds[i] ) if e != nil { return os.NewError( fmt.Sprint(eStr , e )) } for _, j := range r.exits { if j == rmId || j == -rmId { return nil } } } mm.removeRegionExit( reg, rmId ) return nil } func (mm *MudMap) ExitInfo( rmId int64, exitStr string ) ( dest int64, hidden, trigger bool, cost int, e os.Error ){ if strings.HasPrefix( exitStr, "T:" ) { exitStr = exitStr[2:] } k, dest, b := mm.exitData( rmId, exitStr ) if !b { e = os.NewError( "MudMap.ExitInfo error: could not find exit." ) dest = UNKN_DEST return } _, dest, hidden, trigger, cost = splitExitInfo( k, dest ) return } func splitExitInfo( key string, val int64 ) (cmd string, dest int64, hidden, trigger bool, cost int){ dest = val cost = 1 switch { case dest < 0 : trigger = true splits := strings.SplitN( key[1:], ".", 2 ) cost, _ = strconv.Atoi( splits[ 0 ] ) dest *= -1 cmd = splits[ 1 ] case strings.HasPrefix( key, "." ) : hidden = true cmd = key[1:] default : cmd = key } return } func (mm *MudMap) exitData( rmId int64, regOrCmd string ) (k string, v int64, found bool) { r, e := mm.room( rmId ) if e != nil { return "", 0, false } if v, b := r.exits[regOrCmd]; b { return regOrCmd, v, b } for k, v := range r.exits { if !strings.HasPrefix( k, "." ) {continue} if v < 0 { if regOrCmd == strings.SplitN( k[1:], ".", 2 )[1] { return k, v, true } }else{ if regOrCmd == k[1:] { return k, v, true } } } return "", 0, false } func (mm *MudMap) Exits( rmId int64 ) (cmd []string, dest []int64, hid, trig []bool, cost []int, e os.Error) { r, e := mm.room( rmId ) if e != nil { e = os.NewError( "MudMap.Exits error getting room"+ e.String()) return } cmd = make( []string, len(r.exits) ) dest = make( []int64, len(r.exits) ) hid = make( []bool, len(r.exits) ) trig = make( []bool, len(r.exits) ) cost = make( []int, len(r.exits) ) i := 0 for k, v := range r.exits { cmd[i], dest[i], hid[i], trig[i], cost[i] = splitExitInfo(k, v) i++ } return } func (mm *MudMap) DelExit( rmId int64, cmd string ) (e os.Error) { k, v, b := mm.exitData( rmId, cmd ) if !b { return os.NewError( "MudMap.DelExit could not find exit" ) } rm, e := mm.room( rmId ) if e != nil { return os.NewError( "MudMap.DelExit "+e.String() ) } mm.rmIndex.RemoveRoom( rm ) rm.exits[ k ] = 0, false mm.bin.Store( rm ) mm.rmIndex.RegisterRoom( rm ) if v < 0 { v = -v } if v == UNKN_DEST { return } // check & deal with if it was a region exit r1 := rm.regionId rm2, e := mm.room( v ) if e != nil { return os.NewError( "MudMap.DelExit "+e.String() ) } r2 := rm2.regionId if r1 != r2 { e = mm.checkRegionExit( r1, rm2.id ) if e != nil {return os.NewError( "MudMap.DelExit "+e.String()) } } else { // if r1 != r2, no internal paths changed. r1 is still valid // add region to modified mm.alteredRegions[ r1 ] = true } return nil } func (mm *MudMap) AddExit( rmId int64, cmd string, hidden, trigger bool ) os.Error { if _, _, b := mm.exitData( rmId, cmd ); b { return os.NewError( "MudMap.AddExit: Exit already exists." ) } r, e := mm.room( rmId ) if e != nil { return os.NewError( "MudMap.AddExit: "+e.String() ) } switch { case trigger : r.exits[ ".1."+cmd ] = -UNKN_DEST case hidden : r.exits[ "."+cmd ] = UNKN_DEST default : mm.rmIndex.RemoveRoom( r ) r.exits[ cmd ] = UNKN_DEST mm.rmIndex.RegisterRoom( r ) } return mm.bin.Store( r ) } // set cost = 0 to leave it as is. // set dest = 0 to leave it as is. func (mm *MudMap) SetExitInfo( rmId int64, cmd string, dest int64, cost int ) os.Error { eStr := "MudMap.SetExitInfo: " var k string var v int64 var b bool if k, v, b = mm.exitData( rmId, cmd ); !b { return os.NewError( eStr+"No such exit." ) } oCmd, oDest, hid, trig, oCost := splitExitInfo( k, v ) if oCmd != cmd { return os.NewError( eStr+"old and new cmd mismatch!" ) } if dest == 0 { dest = oDest } if oDest != UNKN_DEST && oDest != dest { e := mm.DelExit( rmId, cmd ) if e != nil { return os.NewError( eStr+e.String() ) } e = mm.AddExit( rmId, cmd, hid, trig ) if e != nil { return os.NewError( eStr+e.String() ) } } if !trig && cost > 1 { return os.NewError( eStr+"Only triggers may have cost > 1." ) } if cost < 0 { return os.NewError( eStr+"Cost may not be negative." ) } r, e := mm.room( rmId ) if e != nil { return os.NewError(eStr+"Room not found. "+e.String()) } var dr *Room if dest != UNKN_DEST { dr, e = mm.room( dest ) if e != nil { return os.NewError(eStr+"Dest not found. "+e.String()) } } newVal := dest newKey := k switch{ case trig && oCost != cost : // if changing cost, the key changes. r.exits[ k ] = 0, false newKey = fmt.Sprint(".",cost,".",cmd) newVal = -dest case trig && oCost == cost : newVal = -dest case hid : default : } r.exits[ newKey ] = newVal mm.bin.Store( r ) if dest != UNKN_DEST { if dr.regionId != r.regionId { e = mm.addRegionExit(mm.regionsById[r.regionId],dest) if e != nil { return os.NewError(eStr+e.String()) } e=mm.addRegionEntrance(mm.regionsById[dr.regionId],dest) if e != nil { return os.NewError(eStr+e.String()) } } else { mm.alteredRegions[ r.regionId ] = true } } return nil } // getpath <originid> [destinationid] // FULL {path} || PARTIAL {path} || FAIL {reason} func (mm *MudMap) Path( rmId, destId int64 ) ( p *Path, e os.Error ) { return mm.path( rmId, destId ) } // tags // (tagdesc\(tagId\))* || FAIL {reason} func (mm *MudMap) Tags() ( tags []string ) { tags = make( []string, len( mm.tagsByName ) ) i := 0 for k, _ := range mm.tagsByName { tags[i] = k i++ } sort.Strings( tags ) return tags } // RoomTags // (tagdesc\(tagId\))* || FAIL {reason} func (mm *MudMap) RoomTags( rmId int64 ) ( tags []string, e os.Error ) { r, e := mm.room( rmId ) if !r.anomalous { return make( []string, 0 ), nil } tags = make( []string, 0, len( r.anomalyIds ) ) for i := range r.anomalyIds { a, e := mm.anomaly( r.anomalyIds[ i ] ) if e != nil { return nil, e } if a.atype == TAG { t := mm.tagsById[a.subId] tags = append( tags, t.desc ) continue } } return tags, nil } func (mm *MudMap) CreateRoomTag( tag string ) ( e os.Error ) { var t *Tag if mm.tagsByName[tag] != nil { return os.NewError("Tag "+tag+" already exists!") } t, e = newTag( mm.bin ) if e != nil { return e } t.desc = tag a, e := newAnomaly( mm.bin ) if e != nil { return e } a.atype = TAG a.subId = t.id mm.bin.Store( a ) t.anomalyId = a.id mm.bin.Store( t ) mm.tagsById[ t.id ] = t mm.tagsByName[ tag ] = t return nil } // addTag <roomId> [tagId] // SUCCESS || FAIL {reason} func (mm *MudMap) AddRoomTag( rmId int64, tag string ) ( e os.Error ) { t := mm.tagsByName[ tag ] if t == nil { return os.NewError("Not a valid tag!") } if t.rooms.Contains( rmId ) { return nil } t.rooms.Add( rmId ) mm.bin.Store( t ) r, e := mm.room( rmId ) aid := t.anomalyId r.anomalous = true if r.anomalyIds == nil { r.anomalyIds = make( []int64, 0, 1 ) } r.anomalyIds = append( r.anomalyIds, aid ) return mm.bin.Store( r ) } // removeTag <roomId> [tagId] // SUCCESS || FAIL {reason} func (mm *MudMap) RemRoomTag( rmId int64, tag string ) ( e os.Error ) { t := mm.tagsByName[ tag ] if t == nil { return os.NewError("Not a valid tag!") } t.rooms.Remove( rmId ) mm.bin.Store( t ) aid := t.anomalyId r, e := mm.room( rmId ) if e != nil { return e } if !r.anomalous { return nil } if r.anomalyIds == nil { r.anomalous = false mm.bin.Store( r ) return nil } for i := range r.anomalyIds { if r.anomalyIds[i] == aid { r.anomalyIds[i] = r.anomalyIds[ len(r.anomalyIds)-1 ] r.anomalyIds = r.anomalyIds[:len(r.anomalyIds)-1] mm.bin.Store( r ) return nil } } return nil } // taggedRooms [tagId] // (roomId)* || FAIL {reason} func (mm *MudMap) TaggedRms( tag string ) ( ids *tools.SI64Set, e os.Error ) { t := mm.tagsByName[ tag ] if t == nil { return nil, os.NewError("Not a valid tag!") } return t.rooms.Clone(), nil } func (mm *MudMap) DeleteTag( tag string ) ( e os.Error ) { t := mm.tagsByName[ tag ] if t == nil { return os.NewError("Not a valid tag!") } ids := t.rooms.Values() for i := range ids { mm.RemRoomTag( ids[i], tag ) } return mm.bin.Delete( t.id ) } func (mm *MudMap) NameRoom( rId int64, name string ) ( e os.Error ) { _, b := mm.namedRooms[ name ] if b { return os.NewError( "Name \""+name+"\" already in use." ) } nr := new ( NamedRoom ) nr.SetId( mm.bin.MaxId() + 1 ) nr.name = name nr.roomId = rId e = mm.bin.Store( nr ) if e != nil { return e } mm.namedRooms[ name ] = nr return nil } func (mm *MudMap) NamedRoomId( name string ) ( id int64, e os.Error ) { nr, b := mm.namedRooms[ name ] if !b { return 0, os.NewError( "No room named \""+name+"\"." ) } return nr.roomId, nil } func (mm *MudMap) UnnameRoom( name string ) ( e os.Error ) { nr, b := mm.namedRooms[ name ] if !b { return os.NewError( "No room named \""+name+"\"." ) } mm.namedRooms[ name ] = nil, false return mm.bin.Delete( nr.id ) } func (mm *MudMap) ListNamedRooms() ( names []string ) { names = make( []string, 0, len( mm.namedRooms ) ) for k, _ := range mm.namedRooms { names = append( names, k ) } sort.Strings( names ) return names } func (mm *MudMap) SetRoomCacheSize( size int ) { mm.rmc.setSize( size ) } func (mm *MudMap) RoomCacheSize() ( size int ) { return mm.rmc.size } // internal get room gets the cached room if available, otherwise hits // the bin. func (mm *MudMap) room( rId int64 ) ( r *Room, e os.Error ) { r = mm.rmc.room( rId ) if r != nil { return r, nil } if mm.bin.TypeOfId( rId ) != ROOM_HASH { s:=fmt.Sprint("MudMap.room error: ",rId," is not a Room id." ) return nil, os.NewError( s ) } r = new ( Room ) e = mm.bin.Load( rId, r ) if e != nil { return nil, e } mm.rmc.add( r ) return r, nil } // MARK need to add ability to put notes on rooms. type roomCache struct { size int id2e map[int64] *list.Element lst *list.List } func (rc *roomCache) room( id int64 ) (r *Room) { e := rc.id2e[ id ] if e == nil { return nil } r = (e.Value).(*Room) rc.lst.MoveToFront( e ) return r } func (rc *roomCache) add( r *Room ) { e := rc.lst.PushFront( r ) rc.id2e[ r.id ] = e rc.trimSize() } func (rc *roomCache) remove( id int64 ) { e := rc.id2e[ id ] rc.lst.Remove( e ) rc.id2e[ id ] = nil, false } func (rc *roomCache) trimSize() { for i := rc.lst.Len(); i > rc.size; i-- { e := rc.lst.Back() r := e.Value.(*Room) rc.id2e[r.id] = nil, false rc.lst.Remove( e ) } } func (rc *roomCache) setSize( newSize int ) { rc.size = newSize rc.trimSize() } // beyond this point lies the cleaning crew. func (mm *MudMap) CleanData() (e os.Error) { mm.bin.Commit() mm.rmIndex = new( RoomFinder ) mm.strIndex = nil mm.regionsById = make( map[int64] *Region, len(mm.regionsById) ) mm.ridsByName = nil mm.alteredRegions = nil mm.tagsById = nil mm.tagsByName = nil mm.namedRooms = make( map[string] *NamedRoom, len(mm.namedRooms) ) oldRmcSize := mm.rmc.size mm.rmc = nil bfMap[ mm.bin ] = nil, false storedPStringIds := mm.bin.IdsOfType( PSTRING_HASH ) duplicatePStrings := make(map[int64] bool, 10 ) hashedPStringMap := make(map[int32] int64, 10 ) referencedPStringIds := make(map[int64] bool, len(storedPStringIds) ) ids := mm.bin.IdsOfType( REGION_HASH ) for i := range ids { r := new( Region ) e = mm.bin.Load( ids[i], r ) if e != nil { return e } r.entrances = make( []int64, 0 ) r.exits = make( []int64, 0 ) r.paths = make( [][]*IPath, 0 ) e = mm.bin.Store( r ) if e != nil { return e } mm.regionsById[ ids[i] ] = r } ids = mm.bin.IdsOfType( ROOM_HASH ) for i := range ids { rm := new( Room ) e = mm.bin.Load( ids[i], rm ) if e != nil { return e } if _, b := mm.regionsById[ rm.regionId ]; !b { mm.bin.Delete( rm.id ) rm = nil continue } for k, v := range rm.exits { if v == UNKN_DEST || v == -UNKN_DEST { continue } if mm.bin.TypeOfId( v ) != ROOM_HASH { if strings.HasPrefix( k, "." ) { rm.exits[ k ] = 0, false } else { rm.exits[ k ] = UNKN_DEST } } } keys := make( []string, 0, len( rm.exits ) ) for k, _ := range rm.exits { keys = append( keys, k ) } for i := len(keys)-1; i >= 0; i-- { for j := i-1; j >= 0; j-- { // don't keep the long version of common alii switch { case keys[i]=="n" && keys[j]=="north" || keys[j]=="n" && keys[i]=="north": rm.exits["north"] = 0, false case keys[i]=="s" && keys[j]=="south" || keys[j]=="s" && keys[i]=="south": rm.exits["south"] = 0, false case keys[i]=="e" && keys[j]=="east" || keys[j]=="e" && keys[i]=="east": rm.exits["east"] = 0, false case keys[i]=="w" && keys[j]=="west" || keys[j]=="w" && keys[i]=="west": rm.exits["west"] = 0, false case keys[i]=="ne" && keys[j]=="northeast" || keys[j]=="ne" && keys[i]=="northeast": rm.exits["northeast"] = 0, false case keys[i]=="se" && keys[j]=="southeast" || keys[j]=="se" && keys[i]=="southeast": rm.exits["southeast"] = 0, false case keys[i]=="sw" && keys[j]=="southwest" || keys[j]=="sw" && keys[i]=="southwest": rm.exits["southwest"] = 0, false case keys[i]=="nw" && keys[j]=="northwest" || keys[j]=="nw" && keys[i]=="northwest": rm.exits["northwest"] = 0, false case keys[i]=="u" && keys[j]=="up" || keys[j]=="u" && keys[i]=="up": rm.exits["up"] = 0, false case keys[i]=="d" && keys[j]=="down" || keys[j]=="d" && keys[i]=="down": rm.exits["down"] = 0, false } // if two triggers are the same, remove // the lower cost one. if rm.exits[keys[i]]<0 && rm.exits[keys[j]]<0 { si := strings.SplitN(keys[i][1:],".",2) sj := strings.SplitN(keys[j][1:],".",2) trigi := si[1] trigj := sj[1] if trigi == trigj { ci, e := strconv.Atoi(si[0]) if e != nil { return e } cj, e := strconv.Atoi(sj[0]) if e != nil { return e } if ci < cj { rm.exits[keys[i]]=0,false }else{ rm.exits[keys[j]]=0,false } } } } } // now that anything that will be removed has, check regions for _, v := range rm.exits { if v < 0 { v *= -1 } if v == UNKN_DEST { continue } dr := new ( Room ) e = mm.bin.Load( v, dr ) if e != nil { return e } if dr.regionId != rm.regionId { // it's okay if we duplicate these in the // arrays, since the first thing repathRegion // does is scan and remove duplicates. r1 := mm.regionsById[ rm.regionId ] r2 := mm.regionsById[ dr.regionId ] r1.exits = append( r1.exits, v ) r2.entrances = append( r2.entrances, v ) } } // now that anything that will be removed has, check regions if rm.anomalous { if rm.anomalyIds == nil || len( rm.anomalyIds ) == 0 { rm.anomalous = false } } if rm.anomalyIds != nil { for i := range rm.anomalyIds { a := new( Anomaly ) e = mm.bin.Load( rm.anomalyIds[i], a ) if e != nil { return e } switch a.atype { case TAG : t := new( Tag ) if mm.bin.TypeOfId( a.subId ) != TAG_HASH { e = mm.bin.Delete( a.id ) if e != nil { return e } rm.anomalyIds[i] = rm.anomalyIds[len(rm.anomalyIds)-1] rm.anomalyIds = rm.anomalyIds[:len(rm.anomalyIds)-1] break } e = mm.bin.Load( a.subId, t ) if e != nil { return e } if t.anomalyId != a.id { e = mm.bin.Delete( a.id ) if e != nil { return e } a = new( Anomaly ) e = mm.bin.Load( t.anomalyId, a ) if e != nil { return e } if a.subId == t.id { rm.anomalyIds[i] = a.id } else { rm.anomalyIds[i] = rm.anomalyIds[len(rm.anomalyIds)-1] rm.anomalyIds = rm.anomalyIds[:len(rm.anomalyIds)-1] } } if !t.rooms.Contains( rm.id ) { t.rooms.Add( rm.id ) e = mm.bin.Store( t ) if e != nil { return e } } case NOTE : // not implemented yet case MOBILE_EXIT : // not implemented yet default : e = mm.bin.Delete( a.id ) if e != nil { return e } rm.anomalyIds[i] = rm.anomalyIds[len(rm.anomalyIds)-1] rm.anomalyIds = rm.anomalyIds[:len(rm.anomalyIds)-1] } } if len( rm.anomalyIds ) > 0 { rm.anomalous = true } else { rm.anomalous = false } } if mm.bin.TypeOfId( rm.shortDescId ) != PSTRING_HASH { rm.shortDescId = 0 rm.sDesc = nil } else { ps1 := new( PString ) e = mm.bin.Load( rm.shortDescId, ps1 ) if e != nil { return e } hash := tools.Hash( ps1.val ) hashedId, b := hashedPStringMap[ hash ] if b && hashedId != ps1.id { ps2 := new( PString ) e = mm.bin.Load( hashedId, ps2 ) if e != nil { return e } if ps2.val == ps1.val { // duplicate PString. Delete it once all rooms are // scanned (or it could mess up a later room). duplicatePStrings[ ps1.id ] = true if e != nil { return e } rm.shortDescId = ps2.id } } hashedPStringMap[ hash ] = rm.shortDescId } referencedPStringIds[ rm.shortDescId ] = true if mm.bin.TypeOfId( rm.longDescId ) != PSTRING_HASH { rm.longDescId = 0 rm.lDesc = nil } else { ps1 := new( PString ) e = mm.bin.Load( rm.longDescId, ps1 ) if e != nil { return e } hash := tools.Hash( ps1.val ) hashedId, b := hashedPStringMap[ hash ] if b && hashedId != ps1.id { ps2 := new( PString ) e = mm.bin.Load( hashedId, ps2 ) if e != nil { return e } if ps2.val == ps1.val { // duplicate PString. Delete it once all rooms are // scanned (or it could mess up a later room). duplicatePStrings[ ps1.id ] = true if e != nil { return e } rm.longDescId = ps2.id } } hashedPStringMap[ hash ] = rm.longDescId } referencedPStringIds[ rm.longDescId ] = true mm.rmIndex.RegisterRoom( rm ) mm.bin.Store( rm ) } for k, _ := range duplicatePStrings { e = mm.bin.Delete( k ) if e != nil { return e } } _, e = mm.riFile.Seek( 0, 0 ) if e != nil { return e } _, e = mm.riFile.Write( mm.rmIndex.Write() ) if e != nil { return e } // now that the rooms are all cleaned up, which also // added all the region entrance and exits, we repath // the regions // first, we need to make a new roomCache, which we nilled at the top mm.rmc = new( roomCache ) mm.rmc.size = oldRmcSize mm.rmc.id2e = make( map[int64] *list.Element, mm.rmc.size ) mm.rmc.lst = list.New() for id, r := range mm.regionsById { e = mm.repathRegion( id ) if e != nil { return e } e = mm.bin.Store( r ) if e != nil { return e } } ids = mm.bin.IdsOfType( TAG_HASH ) for i := range ids { t := new( Tag ) e = mm.bin.Load( ids[i], t ) if e != nil { return e } rids := t.rooms.Values() G: for i := range rids { if mm.bin.TypeOfId( rids[i] ) != ROOM_HASH { t.rooms.Remove( rids[i] ) continue } rm := new( Room ) e = mm.bin.Load( rids[i], rm ) if e != nil { return e } if rm.anomalous { for j := range rm.anomalyIds { if rm.anomalyIds[j] == t.anomalyId { continue G } } } t.rooms.Remove( rids[i] ) } mm.bin.Store( t ) } ids = mm.bin.IdsOfType( ANOMALY_HASH ) for i := range ids { a := new( Anomaly ) e = mm.bin.Load( ids[i], a ) if e != nil { return e } switch a.atype{ case TAG : if mm.bin.TypeOfId( a.subId ) != TAG_HASH { mm.bin.Delete( a.id ) continue } t := new( Tag ) e = mm.bin.Load( a.subId, t ) if e != nil { return e } if t.anomalyId != a.id { mm.bin.Delete( a.id ) if e != nil { return e } a = new( Anomaly ) e = mm.bin.Load( t.anomalyId, a ) if e != nil { return e } if a.subId != t.id { mm.bin.Delete( t.id ) if e != nil { return e } } continue } case NOTE : // not yet defined case MOBILE_EXIT : // not yet defined default : // not yet defined } } ids = mm.bin.IdsOfType( NAMED_ROOM_HASH ) H: for i := range ids { nr := new( NamedRoom ) e = mm.bin.Load( ids[i], nr ) if e != nil { return e } if mm.bin.TypeOfId( nr.roomId ) != ROOM_HASH { mm.bin.Delete( nr.id ) continue } nr2, b := mm.namedRooms[ nr.name ] for b { if nr2.roomId == nr.roomId { e = mm.bin.Delete( nr.id ) if e != nil { return e } continue H } m, e := regexp.MatchString( "\\([0-9]+\\)$", nr.name ) if e != nil { return e } if m { j := strings.LastIndex( nr.name, "(" ) nri, e := strconv.Atoi( nr.name[j+1:len(nr.name)-1] ) if e != nil { return e } nr.name = fmt.Sprint(nr.name[:j+1],nri+1,")") } else { nr.name = nr.name + "(2)" } nr2, b = mm.namedRooms[ nr.name ] } e = mm.bin.Store( nr ) if e != nil { return e } } // check PStrings for orphans and remove them for i := range storedPStringIds { if !referencedPStringIds[storedPStringIds[i]] { e = mm.bin.Delete( storedPStringIds[i] ) if e != nil { return e } } } // now load it from the DB mm.strIndex = getPStringFinder( mm.bin ) _, e = mm.siFile.Seek( 0, 0 ) if e != nil { return e } _, e = mm.siFile.Write( mm.strIndex.Write() ) if e != nil { return e } e = mm.bin.CommitAndPack() if e != nil { return e } e = mm.loadIndexes() if e != nil { return e } mm.alteredRegions = make( map [int64] bool, 5 ) // for next version: // break it into subfuncs // check for orphaned Anomalies (no room or tag references) // check for orphaned Notes return nil }
true
d880e7d35b89249ea71f5a412c1d3b290d4f490b
Go
RachidP/udemyTraining
/Golang/Golang base_course/exercise/channel/channe1/cha1.go
UTF-8
282
3.53125
4
[]
no_license
[]
no_license
package main import "fmt" func main() { for index := range fact(10) { fmt.Println(index) } } func fact(num int) chan int { c := make(chan int) go func() { v := 1 if num > 1 { for i := 1; i <= num; i++ { v *= i } c <- v close(c) } }() return c }
true
f2bf2996f60963ee8def29c0ab18c11b9c3ca696
Go
toru/cellar
/config/validation.go
UTF-8
905
3.328125
3
[]
no_license
[]
no_license
package config import ( "strings" ) // configValidationError is a custom error type for representing // validation related errors. type configValidationError struct { InvalidFields map[string]string // Maps a field to its descriptive error message } // NewConfigValidationError returns a new configValidationError. func NewConfigValidationError() *configValidationError { err := configValidationError{} err.InvalidFields = make(map[string]string) return &err } // Error returns a summarized context of the validation error. // It is also needed to implement the Go "error" interface. func (cve *configValidationError) Error() string { if len(cve.InvalidFields) == 0 { return "" } errStr := "Invalid configuration found in: " keys := make([]string, 0, len(cve.InvalidFields)) for key := range cve.InvalidFields { keys = append(keys, key) } return errStr + strings.Join(keys, ", ") }
true
0a3f055b5982651b7ccbb42109aa8e43f125c27a
Go
cybybchen/littletest
/interface/intertointer/main.go
UTF-8
543
3.390625
3
[]
no_license
[]
no_license
package main import "fmt" type inter1 interface { do() } type inter2 interface { send() do() } type inter struct { } type test struct { in inter } type test1 struct { t test } func (this *inter) send() { } func (this *inter) do() { fmt.Println("inter") } func main() { //in := &inter{} //send2(in) test := &test1{} fmt.Println(test.t) //test.t.in.a = 10 fmt.Println(test.t.in) } func send1(in1 inter1) { fmt.Println("1haha") in := in1.(*inter) in.do() } func send2(in2 inter2) { fmt.Println("2haha") send1(in2) }
true
3577b1ef72c1320a254c3617f01c7a69ecb7cb55
Go
GSamuel/GoGame
/server/netlistener.go
UTF-8
1,179
3.125
3
[]
no_license
[]
no_license
package server import ( "fmt" "net" ) type Listener interface { Listen() error Close() Packets() chan *RawPacket } type UDPListener struct { address string udpaddress *net.UDPAddr connection *net.UDPConn packets chan *RawPacket } func (u *UDPListener) Packets() chan *RawPacket { return u.packets } func (u *UDPListener) Listen() error { udpaddress, err := net.ResolveUDPAddr("udp", u.address) if err != nil { return err } u.udpaddress = udpaddress connection, err := net.ListenUDP("udp", udpaddress) if err != nil { return err } u.connection = connection go u.listen() return nil } func (u *UDPListener) listen() { buf := make([]byte, 1024) //hardcoded byte amount for { n, addr, err := u.connection.ReadFromUDP(buf) if err != nil { fmt.Println("Error: ", err) } packet := NewRawPacket(addr.String(), buf[0:n]) fmt.Println(packet) u.packets <- packet //gameServer.ResolveConnection(NewConnection(addr.String())) } } func (u *UDPListener) Close() { u.connection.Close() } type TcpListener struct { } func NewUDPListener(addr string) Listener { return &UDPListener{addr, nil, nil, make(chan *RawPacket, 5)} }
true
48c29784f3bb695ec70cbbf67caec13c1304ddaf
Go
sour-is/go-profile
/internal/model/user.go
UTF-8
2,873
2.8125
3
[]
no_license
[]
no_license
package model import ( "database/sql" sq "gopkg.in/Masterminds/squirrel.v1" "sour.is/x/toolbox/dbm" "sour.is/x/toolbox/log" ) type UserRole struct { User string Aspect string Role string } func HasUserRoleTx(tx *dbm.Tx, aspect, user string, role ...string) (bool, error) { var ok int var err error err = sq.Select("count(*)"). From("user_roles"). Where(sq.Eq{ "`aspect`": []string{"*", aspect}, "`user`": user, "`role`": role}). RunWith(tx.Tx).QueryRow().Scan(&ok) if err != nil { log.Warning(err.Error()) return false, err } log.Debugf("Count: %d, %+v", ok, role) return ok > 0, err } func HasUserRole(aspect, ident string, role ...string) (ok bool, err error) { err = dbm.Transaction(func(tx *dbm.Tx) (err error) { // has hash role? ok, err = HasUserRoleTx( tx, aspect, ident, role...) return }) return } func GetUserRoles(tx *dbm.Tx, aspect, user string) (lis []UserRole, err error) { var rows *sql.Rows rows, err = sq.Select("DISTINCT `role`"). From("user_roles"). Where(sq.Eq{"`aspect`": []string{"*", aspect}, "`user`": user}). RunWith(tx.Tx).Query() if err != nil { log.Debug(err) return } defer rows.Close() for rows.Next() { var r UserRole if err = rows.Scan(&r.Role); err != nil { return } lis = append(lis, r) } return } func GetUserRoleList(tx *dbm.Tx, aspect, user string) (lis []string, err error) { lis = make([]string, 0, 1) var roles []UserRole if roles, err = GetUserRoles(tx, aspect, user); err != nil { return } for _, r := range roles { lis = append(lis, r.Role) } return } type UserGroup struct { User string Aspect string Group string } func HasUserGroup(tx *dbm.Tx, aspect, user string, role ...string) (bool, error) { var ok int var err error err = sq.Select("count(*)"). From("group_users"). Where(sq.Eq{ "`aspect`": []string{"*", aspect}, "`user`": user, "`group`": role}). RunWith(tx.Tx).QueryRow().Scan(&ok) if err != nil { log.Warning(err.Error()) return false, err } log.Debugf("Count: %d, %+v", ok, role) return ok > 0, err } func GetUserGroups(tx *dbm.Tx, aspect, user string) (lis []UserGroup, err error) { var rows *sql.Rows rows, err = sq.Select("DISTINCT `group`"). From("group_users"). Where(sq.Eq{"`aspect`": []string{"*", aspect}, "`user`": user}). RunWith(tx.Tx).Query() if err != nil { log.Debug(err) return } defer rows.Close() for rows.Next() { var r UserGroup if err = rows.Scan(&r.Group); err != nil { return } lis = append(lis, r) } return } func GetUserGroupList(tx *dbm.Tx, aspect, user string) (lis []string, err error) { lis = make([]string, 0, 1) var groups []UserGroup if groups, err = GetUserGroups(tx, aspect, user); err != nil { return } for _, r := range groups { lis = append(lis, r.Group) } return }
true
fa8fae0c04f7519d32b97d2a23c5c9c25233900b
Go
ramadani/clinci
/helper.go
UTF-8
1,207
2.6875
3
[ "MIT" ]
permissive
[ "MIT" ]
permissive
package clinci type defaultListener struct { queuer Queuer consumer Consumer task Task } type defaultQueuer struct { name string } type defaultConsumer struct{} func CreateFromDefaultListener(task Task) Listener { return &defaultListener{ queuer: DefaultQueuer(), consumer: DefaultConsumer(), task: task, } } func DefaultQueuer() Queuer { return &defaultQueuer{} } func DefaultConsumer() Consumer { return &defaultConsumer{} } func (l *defaultListener) Queuer() Queuer { return l.queuer } func (l *defaultListener) Consumer() Consumer { return l.consumer } func (l *defaultListener) Key() string { return l.task.Key() } func (l *defaultListener) Handle(data []byte) error { return l.task.Handle(data) } func (q *defaultQueuer) SetName(name string) { q.name = name } func (q *defaultQueuer) Name() string { return q.name } func (q *defaultQueuer) Config() *Config { return &Config{ Durable: false, AutoDelete: false, NoWait: false, Args: nil, } } func (c *defaultConsumer) Name() string { return "" } func (c *defaultConsumer) Config() *Config { return &Config{ AutoAck: true, NoLocal: false, NoWait: false, Args: nil, } }
true
3985204f5f24d95deee8bba0ba196584cb23bd79
Go
aquasecurity/trivy
/pkg/licensing/expression/lexer.go
UTF-8
2,381
3.21875
3
[ "Apache-2.0" ]
permissive
[ "Apache-2.0" ]
permissive
package expression import ( "bufio" "errors" "io" "strings" "unicode" "unicode/utf8" multierror "github.com/hashicorp/go-multierror" ) type Lexer struct { s *bufio.Scanner result Expression errs error } func NewLexer(reader io.Reader) *Lexer { scanner := bufio.NewScanner(reader) scanner.Split(func(data []byte, atEOF bool) (advance int, token []byte, err error) { // The implementation references bufio.ScanWords() // Skip leading spaces. start := 0 for width := 0; start < len(data); start += width { var r rune r, width = utf8.DecodeRune(data[start:]) if !unicode.IsSpace(r) { break } } // Process terminal symbols if len(data) > start && (data[start] == '(' || data[start] == ')' || data[start] == '+') { return start + 1, data[start : start+1], nil } // Scan until space or token, marking end of word. for width, i := 0, start; i < len(data); i += width { var r rune r, width = utf8.DecodeRune(data[i:]) switch r { case '(', ')': return i, data[start:i], nil case '+': // Peek the next rune if len(data) > i+width { adv := i i += width r, width = utf8.DecodeRune(data[i:]) if unicode.IsSpace(r) || r == '(' || r == ')' { return adv, data[start:adv], nil } } else if atEOF { return i, data[start:i], nil } default: if unicode.IsSpace(r) { return i + width, data[start:i], nil } } } // If we're at EOF, we have a final, non-empty, non-terminated word. Return it. if atEOF && len(data) > start { return len(data), data[start:], nil } // Request more data. return start, nil, nil }) return &Lexer{ s: scanner, } } func (l *Lexer) Lex(lval *yySymType) int { if !l.s.Scan() { return 0 } var token int literal := l.s.Text() switch literal { case "(", ")", "+": token = int(literal[0]) default: token = lookup(literal) } lval.token = Token{ token: token, literal: literal, } if err := l.s.Err(); err != nil { l.errs = multierror.Append(l.errs, l.s.Err()) } return lval.token.token } func (l *Lexer) Error(e string) { l.errs = multierror.Append(l.errs, errors.New(e)) } func (l *Lexer) Err() error { return l.errs } func lookup(t string) int { t = strings.ToUpper(t) for i, name := range yyToknames { if t == name { return yyPrivate + (i - 1) } } return IDENT }
true
71c4c35a343a5500c4d5b6dec8258389b0dd8919
Go
webrpc/webrpc
/gen/funcmap_types.go
UTF-8
2,549
2.984375
3
[ "MIT" ]
permissive
[ "MIT" ]
permissive
package gen import ( "fmt" "strings" "github.com/webrpc/webrpc/schema" ) // Returns true if given type is core type. func isCoreType(v interface{}) bool { _, isCoreType := schema.CoreTypeFromString[toString(v)] return isCoreType } // Returns true if given type is struct. func isStructType(v interface{}) (bool, error) { switch t := v.(type) { case schema.Type: return t.Kind == "struct", nil case *schema.Type: return t.Kind == "struct", nil case schema.VarType: return t.Type == schema.T_Struct, nil case *schema.VarType: if t != nil { return t.Type == schema.T_Struct, nil } return false, nil default: return false, fmt.Errorf("isStructType(): unexpected type %T: %+v", v, v) } } // Returns true if given type is enum. func isEnumType(v interface{}) (bool, error) { switch t := v.(type) { case schema.Type: return t.Kind == "enum", nil case *schema.Type: return t.Kind == "enum", nil case schema.VarType: return t.Struct.Type.Kind == "enum", nil case *schema.VarType: if t != nil { return t.Struct.Type.Kind == "enum", nil } return false, nil default: return false, fmt.Errorf("isEnumType(): unexpected type %T: %+v", v, v) } } // Returns true if given type is list (ie. `[]T`). func isListType(v interface{}) bool { return strings.HasPrefix(toString(v), "[]") } // Return true if given type is map (ie. map<T1,T2>). func isMapType(v interface{}) bool { key, value, found := stringsCut(toString(v), ",") return found && strings.HasPrefix(key, "map<") && strings.HasSuffix(value, ">") } // Returns given map's key type (ie. `T1` from `map<T1,T2>`) func mapKeyType(v interface{}) string { str := toString(v) key, value, found := stringsCut(str, ",") if !found || !strings.HasPrefix(key, "map<") || !strings.HasSuffix(value, ">") { panic(fmt.Errorf("mapKeyValue: expected map<Type1,Type2>, got %v", str)) } return strings.TrimPrefix(key, "map<") } // Returns given map's value type (ie. `T2` from `map<T1,T2>`) func mapValueType(v interface{}) string { str := toString(v) key, value, found := stringsCut(str, ",") if !found || !strings.HasPrefix(key, "map<") || !strings.HasSuffix(value, ">") { panic(fmt.Errorf("mapKeyValue: expected map<Type1,Type2>, got %v", str)) } return strings.TrimSuffix(value, ">") } // Returns list's element type (ie. `T` from `[]T`) func listElemType(v interface{}) string { str := toString(v) if !strings.HasPrefix(str, "[]") { panic(fmt.Errorf("listElemType: expected []Type, got %v", str)) } return strings.TrimPrefix(str, "[]") }
true
802b3adb8c0191dccc742abdb2f4bac645d98b00
Go
lin-sel/swabhaw
/go/src/golang-training/day4/06_method.go
UTF-8
415
3.765625
4
[]
no_license
[]
no_license
package main import "fmt" // Student details type Student struct { firstname, lastname string rollno int } func (stu *Student) modify() { stu.rollno = 201 } func (stu Student) modifyPointer() { stu.rollno = 301 } func main() { st := Student{"Nilesh", "Yadav", 100} fmt.Println(st) st.modifyPointer() fmt.Println("Without Refrence", st) st.modify() fmt.Println("With Reference", st) }
true
2e4b784c8911c4eba30e9e6bd620b7d3c1a6acb4
Go
krancorp/obsgradeavg
/obsgradeavg.go
UTF-8
4,866
2.609375
3
[ "WTFPL" ]
permissive
[ "WTFPL" ]
permissive
package main import ( "bufio" "bytes" "flag" "fmt" "net/http" "net/http/cookiejar" "net/url" "os" "strconv" "strings" "syscall" "github.com/PuerkitoBio/goquery" "github.com/djimenez/iconv-go" "golang.org/x/crypto/ssh/terminal" ) const obsURL = "https://obs.fbi.h-da.de/obs/" type module struct { name string avg float32 cp float32 } func main() { username := flag.String("username", "", "Your OBS username") password := flag.String("password", "", "Your OBS password") flag.Parse() if *username == "" { fmt.Print("Please enter your OBS username: ") reader := bufio.NewReader(os.Stdin) var err error *username, err = reader.ReadString('\n') if err != nil { fmt.Print("Failed to read username", err) os.Exit(1) } *username = strings.TrimSuffix(*username, "\n") } if *password == "" { fmt.Print("Please enter your OBS password: ") passwordBytes, err := terminal.ReadPassword(int(syscall.Stdin)) fmt.Println() if err != nil { fmt.Print("Failed to read password", err) os.Exit(1) } *password = string(passwordBytes) } fmt.Print("Logging in... ") cookieJar, _ := cookiejar.New(nil) client := &http.Client{ Jar: cookieJar, } if !login(client, *username, *password) { fmt.Println("failed") return } fmt.Println("success") fmt.Println("Gathering average grades per module") modules, err := parseModules(client) exitOnError(err) cpSum := float32(0) gradeSum := float32(0) for _, m := range modules { cpSum += m.cp gradeSum += float32(m.cp) * m.avg } fmt.Printf("The total average is %.2f at currently %.1f cp.\n", gradeSum/float32(cpSum), cpSum) } func login(client *http.Client, username string, password string) bool { res, err := client.Get(obsURL) exitOnError(err) doc, err := goquery.NewDocumentFromReader(res.Body) loginTan, _ := doc.Find("input[name=\"LoginTAN\"]").Attr("value") values := make(url.Values, 3) values.Add("username", username) values.Add("password", password) values.Add("LoginTAN", loginTan) res, err = client.PostForm(obsURL+"login.php?action=login", values) buf := new(bytes.Buffer) buf.ReadFrom(res.Body) return len(buf.String()) > 20000 } func parseModules(client *http.Client) (grades []module, err error) { grades = make([]module, 0) res, err := client.Get(obsURL + "index.php?action=noten") if err != nil { return } //convert charset to utf-8 utfBody, err := iconv.NewReader(res.Body, "windows-1252", "utf-8") if err != nil { return } doc, err := goquery.NewDocumentFromReader(utfBody) if err != nil { return } rows := doc.Find("#formAlleNoten tbody tr") rows.Each(func(i int, row *goquery.Selection) { if i == 0 || i == rows.Length()-1 || row.Children().Size() != 9 || row.Children().Eq(7).Children().Size() == 0 { return } grade, _ := strconv.ParseFloat(row.Children().Eq(6).Text(), 32) if grade == 5.0 { return } mu, _ := row.Children().Eq(4).Children().Eq(0).Attr("href") cp := getCPForModule(client, mu) if cp == 0 { return } moduleName := row.Children().Eq(3).Text() if strings.Contains(moduleName, "(PVL)") { return } fmt.Printf("Module '%v' (%.1f cp)...", moduleName, cp) statID, _ := row.Children().Eq(7).Children().Attr("href") statID = strings.TrimSuffix(strings.TrimPrefix(statID, "javascript:Statistik('"), "')") avg := calculateAvgGrade(client, statID) if avg == -1 { fmt.Println(" not enough module members.") return } fmt.Printf(" %.2f\n", avg) m := module{ name: moduleName, avg: avg, cp: cp, } grades = append(grades, m) }) return } func getCPForModule(client *http.Client, moduleLink string) float32 { res, err := client.Get(moduleLink) exitOnError(err) doc, err := goquery.NewDocumentFromReader(res.Body) exitOnError(err) cpt := doc.Find("#content table tbody").Children().Eq(6).Children().Eq(1).Text() cp, err := strconv.ParseFloat(strings.Replace(cpt, ",", ".", 1), 32) exitOnError(err) return float32(cp) } func calculateAvgGrade(client *http.Client, statID string) float32 { res, err := client.Get(obsURL + "index.php?action=Notenstatistik&statpar=" + statID) exitOnError(err) doc, err := goquery.NewDocumentFromReader(res.Body) exitOnError(err) gradeRows := doc.Find("span > span") if gradeRows.Length() == 0 { return -1 } gradesCnt := 0 gradesSum := float32(0.0) gradeRows.Each(func(i int, row *goquery.Selection) { description, exists := row.Attr("title") if exists { descParts := strings.Split(description, " <= ") newCnt, _ := strconv.Atoi(descParts[0]) g, _ := strconv.ParseFloat(descParts[1], 32) if g == 5 { return } gradesSum += float32(g) * float32(newCnt-gradesCnt) gradesCnt = newCnt } }) return gradesSum / float32(gradesCnt) } func exitOnError(err error) { if err != nil { fmt.Print("Fatal error", err) os.Exit(1) } }
true
ba1edcb28bd528bbe57f8650a8380afe4acdcd16
Go
alexanderbez/titan
/version/version.go
UTF-8
527
2.640625
3
[ "MIT" ]
permissive
[ "MIT" ]
permissive
package version import ( "fmt" "runtime" ) // Version defines the current application semantic version. const Version = "0.0.2" // GitCommit defines the application's Git short SHA-1 revision set during the // build. var GitCommit = "" // ClientVersion returns the application's full version string. func ClientVersion() string { if GitCommit != "" { return fmt.Sprintf("%s-%s+%s/%s", Version, GitCommit, runtime.GOOS, runtime.Version()) } return fmt.Sprintf("%s+%s/%s", Version, runtime.GOOS, runtime.Version()) }
true
ae03ae7ee064ce98675770189ae7be2a307cf804
Go
mgufrone/go-clean-arch
/domains/recipe/recipe.go
UTF-8
2,807
2.640625
3
[]
no_license
[]
no_license
package recipe import ( "context" "recipes/domains/shared" "recipes/domains/user" ) type Recipe struct { shared.Model Title string `json:"title"` Summary string `json:"summary"` Description string `json:"description"` User *user.User `json:"user"` Photos []*Photo `json:"photos"` Steps []*Step `json:"steps"` Ingredients []*Ingredient `json:"ingredients"` } type StatsRecipe struct { *Recipe ViewCount uint64 `json:"view_count"` LikeCount uint64 `json:"like_count"` } type IRecipeRepository interface { GetAll(ctx context.Context, limiter *shared.CommonLimiter, filters ...*Recipe) ([]*Recipe, *shared.CommonLimiter, error) Count(ctx context.Context, filters ...*Recipe) (int64, error) Create(ctx context.Context, recipe *Recipe) error Update(ctx context.Context, recipe *Recipe) error Delete(ctx context.Context, recipe *Recipe) error CreateBatch(ctx context.Context, recipes ...*Recipe) error DeleteBatch(ctx context.Context, recipes ...*Recipe) error } type IRecipeUseCase interface { GetAll(ctx context.Context, limiter *shared.CommonLimiter, filters ...*Recipe) ([]*StatsRecipe, *shared.CommonLimiter, error) GetByUser(ctx context.Context, limiter *shared.CommonLimiter, usr *user.User, filters ...*Recipe) ([]*StatsRecipe, *shared.CommonLimiter, error) Create(ctx context.Context, usr *user.User, recipe *Recipe) error Update(ctx context.Context, usr *user.User, recipe *Recipe) error Delete(ctx context.Context, usr *user.User, recipe *Recipe) error CreateBatch(ctx context.Context, usr *user.User, recipes ...*Recipe) error DeleteBatch(ctx context.Context, usr *user.User, recipes ...*Recipe) error Popular(ctx context.Context, usr *user.User, limiter *shared.CommonLimiter, filters ...*Recipe) ([]*StatsRecipe, *shared.CommonLimiter, error) Like(ctx context.Context, usr *user.User, recipe *Recipe) error Dislike(ctx context.Context, usr *user.User, recipe *Recipe) error View(ctx context.Context, usr *user.User, recipe *Recipe) error AddStep(ctx context.Context, usr *user.User, recipe *Recipe, step string) error UpdateStep(ctx context.Context, usr *user.User, recipe *Recipe, sequence int, step string) error RemoveStep(ctx context.Context, usr *user.User, recipe *Recipe, sequence int) error AddIngredient(ctx context.Context, usr *user.User, recipe *Recipe, ingredient *Ingredient) error UpdateIngredient(ctx context.Context, usr *user.User, recipe *Recipe, ingredient *Ingredient) error RemoveIngredient(ctx context.Context, usr *user.User, recipe *Recipe, sequence int) error AddPhoto(ctx context.Context, usr *user.User, recipe *Recipe, ingredient *Photo) error UpdatePhoto(ctx context.Context, usr *user.User, recipe *Recipe, ingredient *Photo) error RemovePhoto(ctx context.Context, usr *user.User, recipe *Recipe, sequence int) error }
true
e41ae6fa1ffe27561b9f80a500ba51581c0a262c
Go
Lxy417165709/utils
/array/array_test.go
UTF-8
2,031
3.515625
4
[]
no_license
[]
no_license
package array import ( "fmt" "testing" ) type Int int func (i Int) Greater(c Comparable) bool { j := c.(Int) return i > j } type String string func (i String) Greater(c Comparable) bool { j := c.(String) return i > j } func Test(t *testing.T) { fmt.Println(IsExistInSortedArray([]Comparable{ Int(1), Int(2), Int(3), }, Int(2))) fmt.Println(GetFirstGreaterIndex([]Comparable{ String("123"), String("456"), String("789"), }, String("456"))) fmt.Println(GetFirstGreaterOrEqualIndex([]Comparable{ String("123"), String("456"), String("789"), }, String("456"))) } func TestQuickSort(t *testing.T) { nums := []Comparable{ Int(1), Int(8), Int(2), Int(4), Int(8), Int(7), Int(6), Int(7), Int(89), Int(1), Int(98), Int(3), Int(18), Int(9), Int(3), Int(18), Int(-5), Int(123), } fmt.Println("Before sorting", nums) fmt.Println("IsSorted",isSorted(nums)) QuickSort(nums) fmt.Println("After sorting", nums) fmt.Println("IsSorted",isSorted(nums)) } func TestGetKthSmall(t *testing.T) { nums := []Comparable{ Int(1), Int(8), Int(2), Int(4), Int(8), Int(7), Int(6), Int(7), Int(89), Int(1), Int(98), Int(3), Int(18), Int(9), Int(3), Int(18), Int(-5), Int(123), } fmt.Printf("%dth small: %v\n", 1, GetKthSmall(nums, 1)) fmt.Printf("%dth small: %v\n", 5, GetKthSmall(nums, 5)) fmt.Printf("%dth small: %v\n", 6, GetKthSmall(nums, 6)) fmt.Printf("%dth small: %v\n", 10, GetKthSmall(nums, 10)) fmt.Printf("%dth small: %v\n", 15, GetKthSmall(nums, 15)) fmt.Printf("%dth small: %v\n", 16, GetKthSmall(nums, 16)) fmt.Printf("%dth small: %v\n", 20, GetKthSmall(nums, 20)) } func TestPermutation(t *testing.T) { nums := []interface{}{ 1, 1, 1, 2, } var resultSet [][]interface{} Permutation(&resultSet, nums, nil) fmt.Println(len(resultSet)) fmt.Println(resultSet) } func TestSpiralOrder(t *testing.T) { matrix := [][]interface{}{ {1, 2, 3, 100}, {8, 9, 4, 1000}, {7, 6, 5, 10000}, } fmt.Println(SpiralOrder(matrix)) } type ListNode struct { Val int Next *ListNode }
true
fd986e993585fe78925f068cc1d41e4889c49b56
Go
tk103331/jacocogo
/core/analysis/line.go
UTF-8
659
3.296875
3
[]
no_license
[]
no_license
package analysis type Line interface { InstructionCounter() Counter BranchCounter() Counter Status() CoverageStatus } type LineImpl struct { instructions CounterImpl branches CounterImpl } func (l LineImpl) InstructionCounter() Counter { return l.instructions } func (l LineImpl) BranchCounter() Counter { return l.branches } func (l LineImpl) Status() CoverageStatus { return l.instructions.Status() | l.branches.Status() } func (l LineImpl) Increment(instructionCounter Counter, branchCounter Counter) LineImpl { return LineImpl{instructions: l.instructions.Increment(instructionCounter), branches: l.branches.Increment(branchCounter)} }
true
4ca45e5dec3b6e902155446a170dc24cb4f1539b
Go
khalilliu/beau-blog
/server/api/v1/user.go
UTF-8
3,934
2.515625
3
[]
no_license
[]
no_license
package v1 import ( "beau-blog/global" "beau-blog/middleware" "beau-blog/model" "beau-blog/model/request" "beau-blog/model/response" "beau-blog/service" "beau-blog/utils" "github.com/dgrijalva/jwt-go" "github.com/gin-gonic/gin" "go.uber.org/zap" "time" ) // @Tags Base // @Summary 用户登录 // @Produce application/json // @Param data body request.Login true "用户名, 密码, 验证码" // @Success 200 {string} string "{"success":true,"data":{},"msg":"登陆成功"}" // @Router /base/login [post] func Login(c *gin.Context) { var L request.ReqLogin _ = c.ShouldBindJSON(&L) if err := utils.Verify(L, utils.LoginVerify); err != nil { response.FailWithMessage(err.Error(), c) return } if captchaStore.Verify(L.CaptchaId, L.Captcha, true) { User := &model.User{Username: L.Username, Password: L.Password} if err, user := service.Login(User); err != nil { global.BB_LOG.Error("登陆失败! 用户名不存在或者密码错误", zap.Any("err", err)) response.FailWithMessage("登陆失败! 用户名不存在或者密码错误", c); } else { tokenNext(c, &user) } } else { response.FailWithMessage("验证码错误", c); } } // 登录成功后签发jwt func tokenNext(c *gin.Context, user *model.User) { j := &middleware.JWT{SigningKey: []byte(global.BB_CONFIG.JWT.SigningKey)} claims := request.ReqCustomClaims{ UUID: user.UUID, ID: user.ID, Nickname: user.Nickname, Username: user.Username, BufferTime: 60 * 60 * 24, // 缓冲时间1天 缓冲时间内会获得新的token刷新令牌 此时一个用户会存在两个有效令牌 但是前端只留一个 另一个会丢失 StandardClaims: jwt.StandardClaims{ NotBefore: time.Now().Unix() - 1000, // 签名生效时间 ExpiresAt: time.Now().Unix() + 60*60*24*7, // 过期时间 7天 Issuer: "bbPlus", // 签名的发行者 }, } token, err := j.CreateToken(claims) if err != nil { global.BB_LOG.Error("获取token失败", zap.Any("err", err)) response.FailWithMessage("获取token失败", c) return } // 单点登录 if !global.BB_CONFIG.System.UseMultipoint { response.OkWithDetailed(response.ResLogin{ User: *user, Token: token, ExpiredAt: claims.StandardClaims.ExpiresAt * 1000, }, "登录成功", c) return } } // @Tags SysUser // @Summary 用户修改密码 // @Produce application/json // @Param data body model.SysUser true "用户名, 昵称, 密码" // @Success 200 {string} string "{"success":true,"data":{},"msg":"登陆成功"}" // @Router /base/register [post] func ChangePassword(c *gin.Context) { var user request.ReqChangePassword _ = c.ShouldBindJSON(&user) if err := utils.Verify(user, utils.ChangePasswordVerify); err != nil { response.FailWithMessage(err.Error(), c) return } u := &model.User{Username: user.Username, Password: user.Password,} if err, _ := service.ChangePassword(u, user.NewPassword); err != nil { global.BB_LOG.Error("修改失败", zap.Any("err", err)) response.FailWithMessage("修改失败, 原密码与当前账户不符", c) } else { response.OkWithMessage("修改成功", c) } } // @Tags SysUser // @Summary 设置用户信息 // @Security ApiKeyAuth // @accept application/json // @Produce application/json // @Param data body model.SysUser true "ID, 用户名, 昵称, 头像链接" // @Success 200 {string} string "{"success":true,"data":{},"msg":"设置成功"}" // @Router /user/setUserInfo [put] func SetUserInfo(c *gin.Context) { var user model.User _ = c.ShouldBindJSON(&user) if err := utils.Verify(user, utils.IdVerify); err != nil { response.FailWithMessage(err.Error(), c) return } if err, ReqUser := service.SetUserInfo(user); err != nil { global.BB_LOG.Error("设置失败", zap.Any("err", err)) response.FailWithMessage("设置失败", c) }else { response.OkWithDetailed(gin.H{"userInfo": ReqUser}, "设置成功", c) } }
true
a203182f292e0ade6473b735807dcb8341483d8d
Go
MonologueX/golang
/test/src/gocode/Project26/main/main.go
UTF-8
699
3.328125
3
[]
no_license
[]
no_license
package main import ( "fmt" "os" "flag" ) // go run main.go -u root -pwd 123456 -h host -port 3306 func main() { fmt.Printf("命令行有%v个参数!\n", len(os.Args)) for i, v := range os.Args { fmt.Printf("args[%v]=%v\n", i, v) } var user string var pwd string var host string var port int flag.StringVar(&user, "u", "", "用户名默认为空") flag.StringVar(&pwd, "pwd", "", "密码默认为空") flag.StringVar(&host, "h", "localhost", "主机名,默认为localhost") flag.IntVar(&port, "port", 3306, "端口号,默认为3306") flag.Parse() fmt.Printf("user=%q, pwd=%q, host=%q, port=%v\n", user, pwd, host, port) }
true
ebb2eecba13f4329c54b886e1e6441fc2559bab0
Go
mrmiroslav/ratelimit
/httpserver.go
UTF-8
4,238
3.171875
3
[ "BSD-3-Clause" ]
permissive
[ "BSD-3-Clause" ]
permissive
package ratelimit import ( "errors" "fmt" "log" "net/http" "net/url" "strconv" "time" ) type HttpServer struct { limiter Limiter logger *log.Logger } func NewHttpServer(limiter Limiter, logger *log.Logger) *HttpServer { return &HttpServer{ limiter, logger, } } func (s *HttpServer) ServeHTTP(w http.ResponseWriter, req *http.Request) { switch req.Method { case "GET": s.get(w, req) case "POST": s.post(w, req) case "DELETE": s.delete(w, req) default: http.Error(w, http.StatusText(http.StatusMethodNotAllowed), http.StatusMethodNotAllowed) } } func (s *HttpServer) get(w http.ResponseWriter, req *http.Request) { values := req.URL.Query() key, err := s.getRequiredKeyStr("key", values) if err != nil { s.logger.Println("HTTP GET 400", req.URL) http.Error(w, err.Error(), http.StatusBadRequest) return } used, err := s.limiter.Get(key) if err == ErrNotFound { s.logger.Println("HTTP GET 404", key) http.Error(w, err.Error(), http.StatusNotFound) return } else if err != nil { s.logger.Println("HTTP GET 500", key) http.Error(w, err.Error(), http.StatusInternalServerError) return } s.logger.Println("HTTP GET 200", key, used) fmt.Fprintln(w, used) } func (s *HttpServer) post(w http.ResponseWriter, req *http.Request) { values := req.URL.Query() key, err := s.getRequiredKeyStr("key", values) if err != nil { s.logger.Println("HTTP POST 400", req.URL) http.Error(w, err.Error(), http.StatusBadRequest) return } count, err := s.getRequiredKeyInt("count", values) if err != nil { s.logger.Println("HTTP POST 400", req.URL) http.Error(w, err.Error(), http.StatusBadRequest) return } limit, err := s.getRequiredKeyInt("limit", values) if err != nil { s.logger.Println("HTTP POST 400", req.URL) http.Error(w, err.Error(), http.StatusBadRequest) return } duration, err := s.getRequiredKeyDuration("duration", values) if err != nil { s.logger.Println("HTTP POST 400", req.URL) http.Error(w, err.Error(), http.StatusBadRequest) return } used, err := s.limiter.Post(key, count, limit, duration) if err == ErrLimitReached { s.logger.Println("HTTP POST 405", key, count, limit, values.Get("duration")) http.Error(w, err.Error(), http.StatusMethodNotAllowed) return } else if isLimiterError(err) { s.logger.Println("HTTP POST 400", req.URL) http.Error(w, err.Error(), http.StatusBadRequest) return } else if err != nil { s.logger.Println("HTTP POST 500", req.URL, err.Error()) http.Error(w, err.Error(), http.StatusInternalServerError) return } s.logger.Println("HTTP POST 200", key, count, limit, values.Get("duration"), used) fmt.Fprintln(w, used) } func (s *HttpServer) delete(w http.ResponseWriter, req *http.Request) { values := req.URL.Query() key, err := s.getRequiredKeyStr("key", values) if err != nil { s.logger.Println("HTTP DELETE 400", req.URL) http.Error(w, err.Error(), http.StatusBadRequest) return } err = s.limiter.Delete(key) if err != nil { s.logger.Println("HTTP DELETE 500", req.URL) http.Error(w, err.Error(), http.StatusInternalServerError) return } s.logger.Println("HTTP DELETE 200", key) fmt.Fprint(w, "") } func (s *HttpServer) getRequiredKeyStr(key string, values url.Values) (string, error) { value := values.Get(key) if value == "" { return "", errors.New(fmt.Sprintf("'%s' field is missing", key)) } return value, nil } func (s *HttpServer) getRequiredKeyInt(key string, values url.Values) (int64, error) { value, err := s.getRequiredKeyStr(key, values) if err != nil { return 0, err } parsed, err := strconv.ParseInt(value, 10, 64) if err != nil { return 0, err } return parsed, nil } func (s *HttpServer) getRequiredKeyDuration(key string, values url.Values) (time.Duration, error) { value, err := s.getRequiredKeyStr(key, values) if err != nil { return 0, err } duration, err := time.ParseDuration(value) if err != nil { return 0, errors.New(fmt.Sprintf("'%s' is not a valid duration value", key)) } return duration, err } func isLimiterError(err error) bool { list := [...]error{ErrKeyEmpty, ErrCountZero, ErrLimitZero, ErrCountLimit, ErrZeroDuration} for _, e := range list { if err == e { return true } } return false }
true
610b3f93bd3e77a578d08ec70a73e794e86b8c7e
Go
funkygao/nano
/transport/tcp/dialer.go
UTF-8
784
2.765625
3
[]
no_license
[]
no_license
package tcp import ( "net" "github.com/funkygao/nano" ) // dialer implements the nano.PipeDialer interface. type dialer struct { t *tcpTransport addr *net.TCPAddr proto nano.Protocol opts options } func (this *dialer) Dial() (nano.Pipe, error) { conn, err := net.DialTCP("tcp", nil, this.addr) if err != nil { return nil, err } if err = this.opts.configTCP(conn); err != nil { conn.Close() return nil, err } nano.Debugf("dial tcp:%v done, NewConnPipe...", *this.addr) return nano.NewConnPipe(conn, this.proto, nano.FlattenOptions(this.t.opts)...) } func (this *dialer) SetOption(name string, val interface{}) error { return this.opts.set(name, val) } func (this *dialer) GetOption(name string) (interface{}, error) { return this.opts.get(name) }
true
250b39660fe07797dac3c722495e2dfeb59637b9
Go
zhlhahaha/bazeldnf
/pkg/ldd/ldd.go
UTF-8
2,309
2.90625
3
[]
no_license
[]
no_license
package ldd import ( "debug/elf" "os" "path/filepath" ) func Resolve(objects []string, library_path string) (finalFiles []string, err error) { discovered := map[string]struct{}{} for _, obj := range objects { if files, err := resolve(obj, library_path); err != nil { return nil, err } else { for _, l := range files { if _, exists := discovered[l]; !exists { discovered[l] = struct{}{} finalFiles = append(finalFiles, l) } } } } return } func resolve(library string, library_path string) ([]string, error) { next := []string{library} processed := map[string]struct{}{} finalFiles := []string{} for { if len(next) == 0 { break } if d, err := ldd(next[0], library_path); err != nil { return nil, err } else { for _, l := range d { if _, exists := processed[l]; !exists { next = append(next, l) processed[l] = struct{}{} finalFiles = append(finalFiles, l) } } if len(next) > 1 { next = next[1 : len(next)-1] } else { next = []string{} } } } finalFiles = append(finalFiles, library) symlinks, err := followSymlinks(library) if err != nil { return nil, err } finalFiles = append(finalFiles, symlinks...) return finalFiles, nil } func ldd(library string, library_path string) (discovered []string, err error) { bin, err := elf.Open(library) if err != nil { return nil, err } libs, err := bin.ImportedLibraries() if err != nil { return nil, err } for _, l := range libs { _, err := os.Stat(filepath.Join(library_path, l)) if err != nil { return nil, err } discovered = append(discovered, filepath.Join(library_path, l)) symlinks, err := followSymlinks(filepath.Join(library_path, l)) if err != nil { return nil, err } discovered = append(discovered, symlinks...) } return discovered, nil } func followSymlinks(file string) (files []string, err error) { dir := filepath.Dir(file) for { info, err := os.Lstat(file) if err != nil { return nil, err } if info.Mode()&os.ModeSymlink == os.ModeSymlink { file, err = os.Readlink(file) if err != nil { return nil, err } if !filepath.IsAbs(file) { file = filepath.Join(dir, file) } files = append(files, file) } else { files = append(files, file) break } } return }
true
72af53bc7199b9f05cc0941ea85a1c1fe812acd9
Go
fishingfly/go-
/14_字符和字符串的区别.go
UTF-8
418
3.84375
4
[]
no_license
[]
no_license
// 14_字符和字符串的区别 package main import ( "fmt" ) func main() { // var ch byte var str string // 字符单引号,字符串双引号 // 字符往往都只有一个字符,转义字符除外 // 字符串是有1个或多个字符组成 // 字符串是隐藏了一个结束符 // ch = 'a' str = "a" //有'a'和'\0'组成了一个字符串 str = "hello go" fmt.Printf("str[0] = %c", str[0]) }
true
b8b02be606945ecce7dbf475b0eebf44eca4df4c
Go
BrunoScheufler/blog-code-examples
/choosing-go-web-framework/echo/main.go
UTF-8
1,759
3.296875
3
[]
no_license
[]
no_license
package main import ( "github.com/labstack/echo" "net/http" ) // This is the response struct that will be // serialized and sent back type StatusResponse struct { Status string `json:"status"` User string `json:"user"` } // In addition to echo request handlers // using a special context including // all kinds of utilities, generated errors // can be returned to handle them easily func UserGetHandler(e echo.Context) error { // Create response object body := &StatusResponse{ Status: "Hello world from echo!", User: e.Param("user"), } // In this case we can return the JSON // function with our body as errors // thrown by this will be handled return e.JSON(http.StatusOK, body) } // This simple struct will be deserialized // and processed in the request handler type RequestBody struct { Name string `json:"name"` } func UserPostHandler(e echo.Context) error { // Similar to the gin implementation, // we start off by creating an // empty request body struct requestBody := &RequestBody{} // Bind body to the request body // struct and check for potential // errors err := e.Bind(requestBody) if err != nil { // If an error was created by the // Bind operation, we can utilize // echo's request handler structure // and simply return the error so // it gets handled accordingly return err } body := &StatusResponse{ Status: "Hello world from echo!", User: requestBody.Name, } return e.JSON(http.StatusOK, body) } func main() { // Create echo instance e := echo.New() // Add endpoint route for /users/<username> e.GET("/users/:user", UserGetHandler) // Add endpoint route for /users e.POST("/users", UserPostHandler) // Start echo and handle errors e.Logger.Fatal(e.Start(":8002")) }
true
b268d2262644e2d2cc4e0dc9c0ec587e74b3f5a3
Go
tgunnoe/paygate
/internal/filetransfer/incoming_test.go
UTF-8
2,251
2.5625
3
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
// Copyright 2020 The Moov Authors // Use of this source code is governed by an Apache License // license that can be found in the LICENSE file. package filetransfer import ( "io/ioutil" "os" "path/filepath" "strings" "testing" "github.com/go-kit/kit/log" ) func TestController__writeFiles(t *testing.T) { dir, _ := ioutil.TempDir("", "file-transfer-async") defer os.RemoveAll(dir) controller := &Controller{} files := []File{ { Filename: "write-test", Contents: ioutil.NopCloser(strings.NewReader("test conents")), }, } if err := controller.writeFiles(files, dir); err != nil { t.Error(err) } // verify file was written bs, err := ioutil.ReadFile(filepath.Join(dir, "write-test")) if err != nil { t.Error(err) } if v := string(bs); v != "test conents" { t.Errorf("got %q", v) } } func TestController__saveRemoteFiles(t *testing.T) { agent := &mockFileTransferAgent{ inboundFiles: []File{ { Filename: "ppd-debit.ach", Contents: readFileAsCloser(filepath.Join("..", "..", "testdata", "ppd-debit.ach")), }, }, returnFiles: []File{ { Filename: "return-WEB.ach", Contents: readFileAsCloser(filepath.Join("..", "..", "testdata", "return-WEB.ach")), }, }, } dir, err := ioutil.TempDir("", "saveRemoteFiles") if err != nil { t.Fatal(err) } defer os.RemoveAll(dir) controller := &Controller{ rootDir: dir, // use our temp dir logger: log.NewNopLogger(), } if err := controller.saveRemoteFiles(agent, dir); err != nil { t.Error(err) } // read written files file, err := parseACHFilepath(filepath.Join(dir, agent.InboundPath(), "ppd-debit.ach")) if err != nil { t.Error(err) } if v := file.Batches[0].GetHeader().StandardEntryClassCode; v != "PPD" { t.Errorf("SEC code found is %s", v) } file, err = parseACHFilepath(filepath.Join(dir, agent.ReturnPath(), "return-WEB.ach")) if err != nil { t.Error(err) } if v := file.Batches[0].GetHeader().StandardEntryClassCode; v != "WEB" { t.Errorf("SEC code found is %s", v) } // latest deleted file should be our return WEB if !strings.Contains(agent.deletedFile, "return-WEB.ach") && !strings.Contains(agent.deletedFile, "ppd-debit.ach") { t.Errorf("deleted file was %s", agent.deletedFile) } }
true
6719646968ef5d7b49d87c61514004d6ec6faaf3
Go
SkillfactoryCoding/Geolocation-API
/Geolocation-API-backend/api/GetLocation.go
UTF-8
1,329
2.875
3
[]
no_license
[]
no_license
package api import ( "context" "log" "net/http" "os" "strconv" "googlemaps.github.io/maps" "geolocationAPI/handlers" ) type GetLocationResponse struct { Address string `json:"address"` } func GetLocation(w http.ResponseWriter, r *http.Request) { var ( err error latitude float64 longitude float64 ) /*достаем широту из параметра запроса*/ lat := r.URL.Query().Get("lat") /*конвертируем в float64*/ latitude, err = strconv.ParseFloat(lat, 64) /*достаем долготу из параметра запроса*/ long := r.URL.Query().Get("long") /*конвертируем в float64*/ longitude, err = strconv.ParseFloat(long, 64) /*создаем клиента с помощью API_KEY*/ c, err := maps.NewClient(maps.WithAPIKey(os.Getenv("API_KEY"))) if err != nil { log.Fatal(err) } /*получение адреса по координатам*/ res, err := c.Geocode(context.Background(), &maps.GeocodingRequest{ LatLng: &maps.LatLng{ Lat: latitude, Lng: longitude, }, }) if err != nil{ log.Fatal(err) } /*записываем полученные данные в ответ*/ response := GetLocationResponse{ Address: res[0].FormattedAddress, } handlers.JsonResponse(w, response, http.StatusOK) }
true
3702a832a5c1a62d8a92f9d4fefb2a05af2a4ed2
Go
billmi/go-utils
/xorm-helper/example/condition-build.go
UTF-8
1,375
2.671875
3
[ "Apache-2.0" ]
permissive
[ "Apache-2.0" ]
permissive
package main import ( _ "github.com/go-sql-driver/mysql" "fmt" "github.com/billmi/xorm-helper" ) /** datetime : 2019-08-30 18:18:18 author : Bill */ func main() { var XormHelper = xormhelper.XormHelper{} //condition Build var ( _condi = make(map[string]map[string]interface{}, 0) ) //Like Condi Set _condi["LIKE"] = map[string]interface{}{ "title": "Bill", } //And Condi Set _condi["AND"] = map[string]interface{}{ "title": "Bill", } //GT Set _condi["GT"] = map[string]interface{}{ "device_screen_width": 300, } //GT Set _condi["LT"] = map[string]interface{}{ "device_screen_width": 300, } //IN Set _condi["IN"] = map[string]interface{}{ "id": "1,2,3", } //NULL Set (only field) _condi["NULL"] = map[string]interface{}{ "device_type_title": "", } //OR Set Or is special , condition you can build by yourself _condi["OR"] = map[string]interface{}{ "Or_1": "id = 1", "Or_2": "device_screen_width > 0", } fmt.Print("\r\n ========== Conditon Build \r\n") fmt.Print(XormHelper.ConditionBuild(_condi)) fmt.Print("\r\n ========== Conditon Build \r\n") //join build , -- join var joinDemo = [][]string{ {"LEFT", "b b", "b.id = a.id"}, {"INNER", "c c", "c.id = b.id"}, {"RIGHT", "c c", "c.id = b.id"}, } fmt.Print("\r\n ========== Join Conditon Build \r\n") fmt.Print(XormHelper.ConditionJoin(joinDemo)) }
true
325a0073b1096059c798de17482dd3691c8feefe
Go
uni-3/go-by-tdd
/dependency_injection/main.go
UTF-8
494
3.703125
4
[]
no_license
[]
no_license
package main import ( "fmt" "io" "log" "net/http" "os" ) func main() { Greet(os.Stdout, "elodie\n") fmt.Println("server started on http://localhost:5000") if err := http.ListenAndServe(":5000", http.HandlerFunc(MyGreeterHandler)); err != nil { log.Fatal(err) } } func Greet(writer io.Writer, name string) { fmt.Fprintf(writer, "hello, %s", name) } // wにgreetを書き込んで、rで返す func MyGreeterHandler(w http.ResponseWriter, r *http.Request) { Greet(w, "world") }
true
3ef78ebbeb86468a2344f8788e1803f0493182e9
Go
matthiase/kirby
/api/healthcheck/check_database_connection.go
UTF-8
771
2.9375
3
[]
no_license
[]
no_license
package healthcheck import ( "fmt" "kirby/httputil" "net/http" "github.com/jinzhu/gorm" ) // CheckDatabaseConnection verifies successful database connection func CheckDatabaseConnection(db *gorm.DB) func(http.ResponseWriter, *http.Request) { handler := func(w http.ResponseWriter, r *http.Request) { var result DatabaseCheckResult db.Raw("SELECT current_database()").Scan(&result) if result != (DatabaseCheckResult{}) { httputil.RespondWithJSON(w, http.StatusOK, Healthcheck{ Status: "ok", Message: fmt.Sprintf("Database connection to '%s' succeeded", result.CurrentDatabase), }) return } httputil.RespondWithJSON(w, http.StatusOK, Healthcheck{ Status: "failed", Message: "Database connection failed", }) } return handler }
true
c3363d5b0706bb2565814d035a0c176e21193674
Go
Ovy95/BasicsOfGolangfunctions
/Maps/fileExtension.go
UTF-8
381
3.109375
3
[]
no_license
[]
no_license
package main import "fmt" func main() { fileExt := map[string]string{ "Golang": ".go", "C++": ".cpp", "Java": ".java", "Python": ".py ", } fmt.Println(fileExt) fmt.Println(len(fileExt)) if ext, ok := fileExt["Java"]; ok { fmt.Println(ext, ok) } if ext, ok := fileExt["Ruby"]; ok { fmt.Println(ext, ok) } else { fmt.Println("Error not found") } }
true
2c0926f0fac2bab5f27f3da016928d57060c08b0
Go
gaosong030431207/ngac-1
/pkg/pip/graph/memory/graph_test.go
UTF-8
10,105
2.859375
3
[]
no_license
[]
no_license
package memory import ( "ngac/pkg/operations" gg "ngac/pkg/pip/graph" "testing" ) func TestCreateNode(t *testing.T) { g := New() pc, _ := g.CreatePolicyClass("pc", nil) if !g.PolicyClasses().Contains(pc.Name) { t.Fatalf("failed to lookup policy class") } node, _ := g.CreateNode("oa", gg.OA, gg.ToProperties(gg.PropertyPair{"namespace", "test"}), pc.Name) // check node is added node, _ = g.Node(node.Name) if node.Name != "oa" { t.Fatalf("failed to lookup node") } if node.Type != gg.OA { t.Fatalf("failed to lookup type") } } func TestUpdateNode(t *testing.T) { g := New() node, _ := g.CreatePolicyClass("node", gg.ToProperties(gg.PropertyPair{"namespace", "test"})) if err := g.UpdateNode("newNodeName", nil); err == nil { t.Fatalf("failed to catch an error for non-existing node update") } g.UpdateNode("node", gg.ToProperties(gg.PropertyPair{"newKey", "newValue"})) n, _ := g.Node(node.Name) if v, _ := n.Properties["newKey"]; v != "newValue" { t.Fatalf("failed to update properties") } } func TestRemoveNode(t *testing.T) { g := New() node, _ := g.CreatePolicyClass("node", gg.ToProperties(gg.PropertyPair{"namespace", "test"})) g.RemoveNode(node.Name) if g.Exists(node.Name) { t.Fatalf("node should not exist after deleting") } if g.PolicyClasses().Contains(node.Name) { t.Fatalf("node should not have policy after deletion of policy node") } } func TestPolicies(t *testing.T) { g := New() g.CreatePolicyClass("node1", nil) g.CreatePolicyClass("node2", nil) g.CreatePolicyClass("node3", nil) if g.PolicyClasses().Len() != 3 { t.Fatalf("node should not have 3 policies") } } func TestChildren(t *testing.T) { g := New() parentNode, _ := g.CreatePolicyClass("parent", nil) child1Node, _ := g.CreateNode("child1", gg.OA, nil, "parent") child2Node, _ := g.CreateNode("child2", gg.OA, nil, "parent") children := g.Children(parentNode.Name) if !children.Contains(child1Node.Name, child2Node.Name) { t.Fatalf("failed to lookup child 1 or 2") } } func TestParents(t *testing.T) { g := New() parent1Node, _ := g.CreatePolicyClass("parent1", nil) parent2Node, _ := g.CreateNode("parent2", gg.OA, nil, "parent1") child1Node, _ := g.CreateNode("child1", gg.OA, nil, "parent1", "parent2") parents := g.Parents(child1Node.Name) if !parents.Contains(parent1Node.Name, parent2Node.Name) { t.Fatalf("failed to lookup parent 1 or 2") } } func TestAssign(t *testing.T) { g := New() parent1Node, _ := g.CreatePolicyClass("parent1", nil) child1Node, _ := g.CreateNode("child1", gg.OA, nil, "parent1") child2Node, _ := g.CreateNode("child2", gg.OA, nil, "parent1") if err := g.Assign("1241124", "123442141"); err == nil { t.Fatalf("should not assign non existing node ids") } if err := g.Assign("1", "12341234"); err == nil { t.Fatalf("should not assign non existing node ids") } g.Assign(child1Node.Name, child2Node.Name) if !g.Children(parent1Node.Name).Contains(child1Node.Name) { t.Fatalf("failed to lookup child 1") } if !g.Parents(child1Node.Name).Contains(parent1Node.Name) { t.Fatalf("failed to lookup parent") } } func TestDeassign(t *testing.T) { g := New() parent1Node, _ := g.CreatePolicyClass("parent1", nil) child1Node, _ := g.CreateNode("child1", gg.OA, nil, "parent1") if err := g.Assign("", ""); err == nil { t.Fatalf("should not assign non existing node ids") } if err := g.Assign(child1Node.Name, ""); err == nil { t.Fatalf("should not assign non existing node ids") } g.Deassign(child1Node.Name, parent1Node.Name) if g.Children(parent1Node.Name).Contains(child1Node.Name) { t.Fatalf("still able lookup child") } if g.Parents(child1Node.Name).Contains(parent1Node.Name) { t.Fatalf("still able lookup parent") } } func TestAssociate(t *testing.T) { g := New() g.CreatePolicyClass("pc", nil) uaNode, _ := g.CreateNode("subject", gg.UA, nil, "pc") targetNode, _ := g.CreateNode("target", gg.OA, nil, "pc") g.Associate(uaNode.Name, targetNode.Name, operations.NewOperationSet("read", "write")) associations, err := g.SourceAssociations(uaNode.Name) if err != nil { t.Fatalf("error thrown at getting source associations") } if _, ok := associations[targetNode.Name]; !ok { t.Fatalf("failed to get association for id: %s", targetNode.Name) } if !associations[targetNode.Name].Contains("read", "write") { t.Fatalf("failed to get right associations for source: read/write") } associations, err = g.TargetAssociations(targetNode.Name) if err != nil { t.Fatalf("error thrown at getting target associations") } if _, ok := associations[uaNode.Name]; !ok { t.Fatalf("failed to get association for id: %s", uaNode.Name) } if !associations[uaNode.Name].Contains("read", "write") { t.Fatalf("failed to get right associations for target: read/write") } g.CreateNode("test", gg.UA, nil, "subject") g.Associate("test", "subject", operations.NewOperationSet("read")) associations, err = g.SourceAssociations("test") if err != nil { t.Fatalf("error thrown at getting source associations") } if _, ok := associations["subject"]; !ok { t.Fatalf("failed to get association for id: subject") } if !associations["subject"].Contains("read") { t.Fatalf("failed to get right associations for source: read") } } func TestDissociate(t *testing.T) { g := New() g.CreatePolicyClass("pc", nil) uaNode, _ := g.CreateNode("subject", gg.UA, nil, "pc") targetNode, _ := g.CreateNode("target", gg.OA, nil, "pc") g.Associate(uaNode.Name, targetNode.Name, operations.NewOperationSet("read", "write")) g.Dissociate(uaNode.Name, targetNode.Name) associations, err := g.SourceAssociations(uaNode.Name) if err != nil { t.Fatalf("error thrown at getting source associations") } if _, ok := associations[targetNode.Name]; ok { t.Fatalf("able to get association for target id: %s", targetNode.Name) } associations, err = g.TargetAssociations(targetNode.Name) if err != nil { t.Fatalf("error thrown at getting target associations") } if _, ok := associations[uaNode.Name]; ok { t.Fatalf("able to get association for source id: %s", uaNode.Name) } } func TestSourceAssociations(t *testing.T) { g := New() g.CreatePolicyClass("pc", nil) uaNode, _ := g.CreateNode("subject", gg.UA, nil, "pc") targetNode, _ := g.CreateNode("target", gg.OA, nil, "pc") g.Associate(uaNode.Name, targetNode.Name, operations.NewOperationSet("read", "write")) associations, err := g.SourceAssociations(uaNode.Name) if err != nil { t.Fatalf("error thrown at getting uaNode associations") } if _, ok := associations[targetNode.Name]; !ok { t.Fatalf("failed to get association for target id: %s", targetNode.Name) } if !associations[targetNode.Name].Contains("read", "write") { t.Fatalf("failed to get right associations for target: read/write") } if _, err := g.SourceAssociations("123"); err == nil { t.Fatalf("able to get association for source id: %s", "123") } } func TestTargetAssociations(t *testing.T) { g := New() g.CreatePolicyClass("pc", nil) uaNode, _ := g.CreateNode("subject", gg.UA, nil, "pc") targetNode, _ := g.CreateNode("target", gg.OA, nil, "pc") g.Associate(uaNode.Name, targetNode.Name, operations.NewOperationSet("read", "write")) associations, err := g.TargetAssociations(targetNode.Name) if err != nil { t.Fatalf("error thrown at getting uaNode associations") } if _, ok := associations[uaNode.Name]; !ok { t.Fatalf("failed to get association for source id: %s", uaNode.Name) } if !associations[uaNode.Name].Contains("read", "write") { t.Fatalf("failed to get right associations for target: read/write") } if _, err := g.TargetAssociations("123"); err == nil { t.Fatalf("able to get association for target id: %s", "123") } } func TestSearch(t *testing.T) { g := New() g.CreatePolicyClass("pc", nil) g.CreateNode("oa1", gg.OA, gg.ToProperties(gg.PropertyPair{"namespace", "test"}), "pc") g.CreateNode("oa2", gg.OA, gg.ToProperties(gg.PropertyPair{"key1", "value1"}), "pc") g.CreateNode("oa3", gg.OA, gg.ToProperties(gg.PropertyPair{"key1", "value1"}, gg.PropertyPair{"key2", "value2"}), "pc") // name and type no properties nodes := g.Search(gg.OA, nil) if nodes.Len() != 3 { t.Fatalf("incorrect length after search: %d", nodes.Len()) } // one property nodes = g.Search(-1, gg.ToProperties(gg.PropertyPair{"key1", "value1"})) if nodes.Len() != 2 { t.Fatalf("incorrect length after search: %d", nodes.Len()) } // just namespace nodes = g.Search(-1, gg.ToProperties(gg.PropertyPair{"namespace", "test"})) if nodes.Len() != 1 { t.Fatalf("incorrect length after search: %d", nodes.Len()) } // name, type, namespace nodes = g.Search(gg.OA, gg.ToProperties(gg.PropertyPair{"namespace", "test"})) if nodes.Len() != 1 { t.Fatalf("incorrect length after search: %d", nodes.Len()) } nodes = g.Search(gg.OA, gg.ToProperties(gg.PropertyPair{"namespace", "test"})) if nodes.Len() != 1 { t.Fatalf("incorrect length after search: %d", nodes.Len()) } nodes = g.Search(gg.OA, nil) if nodes.Len() != 3 { t.Fatalf("incorrect length after search: %d", nodes.Len()) } nodes = g.Search(gg.OA, gg.ToProperties(gg.PropertyPair{"key1", "value1"})) if nodes.Len() != 2 { t.Fatalf("incorrect length after search: %d", nodes.Len()) } nodes = g.Search(-1, nil) if nodes.Len() != 4 { t.Fatalf("incorrect length after search: %d", nodes.Len()) } } func TestNodes(t *testing.T) { g := New() g.CreatePolicyClass("pc", nil) g.CreateNode("node1", gg.OA, nil, "pc") g.CreateNode("node2", gg.OA, nil, "pc") g.CreateNode("node3", gg.OA, nil, "pc") // name and type no properties if g.Nodes().Len() != 4 { t.Fatalf("incorrect length : %d", g.Nodes().Len()) } } func TestNode(t *testing.T) { g := New() _, err := g.Node("123") if err == nil { t.Fatalf("no node expected") } node, _ := g.CreatePolicyClass("pc", nil) // name and type no properties n, _ := g.Node(node.Name) if n.Name != "pc" { t.Fatalf("incorrect node name") } if n.Type != gg.PC { t.Fatalf("incorrect node type") } }
true
078d405ae9ab1e614826fc473e68a57e81c36213
Go
wenyekui/leetcode
/longest-univalue-path.go
UTF-8
395
2.5625
3
[]
no_license
[]
no_license
package main import ( "fmt" ) /** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */ func longestUnivaluePath(root *TreeNode) int { } func do(node *TreeNode, parentVal int, curLen int, maxLen int) int { if node == nil { return maxLen } if node.Val == parentVal { } } func main() { fmt.Println("") }
true
6035f0efe505dc6de05c8c890d41012cf4a54cd0
Go
ferhatelmas/gitql
/sql/analyzer/analyzer_test.go
UTF-8
2,471
2.859375
3
[ "MIT" ]
permissive
[ "MIT" ]
permissive
package analyzer_test import ( "fmt" "testing" "github.com/gitql/gitql/mem" "github.com/gitql/gitql/sql" "github.com/gitql/gitql/sql/analyzer" "github.com/gitql/gitql/sql/expression" "github.com/gitql/gitql/sql/plan" "github.com/stretchr/testify/require" ) func TestAnalyzer_Analyze(t *testing.T) { assert := require.New(t) table := mem.NewTable("mytable", sql.Schema{{"i", sql.Integer}}) db := mem.NewDatabase("mydb") db.AddTable("mytable", table) catalog := &sql.Catalog{Databases: []sql.Database{db}} a := analyzer.New(catalog) a.CurrentDatabase = "mydb" var notAnalyzed sql.Node = plan.NewUnresolvedRelation("mytable") analyzed, err := a.Analyze(notAnalyzed) assert.Nil(err) assert.Equal(table, analyzed) notAnalyzed = plan.NewUnresolvedRelation("nonexistant") analyzed, err = a.Analyze(notAnalyzed) assert.NotNil(err) assert.Equal(notAnalyzed, analyzed) analyzed, err = a.Analyze(table) assert.Nil(err) assert.Equal(table, analyzed) notAnalyzed = plan.NewProject( []sql.Expression{expression.NewUnresolvedColumn("i")}, plan.NewUnresolvedRelation("mytable"), ) analyzed, err = a.Analyze(notAnalyzed) expected := plan.NewProject( []sql.Expression{expression.NewGetField(0, sql.Integer, "i")}, table, ) assert.Nil(err) assert.Equal(expected, analyzed) notAnalyzed = plan.NewProject( []sql.Expression{expression.NewUnresolvedColumn("i")}, plan.NewFilter( expression.NewEquals( expression.NewUnresolvedColumn("i"), expression.NewLiteral(int32(1), sql.Integer), ), plan.NewUnresolvedRelation("mytable"), ), ) analyzed, err = a.Analyze(notAnalyzed) expected = plan.NewProject( []sql.Expression{expression.NewGetField(0, sql.Integer, "i")}, plan.NewFilter( expression.NewEquals( expression.NewGetField(0, sql.Integer, "i"), expression.NewLiteral(int32(1), sql.Integer), ), table, ), ) assert.Nil(err) assert.Equal(expected, analyzed) } func TestAnalyzer_Analyze_MaxIterations(t *testing.T) { assert := require.New(t) catalog := &sql.Catalog{} a := analyzer.New(catalog) a.CurrentDatabase = "mydb" i := 0 a.Rules = []analyzer.Rule{{ "infinite", func(a *analyzer.Analyzer, n sql.Node) sql.Node { i += 1 return plan.NewUnresolvedRelation(fmt.Sprintf("rel%d", i)) }, }} notAnalyzed := plan.NewUnresolvedRelation("mytable") analyzed, err := a.Analyze(notAnalyzed) assert.NotNil(err) assert.Equal(plan.NewUnresolvedRelation("rel1001"), analyzed) }
true
cbf1afd1d382bda94a08fd34fd9531d09739fed3
Go
hoon-k/go-chit-chat-api
/user-api/services/account-service.go
UTF-8
1,661
2.84375
3
[]
no_license
[]
no_license
package services import ( "go-chit-chat-api/user-api/models" ) // CreateUser creates a user and returns a message to broadcast on success func CreateUser(req *models.CreateUserRequest) (*models.CreateUserMessage, error) { db := getDBConnection() defer db.Close() rows, err := db.Query(`SELECT * FROM create_user($1, $2, $3, $4)`, req.UserName, req.Password, req.FirstName, req.LastName) failOnError(err, "Unable to create new user") if err != nil { return nil, err } msg := &models.CreateUserMessage{} rows.Next() rows.Scan(&msg.FirstName, &msg.LastName, &msg.UserName, &msg.Role) return msg, nil } // DeleteUser deletes user func DeleteUser(id string) (*models.DeleteUserMessage, error) { db := getDBConnection() defer db.Close() rows, err := db.Query(`SELECT * FROM delete_user($1)`, id) failOnError(err, "Unable to delete a user") msg := &models.DeleteUserMessage{} rows.Next() rows.Scan(&msg.UserName, &msg.FirstName, &msg.LastName) return msg, err } // GetAllUsers lists all users func GetAllUsers() *models.UserResults { db := getDBConnection() defer db.Close() rows, _ := db.Query("SELECT first_name, last_name FROM users") defer rows.Close() userResults := &models.UserResults{} count := 0 for rows.Next() { user := &models.User{} err := rows.Scan(&user.FirstName, &user.LastName) failOnError(err, "Unable to get a list of users") userResults.Users = append(userResults.Users, *user) count = count + 1 } userResults.TotalNumber = count return userResults }
true
f7156480a00b48f5ce05fac2de5046ebb0779795
Go
linml/xsys
/xclock/_date.go
UTF-8
4,389
3.21875
3
[]
no_license
[]
no_license
package xclock import ( "strconv" "time" "fmt" "github.com/pkg/errors" "github.com/smcduck/xdsa/xstring" ) type Date time.Time //type Date int32 // Fixme 由于内部是time.Time 格式化、对比大小等操作时,可能会发生错误 func Today() Date { return TimeToDate(time.Now()) } func Yesterday() Date { return TimeToDate(Sub(time.Now(), time.Hour * 24)) } func TodayString(tz *time.Location) string { return time.Now().In(tz).Format("2006-01-02") } func TimeToDate(tm time.Time) Date { return Date(tm) //return Date(tm.Year() * 10000 + int(tm.Month()) * 100 + tm.Day()) } // check if date is valid // invalid date example: 2018-2-30 func DateValid(year, month, day int) bool { if month <= 0 || month >= 13 { return false } if day <= 0 || day >= 32 { return false } tm := time.Date(year, time.Month(month), day, 0, 0, 0, 0, time.UTC) if tm.Year() != year || tm.Month() != time.Month(month) || tm.Day() != day { return false } return true } func NewDate(year, month, day int, tz *time.Location) (Date, error) { if tz == nil { return ZeroDate, errors.New("nil *time.Location") } if !DateValid(year, month, day) { return Date{}, errors.Errorf("Invalid date input %d-%d-%d", year, month, day) } return Date(time.Date(year, time.Month(month), day, 0, 0, 0, 0, tz)), nil //return Date((year * 10000) + (month * 100) + day), nil } func (d Date) In(tz *time.Location) Date { return Date(time.Time(d).In(tz)) } func (d Date) Year() int { return time.Time(d).Year() } func (d Date) Month() time.Month { return time.Time(d).Month() } func (d Date) Day() int { return time.Time(d).Day() } func (d Date) Equal(cmp Date) bool { return d.IntYYYYMMDD() == cmp.IntYYYYMMDD() } func (d Date) Before(cmp Date) bool { return d.IntYYYYMMDD() < cmp.IntYYYYMMDD() } func (d Date) BeforeEqual(cmp Date) bool { return d.IntYYYYMMDD() <= cmp.IntYYYYMMDD() } func (d Date) After(cmp Date) bool { return d.IntYYYYMMDD() > cmp.IntYYYYMMDD() } func (d Date) AfterEqual(cmp Date) bool { return d.IntYYYYMMDD() >= cmp.IntYYYYMMDD() } func (d Date) IsZero() bool { return d.Equal(ZeroDate) } func (d Date) Sub(cmp Date) int { return int(d.ToTime().Sub(cmp.ToTime()).Hours() / 24) } func (d Date) String() string { if d.ToTime().IsZero() { return "" } return d.StringYYYY_MM_DD() } func (d Date) MarshalJSON() ([]byte, error) { return []byte(fmt.Sprintf("\"%s\"", d.String())), nil } func (d *Date) UnmarshalJSON(b []byte) error { s := string(b) if len(s) <= 1 { return errors.Errorf("Invalid json date '%s'", s) } if s[0] != '"' || s[len(s) - 1] != '"' { return errors.Errorf("Invalid json date '%s'", s) } s = xstring.RemoveHead(s, 1) s = xstring.RemoveTail(s, 1) dt, err := ParseDateString(s, true) if err != nil { *d = ZeroDate return err } *d = dt return nil } // yyyymmdd // Notice: // 如果你写成了fmt.Sprintf("%04d%02d%02d", d.Year, d.YearMonth, d.Day),编译也能通过 // 但是返回结果却是很大很大的数字,因为它们代表函数地址 func (d Date) StringYYYYMMDD() string { return d.ToTime().Format("20060102") } func (d Date) IntYYYYMMDD() int { n, _ := strconv.ParseInt(d.ToTime().Format("20060102"), 10, 64) return int(n) } // yyyy-mm-dd func (d Date) StringYYYY_MM_DD() string { return d.ToTime().Format("2006-01-02") } // 以time.Time相同的格式输出字符串 func (d Date) StringTime() string { return d.ToTime().String() } func (d Date) ToTime() time.Time { return time.Time(d) } type DateRange struct { Begin Date End Date } func (dr DateRange) String() string { if dr.Begin.IsZero() && dr.End.IsZero() { return "" } return dr.Begin.String() + "/" + dr.End.String() } func (dr DateRange) MarshalJSON() ([]byte, error) { return []byte(fmt.Sprintf("\"%s\"", dr.String())), nil } func (dr *DateRange) UnmarshalJSON(b []byte) error { // Init dr.Begin = ZeroDate dr.End = ZeroDate // Remove '"' s := string(b) ErrDefault := errors.Errorf("invalid json date range '%s'", s) if len(s) <= 1 { return ErrDefault } if s[0] != '"' || s[len(s) - 1] != '"' { return ErrDefault } s = xstring.RemoveHead(s, 1) s = xstring.RemoveTail(s, 1) // Parse res, err := ParseDateRangeString(s, true) if err != nil { return ErrDefault } *dr = res return nil } func (dr DateRange) IsZero() bool { return dr.Begin.IsZero() && dr.End.IsZero() }
true
99d3af1d510bf9e121892b20f79b931d5d76e7b7
Go
solinox/advent-of-code
/2019/10/main.go
UTF-8
3,180
3.515625
4
[]
no_license
[]
no_license
package main import ( "fmt" "io/ioutil" "strings" "math" "sort" ) type Angle1 struct { Quadrant int Val float64 } type Angle2 struct { Asteroid Point Quadrant int Val float64 Mag float64 } type Point struct { X, Y int } type Asteroids map[Point]bool func main() { asteroids := parseInput("input.txt") // Part 1 lineOfSight := getAsteroidsInLOS(asteroids) part1 := 0 var bestAsteroid Point for asteroid, count := range lineOfSight { if count > part1 { part1 = count bestAsteroid = asteroid } } fmt.Println("Part 1", part1, bestAsteroid) // Part 2 part2 := sortAsteroids(asteroids, bestAsteroid) fmt.Println("Part 2", part2[199].Asteroid.X * 100 + part2[199].Asteroid.Y) } func sortAsteroids(asteroids Asteroids, asteroid Point) []Angle2{ sorted := make([]Angle2, 0, len(asteroids)-1) for other := range asteroids { if asteroid.X == other.X && asteroid.Y == other.Y { continue } _, angle := newAngles(asteroid, other) sorted = append(sorted, angle) } sort.Slice(sorted, func(i, j int) bool { a1, a2 := sorted[i], sorted[j] if a1.Quadrant == a2.Quadrant { if a1.Val == a2.Val { return a1.Mag < a2.Mag } if a1.Quadrant == 1 || a1.Quadrant == 3 { return a1.Val > a2.Val } return a1.Val < a2.Val } return a1.Quadrant < a2.Quadrant }) for i := 1; i < len(sorted); { if sorted[i].Val == sorted[i-1].Val { // move to end, preserve order of the rest cutAngle := sorted[i] sorted = append(sorted[:i], append(sorted[i+1:], cutAngle)...) } else { i++ } } return sorted } func getAsteroidsInLOS(asteroids Asteroids) map[Point]int { lineOfSight := make(map[Point]int) for asteroid := range asteroids { blockedAngles := make(map[Angle1]bool) lineOfSightCount := 0 for other := range asteroids { if asteroid.X == other.X && asteroid.Y == other.Y { continue } angle, _ := newAngles(asteroid, other) if exists := blockedAngles[angle]; exists { continue } else { lineOfSightCount++ blockedAngles[angle] = true } } lineOfSight[asteroid] = lineOfSightCount } return lineOfSight } // Lazy and tweaked this to return the type I need for either part 1 or 2 func newAngles(asteroid, other Point) (Angle1, Angle2) { angleVal := math.Abs(float64(other.Y - asteroid.Y) / float64(other.X - asteroid.X)) quadrant := 0 if other.X >= asteroid.X && other.Y <= asteroid.Y { quadrant = 1 // Northeast } else if other.X >= asteroid.X && other.Y >= asteroid.Y { quadrant = 2 // Southeast } else if other.X < asteroid.X && other.Y >= asteroid.Y { quadrant = 3 // Southwest } else { quadrant = 4 // Northwest } return Angle1{Quadrant: quadrant, Val: angleVal}, Angle2{Quadrant: quadrant, Val: angleVal, Asteroid: other, Mag: math.Abs(float64(other.X - asteroid.X)) + math.Abs(float64(other.Y - asteroid.Y))} } func parseInput(filename string) Asteroids { data, _ := ioutil.ReadFile(filename) lines := strings.Split(string(data), "\n") asteroids := make(Asteroids) for y := range lines { for x := range lines[y] { if lines[y][x] == '#' { pt := Point{x,y} asteroids[pt] = true } } } return asteroids }
true
b37461f6f4a4b8ed22d48273f49030a111fecba6
Go
indrayam/kubefwd
/pkg/utils/hostfile.go
UTF-8
1,116
2.9375
3
[ "Apache-2.0" ]
permissive
[ "Apache-2.0" ]
permissive
package utils import ( "fmt" "io" "log" "os" "github.com/cbednarski/hostess" ) // GetHostFile returns a pointer to a hostess Hostfile object. func GetHostFile() (*hostess.Hostfile, error) { hostfile, errs := hostess.LoadHostfile() fmt.Printf("Loading hosts file %s\n", hostfile.Path) if errs != nil { fmt.Println("Can not load /etc/hosts") for _, err := range errs { return hostfile, err } } // make backup of original hosts file if no previous backup exists backupHostsPath := hostfile.Path + ".original" if _, err := os.Stat(backupHostsPath); os.IsNotExist(err) { from, err := os.Open(hostfile.Path) if err != nil { return hostfile, err } defer from.Close() to, err := os.OpenFile(backupHostsPath, os.O_RDWR|os.O_CREATE, 0644) if err != nil { log.Fatal(err) } defer to.Close() _, err = io.Copy(to, from) if err != nil { return hostfile, err } fmt.Printf("Backing up your original hosts file %s to %s\n", hostfile.Path, backupHostsPath) } else { fmt.Printf("Original hosts backup already exists at %s\n", backupHostsPath) } return hostfile, nil }
true
aef4b1d965f25d26ac1d1b483739a595e779072c
Go
Eldius/learning-go
/terminal-gui-tests/tools/tweet/tweet.go
UTF-8
1,471
3
3
[ "MIT", "Apache-2.0" ]
permissive
[ "MIT", "Apache-2.0" ]
permissive
package tweet import ( "fmt" "os" "github.com/dghubble/go-twitter/twitter" "github.com/dghubble/oauth1" ) /* MyTwitterClient is an abstraction for the client connection */ type MyTwitterClient struct { client *twitter.Client IsConnected bool } /* Connect will connect your client */ func (c *MyTwitterClient)Connect() (err error) { consumerKey := os.Getenv("TW_CONSUMER_KEY") consumerSecret := os.Getenv("TW_CONSUMER_SECRET") accessToken := os.Getenv("TW_ACCESS_TOKEN") accessTokenSecret := os.Getenv("TW_ACCESS_TOKEN_SECRET") config := oauth1.NewConfig(consumerKey, consumerSecret) token := oauth1.NewToken(accessToken, accessTokenSecret) // OAuth1 http.Client will automatically authorize Requests httpClient := config.Client(oauth1.NoContext, token) // Twitter client c.client = twitter.NewClient(httpClient) // Verify Credentials verifyParams := &twitter.AccountVerifyParams{ SkipStatus: twitter.Bool(true), IncludeEmail: twitter.Bool(true), } user, _, _ := c.client.Accounts.VerifyCredentials(verifyParams) fmt.Printf("User's ACCOUNT:\n%+v\n", user) c.IsConnected = true return } /* FetchTimeline loads fetch tweets from Twitter */ func (c *MyTwitterClient)FetchTimeline(maxQtd int) []twitter.Tweet { client := c.client // Home Timeline homeTimelineParams := &twitter.HomeTimelineParams{ Count: maxQtd, TweetMode: "extended", } tweets, _, _ := client.Timelines.HomeTimeline(homeTimelineParams) return tweets }
true
214011e28517db11861f08e1e65ad5fce3af40c7
Go
mindreframer/golang-testing-stuff
/src/github.com/bmatsuo/go-spec/spec/matcher.go
UTF-8
6,252
2.890625
3
[ "BSD-3-Clause", "BSD-2-Clause", "MIT", "Apache-2.0" ]
permissive
[ "BSD-3-Clause", "BSD-2-Clause", "MIT", "Apache-2.0" ]
permissive
// Copyright 2011, Bryan Matsuo. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package spec /* Filename: matcher.go * Author: Bryan Matsuo <[email protected]> * Created: Thu Nov 3 05:19:41 PDT 2011 * Description: */ import ( "reflect" "errors" "fmt" ) var boolval = true var boolType = reflect.TypeOf(&boolval).Elem() var errorval = errors.New("ERROR") var errorType = reflect.TypeOf(errorval) // The default set of Spec matchers. var ( Equal = MatcherMust(NewMatcher("Equal", matcherEqual)) Satisfy = MatcherMust(NewMatcher("Satisfy", matcherSatisfy)) HaveError = MatcherMust(NewMatcher("HaveError", matcherHaveError)) Panic = MatcherMust(NewMatcher("Panic", matcherPanic)) ) // If x is not a FnCall, return x. Otherwise, return the first return value // of x. func valueOfSpecValue(x interface{}) (y interface{}) { switch x.(type) { case FnCall: y = x.(FnCall).out[0].Interface() default: y = x } return } // Use reflect.DeepEqual to test two values' equality. func matcherEqual(a, b interface{}) (pass bool, err error) { //t.doDebug(func() { t.Logf("%#v = %#v", a, b) }) pass = reflect.DeepEqual( valueOfSpecValue(a), valueOfSpecValue(b)) return } func matcherSatisfy(x, fn interface{}) (pass bool, err error) { //t.doDebug(func() { t.Logf("%#v satisfies function %#v", x, fn) }) fnval := reflect.ValueOf(fn) // Check the type of fn (fn(x)bool). if k := fnval.Kind(); k != reflect.Func { return false, errors.New("Satisfy given non-function") } x = valueOfSpecValue(x) if typ := fnval.Type(); typ.NumIn() != 1 { // error: fn must accept a single value. err = errors.New("Satisfy needs a function of one argument") } else if xtyp := reflect.TypeOf(x); !xtyp.AssignableTo(typ.In(0)) { // error: fn must accept x err = errors.New("Satisfy argument type-mismatch") } else if typ.NumOut() != 1 { // error: fn must return one value err = errors.New("Satisfy needs a predicate (func(x) bool)") } else if !typ.Out(0).AssignableTo(boolType) { // error: fn must return bool err = errors.New("Satisfy output type-mismatch") } if err != nil { return } fnout := fnval.Call([]reflect.Value{reflect.ValueOf(x)}) pass = fnout[0].Bool() return } func matcherHaveError(fn interface{}) (pass bool, err error) { //t.doDebug(func() { t.Logf("Function %#v has an error", fn) }) var errval reflect.Value switch fn.(type) { case FnCall: fncall := fn.(FnCall) fntyp := fncall.fn.Type() if !errorType.AssignableTo(fntyp.Out(fntyp.NumOut() - 1)) { // error: fn's last return value error. return false, errors.New("HaveError function call's last Value must be os.Error") } errval = fncall.out[len(fncall.out)-1] default: err = errors.New("HaveError needs a function call Value") return } var fnerr error switch v := errval.Interface(); v.(type) { case nil: fnerr = nil case error: fnerr = v.(error) default: return false, errors.New("Function call can not have error") } pass = fnerr != nil return } func matcherPanic(fn interface{}) (pass bool, err error) { //t.doDebug(func() { t.Logf("Function %#v has an error", fn) }) switch fn.(type) { case FnCall: fncall := fn.(FnCall) pass = fncall.panicv != nil if pass { return } default: err = errors.New("HaveError needs a function call Value") } return } type Matcher interface { // Run the matcher against arguments. Matches(args []interface{}) (bool, error) // The name of the matcher for printing upon failure. String() string // Return any error encountered executing the matcher. Error() error // Return the number of arguments needed by the matcher NumIn() int } type match struct { name string // For printing purposes fn reflect.Value // A bool function of at least one argument typ reflect.Type // A type with kind reflect.Func err error // An error encountered when running err (panic / bug) } type errpanic struct { v interface{} } func (ep errpanic) Error() string { return fmt.Sprintf("runtime panic: %v", ep.v) } func (m *match) call(args []reflect.Value) (pass bool, err error) { defer func() { if e := recover(); e != nil { m.err = errpanic{e} err = m.err panic(e) } }() out := m.fn.Call(args) pass = out[0].Bool() switch e := out[1].Interface(); e.(type) { case nil: case error: m.err = e.(error) default: err = fmt.Errorf("unexpected type %s", reflect.TypeOf(e).Name()) } return } func (m *match) Matches(args []interface{}) (bool, error) { n := len(args) // Check the arguments. if n != m.NumIn() { return false, errors.New("wrong number of arguments") } // Turn interfaces into reflect.Values and call the matcher. vals := make([]reflect.Value, n) for i := range args { vals[i] = reflect.ValueOf(args[i]) } return m.call(vals) } func (m *match) String() string { return m.name } func (m *match) Error() error { return m.err } func (m *match) NumIn() int { return m.typ.NumIn() } // Create a new Matcher object from function fn. Function fn must take // at least one argument and return exactly one bool. func NewMatcher(name string, fn interface{}) (Matcher, error) { m := new(match) m.name = name m.fn = reflect.ValueOf(fn) m.typ = m.fn.Type() // Check the kind of fn. if k := m.typ.Kind(); k != reflect.Func { return m, errors.New("matcher not a function") } // Check the number of inputs on fn if numin := m.typ.NumIn(); numin == 0 { return m, errors.New("nil-adic matcher") } // Check the number of outputs on fn if numout := m.typ.NumOut(); numout < 2 { return m, errors.New("not enough matcher return values") } else if numout > 2 { return m, errors.New("too many matcher return values") } // Check the types of fn's outputs if bout := m.typ.Out(0); !bout.AssignableTo(boolType) { return m, errors.New("matcher with non-bool return") } if !errorType.AssignableTo(m.typ.Out(1)) { return m, errors.New("matcher with non-error second return value") } return m, nil } func MatcherMust(m Matcher, err error) Matcher { if err != nil { panic(err) } return m }
true
4daa394268e7209cea7da357f35263888bcc334b
Go
AirArto/hw-5
/goroutine_stack_test.go
UTF-8
1,290
2.78125
3
[]
no_license
[]
no_license
package goroutine import ( "errors" "testing" ) func TestRun(t *testing.T) { taskList := [...]func() error{ func() error { return nil }, func() error { return errors.New("err") }, func() error { return errors.New("err") }, func() error { return errors.New("err") }, func() error { return errors.New("err") }, func() error { return errors.New("err") }, func() error { return errors.New("err") }, func() error { return nil }, func() error { return nil }, func() error { return nil }, func() error { return errors.New("err") }, func() error { return nil }, func() error { return nil }, func() error { return nil }, func() error { return nil }, func() error { return nil }, func() error { return nil }, } tasks := taskList[:] err := Run(tasks, 3, 3) if err == nil { t.Errorf("\n\t%s", "Something goes wrong") } else { err = Run(tasks, 2, 8) } if err != nil { t.Errorf("\n\t%s", "Something goes wrong") } else { err = Run(tasks, 4, 7) } if err == nil { t.Errorf("\n\t%s", "Something goes wrong") } else { err = Run(tasks, 0, 7) } if err == nil { t.Errorf("\n\t%s", "Something goes wrong") } else { err = Run(tasks, 3, 0) } if err == nil { t.Errorf("\n\t%s", "Something goes wrong") } }
true
af080fa4280abbb1de3fa2a697f8c45249ec6a6d
Go
dubbe/aoc_20
/day20/main.go
UTF-8
10,834
2.890625
3
[]
no_license
[]
no_license
package main import ( "fmt" "regexp" "strconv" "strings" "time" "github.com/dubbe/advent-of-code-2020/helpers" ) func main() { start := time.Now() lines, err := helpers.ReadGroups("input") helpers.Check(err) //fmt.Printf("result A: %v\n", a(lines)) fmt.Printf("result B: %v\n", b(lines)) elapsed := time.Since(start) fmt.Printf("Solution took %s", elapsed) } type PicturePart struct { ID int Matrix map[int]map[int]rune MostMatches int Matches []MatchedPicturePart } type MatchedPicturePart struct { Matrix map[int]map[int]rune Left int Right int Top int Bottom int ID int } func a(groups []string) int { pictureParts := parseParts(groups) foundParts := []PicturePart{} j := 0 for _, v := range pictureParts { foundParts = append(foundParts, findMatches(v, pictureParts)) j++ } sum := 1 for _, part := range foundParts { if part.MostMatches == 2 { sum *= part.ID } } return sum } func b(groups []string) int { for { pictureParts := parseParts(groups) foundParts := map[int]PicturePart{} for _, part := range pictureParts { p := findMatches(part, pictureParts) foundParts[p.ID] = p } possibleCornerParts := []PicturePart{} for _, part := range foundParts { if part.MostMatches == 2 { possibleCornerParts = append(possibleCornerParts, part) } } m := map[int]map[int]MatchedPicturePart{} m[0] = map[int]MatchedPicturePart{} Test: for _, part := range possibleCornerParts { for _, match := range part.Matches { if match.Right != 0 && match.Bottom != 0 { match.ID = part.ID m[0][0] = match break Test } } } i := 0 for { j := 0 for { p, ok := m[i][j] if ok { if p.Right == 0 { break } part := foundParts[p.Right] for _, match := range part.Matches { if match.Left == p.ID { found := true for x := 0; x < len(p.Matrix); x++ { if p.Matrix[x][len(p.Matrix[0])-1] != match.Matrix[x][0] { found = false break } } if found { match.ID = part.ID m[i][j+1] = match break } } } } else { break } j++ } p, ok := m[i][0] if ok { if p.Bottom == 0 { break } m[i+1] = map[int]MatchedPicturePart{} part := foundParts[p.Bottom] for _, match := range part.Matches { if match.Top == p.ID { found := true fmt.Printf("-----------\n") printMatrix(p.Matrix, true) fmt.Printf("\n") printMatrix(match.Matrix, true) for x := 0; x < len(p.Matrix); x++ { fmt.Printf("x: %d, y: %d", x, len(p.Matrix)-1) fmt.Printf("%s %s \n", string(p.Matrix[len(p.Matrix)-1][x]), string(match.Matrix[0][x])) if p.Matrix[len(p.Matrix)-1][x] != match.Matrix[0][x] { found = false break } } if found { match.ID = part.ID m[i+1][0] = match break } } } } else { break } i++ } finalImage := "" finalImageTest := map[int]map[int]rune{} // matrix grid i = 0 j := 0 // image grid x := 1 y := 1 matrix := m[j][i].Matrix w := 0 z := 0 finalImageTest[z] = map[int]rune{} for { finalImage += string(matrix[y][x]) finalImageTest[z][w] = matrix[y][x] w++ x++ if x > len(matrix)-2 { x = 1 i++ if i > len(m)-1 { i = 0 w = 0 y++ if y > len(matrix[y])-2 { y = 1 j++ if j > len(m[j])-1 { break } } z++ finalImageTest[z] = map[int]rune{} finalImage += "\n" } matrix = m[j][i].Matrix } } // fmt.Print(finalImage) newImage := "" FindImage: for x := 0; x < 4; x++ { for y := 0; y < 3; y++ { image := sprintMatrix(finalImageTest, false) found := false for l := 0; l < len(finalImageTest[0])-len(".#..#..#..#..#..#..."); l++ { re := regexp.MustCompile(fmt.Sprintf(".{%d}..................(#)..*\n.{%d}(#)....(#)(#)....(#)(#)....(#)(#)(#).*\n.{%d}.(#)..(#)..(#)..(#)..(#)..(#)....*", l, l, l)) for re.MatchString(image) { found = true index := re.FindStringSubmatchIndex(image) for w := 2; w < len(index); w += 2 { in := index[w] image = image[:in] + "O" + image[in+1:] } } } if found { newImage = image break FindImage } if x == 0 { finalImageTest = flipMatrixHor(finalImageTest) } else if x == 1 { finalImageTest = flipMatrixHor(finalImageTest) finalImageTest = flipMatrixVert(finalImageTest) } else { finalImageTest = flipMatrixVert(finalImageTest) } } finalImageTest = rotateMatrix(finalImageTest) } sum := strings.Count(newImage, "#") if sum != 0 { fmt.Print(newImage) return sum } } } func joinMaps(left, right map[int]rune) map[int]rune { for key, rightVal := range right { left[key] = rightVal } return left } func parseParts(groups []string) map[int]PicturePart { pictureParts := map[int]PicturePart{} for _, group := range groups { part := parsePart(group) pictureParts[part.ID] = part } return pictureParts } func parsePart(part string) PicturePart { picturePart := PicturePart{} title := strings.Split(strings.Split(part, "\n")[0], " ") id, _ := strconv.Atoi(strings.TrimRight(title[1], ":")) picturePart.ID = id picturePart.Matrix = parseMatrix(part) return picturePart } func findMatches(part PicturePart, parts map[int]PicturePart) PicturePart { finalMatch := 0 finalMatches := []MatchedPicturePart{} matrix := part.Matrix for i := 0; i < 4; i++ { for x := 0; x < 3; x++ { t := getTopFromMatrix(matrix) b := getBottomFromMatrix(matrix) l := getLeftFromMatrix(matrix) r := getRightFromMatrix(matrix) left := []int{} right := []int{} top := []int{} bottom := []int{} for _, p := range parts { if p.ID == part.ID { continue } pMatrix := p.Matrix for y := 0; y < 6; y++ { for w := 0; w < 3; w++ { if t == getBottomFromMatrix(pMatrix) { top = append(top, p.ID) } if b == getTopFromMatrix(pMatrix) { bottom = append(bottom, p.ID) } if l == getRightFromMatrix(pMatrix) { left = append(left, p.ID) } if r == getLeftFromMatrix(pMatrix) { right = append(right, p.ID) } if w == 0 { pMatrix = flipMatrixHor(pMatrix) } else if w == 1 { pMatrix = flipMatrixHor(pMatrix) pMatrix = flipMatrixVert(pMatrix) } else { pMatrix = flipMatrixVert(pMatrix) } } pMatrix = rotateMatrix(pMatrix) } } top = removeDuplicates(top) right = removeDuplicates(right) bottom = removeDuplicates(bottom) left = removeDuplicates(left) match := len(top) + len(right) + len(bottom) + len(left) if match >= finalMatch { m := MatchedPicturePart{} if len(top) == 1 { m.Top = top[0] } if len(right) == 1 { m.Right = right[0] } if len(bottom) == 1 { m.Bottom = bottom[0] } if len(left) == 1 { m.Left = left[0] } m.Matrix = matrix if match == finalMatch { finalMatches = append(finalMatches, m) } else { finalMatch = match finalMatches = []MatchedPicturePart{m} } } if x == 0 { matrix = flipMatrixHor(matrix) } else if x == 1 { matrix = flipMatrixHor(matrix) matrix = flipMatrixVert(matrix) } else { matrix = flipMatrixVert(matrix) } } matrix = rotateMatrix(matrix) } part.MostMatches = finalMatch part.Matches = finalMatches return part } func getTopFromMatrix(matrix map[int]map[int]rune) string { ret := "" for i := 0; i < len(matrix); i++ { ret += fmt.Sprintf("%s", string(matrix[0][i])) } return ret } func getBottomFromMatrix(matrix map[int]map[int]rune) string { ret := "" j := len(matrix) - 1 for i := 0; i < len(matrix); i++ { ret += fmt.Sprintf("%s", string(matrix[j][i])) } return ret } func getLeftFromMatrix(matrix map[int]map[int]rune) string { ret := "" for i := 0; i < len(matrix); i++ { ret += fmt.Sprintf("%s", string(matrix[i][0])) } return ret } func getRightFromMatrix(matrix map[int]map[int]rune) string { ret := "" j := len(matrix) - 1 for i := 0; i < len(matrix); i++ { ret += fmt.Sprintf("%s", string(matrix[i][j])) } return ret } func reverse(s string) string { runes := []rune(s) for i, j := 0, len(runes)-1; i < j; i, j = i+1, j-1 { runes[i], runes[j] = runes[j], runes[i] } return string(runes) } func removeDuplicates(intSlice []int) []int { keys := make(map[int]bool) list := []int{} for _, entry := range intSlice { if _, value := keys[entry]; !value { keys[entry] = true list = append(list, entry) } } return list } func parseMatrix(part string) map[int]map[int]rune { lines := strings.Split(part, "\n") ret := map[int]map[int]rune{} for i, line := range lines { if i == 0 { continue } ret[i-1] = map[int]rune{} for j, r := range line { ret[i-1][j] = r } } return ret } func rotateMatrix(matrix map[int]map[int]rune) map[int]map[int]rune { ret := map[int]map[int]rune{} n := len(matrix[0]) for i := 0; i < n; i++ { ret[i] = map[int]rune{} for j := 0; j < n; j++ { ret[i][j] = matrix[n-j-1][i] } } return ret } func flipMatrixVert(matrix map[int]map[int]rune) map[int]map[int]rune { ret := map[int]map[int]rune{} n := len(matrix[0]) for i := 0; i < n; i++ { ret[i] = matrix[n-i-1] } return ret } func flipMatrixHor(matrix map[int]map[int]rune) map[int]map[int]rune { ret := map[int]map[int]rune{} n := len(matrix[0]) for i := 0; i < n; i++ { ret[i] = map[int]rune{} for j := 0; j < n; j++ { ret[i][j] = matrix[i][n-j-1] } } return ret } func printPicturePart(pp PicturePart) { fmt.Printf("\nid: %d\n", pp.ID) printMatches(pp.Matches) printMatrix(pp.Matrix, true) } func printMatches(matches []MatchedPicturePart) { for _, match := range matches { fmt.Printf("top: %d, right: %d, bottom: %d, left: %d \n ", match.Top, match.Right, match.Bottom, match.Left) printMatrix(match.Matrix, true) fmt.Printf("\n") } } func printMatrix(matrix map[int]map[int]rune, printSpace bool) { for i := 0; i < len(matrix); i++ { value := matrix[i] for j := 0; j < len(value); j++ { v := value[j] if printSpace { fmt.Printf("%s ", string(v)) } else { fmt.Printf("%s", string(v)) } } fmt.Printf("\n") } } func sprintMatrix(matrix map[int]map[int]rune, printSpace bool) string { ret := "" for i := 0; i < len(matrix); i++ { value := matrix[i] for j := 0; j < len(value); j++ { v := value[j] if printSpace { ret += fmt.Sprintf("%s ", string(v)) } else { ret += fmt.Sprintf("%s", string(v)) } } ret += fmt.Sprintf("\n") } return ret }
true
85892639d08e40f5d5ec3d7f90e16895c2379017
Go
CodeFreezr/gobyes
/corpus/chisnall/phrasebook/examples/expandSlice.go
UTF-8
260
2.859375
3
[ "MIT" ]
permissive
[ "MIT" ]
permissive
package main import "fmt" func main() { s0 := make([]int, 2, 10) s1 := append(s0, 2) s2 := append(s0, 3) fmt.Printf("Element: %d %d\n", s1[2], s2[2]) s0 = []int{0, 1} s1 = append(s0, 2) s2 = append(s0, 3) fmt.Printf("Element: %d %d\n", s1[2], s2[2]) }
true
a3f2a6c98e7d5a63e32b1b6e2c0ae27a46f20eca
Go
wnyr/graphic-go-algorithms
/code/HeapSort.go
UTF-8
1,457
3.78125
4
[]
no_license
[]
no_license
package main import "fmt" //调整堆 func adjustHeap(array []int , currentIndex int , maxLength int ) { var noLeafValue = array[currentIndex] // 目前非叶节点 //2 * currentIndex + 1 当前左子树下标 for j := 2 *currentIndex + 1 ; j <= maxLength; j = currentIndex*2 + 1 { if j < maxLength && array[j] < array[j+1 ] { j++ // j 大的下标 } if noLeafValue >= array[j] { break } array[currentIndex] = array[j] // 向上移动到父节点 currentIndex = j } array[currentIndex] = noLeafValue // 放到位置上 } //初始化堆 func createHeap(array []int , length int ) { // 建立一个堆, (length - 1) / 2 扫描一半的子节点 for i := (length - 1 ) / 2 ; i >= 0 ; i-- { adjustHeap(array, i, length-1 ) } } func heapSort(array []int , length int ) { for i := length - 1 ; i > 0 ; i-- { var temp = array[0 ] array[0 ] = array[i] array[i] = temp adjustHeap(array, 0 , i-1 ) } } func main() { var scores = []int {10 , 90 , 20 , 80 , 30 , 70 , 40 , 60 , 50 } var length = len (scores) fmt.Printf("在建立堆之前 : \n" ) for i := 0 ; i < length; i++ { fmt.Printf("%d, " , scores[i]) } fmt.Printf("\n\n" ) fmt.Printf("在建立堆之后 : \n" ) createHeap(scores, length) for i := 0 ; i < length; i++ { fmt.Printf("%d, " , scores[i]) } fmt.Printf("\n\n" ) fmt.Printf("堆排序 : \n" ) heapSort(scores, length) for i := 0 ; i < length; i++ { fmt.Printf("%d, " , scores[i]) } }
true
86be1da383bab0a2e7907444a3c09a4422d255b7
Go
githubtestrk/eleme-hackathon
/server/server.go
UTF-8
1,622
2.71875
3
[]
no_license
[]
no_license
package server import ( "encoding/json" "fmt" "net/http" "service" "sync" "time" ) var order_signal *sync.Cond = sync.NewCond(&sync.Mutex{}) var local = true var order_return_interval time.Duration = 2 * time.Second func OrderTicker() { ticker := time.NewTicker(order_return_interval) for t := range ticker.C { order_signal.L.Lock() order_signal.Broadcast() order_signal.L.Unlock() fmt.Println(t, "Order Ticker Broad Casted.") } } func Start(addr string) { http.HandleFunc("/", dispatcher) http.HandleFunc("/login", loginDispatcher) http.HandleFunc("/foods", foodsDispatcher) http.HandleFunc("/carts", cartsDispatcher) http.HandleFunc("/carts/", addFood) http.HandleFunc("/orders", ordersDispatcher) http.HandleFunc("/admin/orders", adminOrdersDispatcher) err := http.ListenAndServe(addr, nil) if err != nil { fmt.Println(err) } } func writeResponse(w http.ResponseWriter, r *Response) { w.WriteHeader(r.status) ret, _ := json.Marshal(r) fmt.Fprintf(w, string(ret)) } func dealRequest(w http.ResponseWriter, r *http.Request) (int, bool) { token := r.Header.Get("Access-Token") if token == "" { token = r.FormValue("access_token") } // fmt.Println("Debug: Recevice Reques with token: ", token) if token == "" { // fmt.Println("Warning: token is empty!!!!") writeResponse(w, Unauthorized) return 0, false } var id int var ok bool if local { id, ok = service.CheckTokenLocal(token) } else { id, ok = service.CheckToken(token) } if !ok { // fmt.Println("Warning: token not exist!!!!") writeResponse(w, Unauthorized) return 0, false } return id, true }
true
6ee8290ebe0ee2674a5655df9266f7c0c221e918
Go
rh01/gofiles
/offer/ex04/findNumsAppearOnce.go
UTF-8
1,060
3.984375
4
[]
no_license
[]
no_license
package main import "fmt" /* // 一个整型数组里除了两个数字之外,其他的数字都出现了两次。请写程序找出这两个只出现一次的数字。 # -*- coding:utf-8 -*- class Solution: # 返回[a,b] 其中ab是出现一次的两个数字 def FindNumsAppearOnce(self, array): # write code here */ func main() { fmt.Println(FindNumsAppearOnce([]int{1,2,3,4,2,3})) } // 返回出现一次得两个数字 func FindNumsAppearOnce(array []int) [2]int { //res是两个只出现一次得两个数字得抑或结果 var res int = 0 for _, value := range array { res = res ^ value } if res == 0 { return [2]int{} } //这里应该加一判断,因为对于有符号整数来说~xxx表示补码得反码 // 参考:https://colobu.com/2016/06/20/dive-into-go-5/#%E9%80%BB%E8%BE%91%E8%BF%90%E7%AE%97%E7%AC%A6 res = (^(^-res + 1) + 1) ^ res num1, num2 := 0, 0 for _, value := range array { if (value & res) != 0 { num1 = num1 ^ value } else { num2 = num2 ^ value } } return [2]int{num2, num1} }
true
c933eeac1e291ebbaf2d049a9e38bde91b36493b
Go
evergreen-innovations/blogs
/gomain/example3/main.go
UTF-8
848
3.515625
4
[ "BSD-3-Clause" ]
permissive
[ "BSD-3-Clause" ]
permissive
package main import ( "fmt" "io/ioutil" "os" ) func main() { var err error // Deferred functions run in reverse order so this will be the last // one called, after any tidy up. defer func() { if err != nil { fmt.Println("error encountered:", err) os.Exit(1) } else { fmt.Println("exiting") } }() if len(os.Args) != 2 { err = fmt.Errorf("invalid number of arguments") return } fileName := os.Args[1] f, err := os.Open(fileName) if err != nil { err = fmt.Errorf("opening file: %v", err) return } // usually this would be just f.Close() but we are putting some logging // to show the process defer func() { f.Close() fmt.Println("closed the file") }() b, err := ioutil.ReadAll(f) if err != nil { err = fmt.Errorf("reading file: %v", err) return } fmt.Println("File contents:", string(b)) }
true
5e8b3d2a823e77e48055ed87a66acbcfc004c37b
Go
SpiffyEight77/LeetCode
/83.Remove-Duplicates-from-Sorted-List/solution.go
UTF-8
357
3.1875
3
[]
no_license
[]
no_license
package leetcode type ListNode struct { Val int Next *ListNode } func deleteDuplicates(head *ListNode) *ListNode { if head == nil { return nil } current := head for current != nil { for current.Next != nil && current.Val == current.Next.Val { current.Next = current.Next.Next } current = current.Next } return head }
true
170030860aa5568d64ed780776971f1e1da6e4df
Go
yylover/project
/go/src/testpro/tcpclient/tcpclient.go
UTF-8
952
3.09375
3
[]
no_license
[]
no_license
package main import ( "flag" "fmt" "net" "time" ) var host = flag.String("host", "", "host") var port = flag.String("port", "333", "port") func main() { fmt.Println("hello") flag.Parse() tcpconn, err := net.Dial("tcp", *host+":"+*port) if err != nil { panic(err) return } defer tcpconn.Close() done := make(chan string) go handleRead(tcpconn, done) go handleWrite(tcpconn, done) <-done <-done } func handleRead(conn net.Conn, done chan string) { for i := 0; i < 10; i++ { conn.SetWriteDeadline(time.Now().Add(time.Second)) conn.Write([]byte("hello\r\n")) } done <- "Sent" } func handleWrite(conn net.Conn, done chan string) { for i := 0; i < 10; i++ { conn.SetReadDeadline(time.Now().Add(time.Second)) buf := make([]byte, 1024) reqlen, err := conn.Read(buf) if err != nil { fmt.Println("read error", err) break } fmt.Println("read len:", reqlen, string(buf[:reqlen-1])) } done <- "write" }
true
eb03fd239559dfb078ec5c987a75f68b068d4052
Go
klnusbaum/adventofcode2018-go
/day2.2/dist_test.go
UTF-8
645
3.140625
3
[ "MIT" ]
permissive
[ "MIT" ]
permissive
package main import ( "testing" ) func TestDistance(t *testing.T) { tests := []struct { msg string str1 string str2 string dist int }{ { msg: "no distance", str1: "hello", str2: "hello", dist: 0, }, { msg: "distance 1", str1: "hello", str2: "hellg", dist: 1, }, { msg: "distance 2", str1: "hello", str2: "hillg", dist: 2, }, } for _, tt := range tests { t.Run(tt.msg, func(t *testing.T) { dist := distance(tt.str1, tt.str2) if dist != tt.dist { t.Errorf("Expected distance between %q and %q was %d, instead got %d", tt.str1, tt.str2, tt.dist, dist) } }) } }
true
5d7e3ebad02832adb130130b53f5ea66b55bd732
Go
mikesbrown/zq
/zio/zngio/writer.go
UTF-8
2,046
2.53125
3
[ "BSD-3-Clause" ]
permissive
[ "BSD-3-Clause" ]
permissive
package zngio import ( "io" "github.com/brimsec/zq/zcode" "github.com/brimsec/zq/zio" "github.com/brimsec/zq/zng" "github.com/brimsec/zq/zng/resolver" ) type Writer struct { io.Writer encoder *resolver.Encoder buffer []byte streamRecords int streamRecordsMax int position int64 } func NewWriter(w io.Writer, flags zio.WriterFlags) *Writer { return &Writer{ Writer: w, encoder: resolver.NewEncoder(), buffer: make([]byte, 0, 128), streamRecordsMax: flags.StreamRecordsMax, } } func (w *Writer) write(b []byte) error { n, err := w.Writer.Write(b) w.position += int64(n) return err } func (w *Writer) Position() int64 { return w.position } func (w *Writer) EndStream() error { w.encoder.Reset() w.streamRecords = 0 marker := []byte{zng.CtrlEOS} return w.write(marker) } func (w *Writer) Write(r *zng.Record) error { // First send any typedefs for unsent types. typ := w.encoder.Lookup(r.Type) if typ == nil { var b []byte var err error b, typ, err = w.encoder.Encode(w.buffer[:0], r.Type) if err != nil { return err } w.buffer = b err = w.write(b) if err != nil { return err } } dst := w.buffer[:0] id := typ.ID() // encode id as uvarint7 if id < 0x40 { dst = append(dst, byte(id&0x3f)) } else { dst = append(dst, byte(0x40|(id&0x3f))) dst = zcode.AppendUvarint(dst, uint64(id>>6)) } dst = zcode.AppendUvarint(dst, uint64(len(r.Raw))) err := w.write(dst) if err != nil { return err } err = w.write(r.Raw) w.streamRecords++ if w.streamRecordsMax > 0 && w.streamRecords >= w.streamRecordsMax { w.EndStream() } return err } func (w *Writer) WriteControl(b []byte) error { dst := w.buffer[:0] //XXX 0xff for now. need to pass through control codes? dst = append(dst, 0xff) dst = zcode.AppendUvarint(dst, uint64(len(b))) err := w.write(dst) if err != nil { return err } return w.write(b) } func (w *Writer) Flush() error { if w.streamRecords > 0 { return w.EndStream() } return nil }
true
27d90c7d07bea1c2230774a7f2cebf0b9afd9212
Go
davepgreene/turnstile
/http/http.go
UTF-8
793
3.5
4
[ "MIT" ]
permissive
[ "MIT" ]
permissive
package http import "net/http" type WrappedResponseWriter struct { status int wroteHeader bool http.ResponseWriter } func NewWrappedResponseWriter(rw http.ResponseWriter) *WrappedResponseWriter { return &WrappedResponseWriter{ResponseWriter: rw} } // Give a way to get the status func (w *WrappedResponseWriter) Status() int { return w.status } // Satisfy the http.ResponseWriter interface func (w *WrappedResponseWriter) Header() http.Header { return w.ResponseWriter.Header() } func (w *WrappedResponseWriter) Write(data []byte) (n int, err error) { return w.ResponseWriter.Write(data) } func (w *WrappedResponseWriter) WriteHeader(statusCode int) { // Store the status code w.status = statusCode // Write the status code onward. w.ResponseWriter.WriteHeader(statusCode) }
true
4dca7c2f30301912b174939743fc3104bd41ee77
Go
superbrothers/httpdebugger
/roundtripper.go
UTF-8
4,405
2.9375
3
[ "Apache-2.0", "MIT" ]
permissive
[ "Apache-2.0", "MIT" ]
permissive
/* Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ /* Copyright 2017 Kazuki Suda. For the full copyright and license information, please view the LICENSE file that was distributed with this source code. */ package httpdebugger import ( "fmt" "io" "net/http" "time" ) type requestCanceler interface { CancelRequest(*http.Request) } // requestInfo keeps track of information about a request/response combination type requestInfo struct { RequestHeaders http.Header RequestVerb string RequestURL string ResponseStatus string ResponseHeaders http.Header ResponseErr error Duration time.Duration } // newRequestInfo creates a new RequestInfo based on an http request func newRequestInfo(req *http.Request) *requestInfo { return &requestInfo{ RequestURL: req.URL.String(), RequestVerb: req.Method, RequestHeaders: req.Header, } } // complete adds information about the response to the requestInfo func (r *requestInfo) complete(response *http.Response, err error) { if err != nil { r.ResponseErr = err return } r.ResponseStatus = response.Status r.ResponseHeaders = response.Header } // toCurl returns a string that can be run as a command in a terminal (minus the body) func (r *requestInfo) toCurl() string { headers := "" for key, values := range r.RequestHeaders { for _, value := range values { headers += fmt.Sprintf(` -H %q`, fmt.Sprintf("%s: %s", key, value)) } } return fmt.Sprintf("curl -k -v -X%s %s %s", r.RequestVerb, headers, r.RequestURL) } // debuggingRoundTripper will display information about the requests passing // through it based on what is configured type debuggingRoundTripper struct { delegatedRoundTripper http.RoundTripper writer io.Writer levels map[debugLevel]bool } type debugLevel int const ( JustURL debugLevel = iota URLTiming CurlCommand RequestHeaders ResponseStatus ResponseHeaders ) func NewDebuggingRoundTripper(rt http.RoundTripper, w io.Writer, levels ...debugLevel) *debuggingRoundTripper { drt := &debuggingRoundTripper{ delegatedRoundTripper: rt, writer: w, levels: make(map[debugLevel]bool, len(levels)), } for _, v := range levels { drt.levels[v] = true } return drt } func (rt *debuggingRoundTripper) CancelRequest(req *http.Request) { if canceler, ok := rt.delegatedRoundTripper.(requestCanceler); ok { canceler.CancelRequest(req) } } func (rt *debuggingRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) { reqInfo := newRequestInfo(req) if rt.levels[JustURL] { fmt.Fprintf(rt.writer, "%s %s\n", reqInfo.RequestVerb, reqInfo.RequestURL) } if rt.levels[CurlCommand] { fmt.Fprintf(rt.writer, "%s\n", reqInfo.toCurl()) } if rt.levels[RequestHeaders] { fmt.Fprintf(rt.writer, "Request Headers:\n") for key, values := range reqInfo.RequestHeaders { for _, value := range values { fmt.Fprintf(rt.writer, " %s: %s\n", key, value) } } } startTime := time.Now() response, err := rt.delegatedRoundTripper.RoundTrip(req) reqInfo.Duration = time.Since(startTime) reqInfo.complete(response, err) if rt.levels[URLTiming] { fmt.Fprintf(rt.writer, "%s %s %s in %d milliseconds\n", reqInfo.RequestVerb, reqInfo.RequestURL, reqInfo.ResponseStatus, reqInfo.Duration.Nanoseconds()/int64(time.Millisecond)) } if rt.levels[ResponseStatus] { fmt.Fprintf(rt.writer, "Response Status: %s in %d milliseconds\n", reqInfo.ResponseStatus, reqInfo.Duration.Nanoseconds()/int64(time.Millisecond)) } if rt.levels[ResponseHeaders] { fmt.Fprintf(rt.writer, "Response Headers:\n") for key, values := range reqInfo.ResponseHeaders { for _, value := range values { fmt.Fprintf(rt.writer, " %s: %s\n", key, value) } } } return response, err } func (rt *debuggingRoundTripper) WrappedRoundTripper() http.RoundTripper { return rt.delegatedRoundTripper }
true
47d410d31363bc80c7e61de62f4ab51d246430a1
Go
LunaticPy/level-1
/25.go
UTF-8
654
3.1875
3
[]
no_license
[]
no_license
package main //t25 import ( "fmt" "math/rand" "sync" "time" ) type Container struct { counter int mx sync.Mutex } func main() { num := 10 data := Container{} end := make(chan bool) for i := 0; i < num; i++ { go func(data *Container, end *chan bool) { for i := 0; i < rand.Int(); i++ { //может быть 1 значение или несколько запустите несколько раз select { case <-*end: return default: data.mx.Lock() data.counter++ fmt.Print(data.counter, " ") data.mx.Unlock() } } }(&data, &end) } time.Sleep(time.Microsecond * 15) end <- true }
true
954a7397e24762387e9b68e03bf9b1a0f7646d71
Go
Awesome-RJ/cli
/main.go
UTF-8
9,880
2.65625
3
[ "MIT" ]
permissive
[ "MIT" ]
permissive
package main import ( "context" "fmt" "os" "runtime" "runtime/debug" "strings" "github.com/railwayapp/cli/cmd" "github.com/railwayapp/cli/constants" "github.com/railwayapp/cli/entity" "github.com/railwayapp/cli/ui" "github.com/spf13/cobra" ) var rootCmd = &cobra.Command{ Use: "railway", SilenceUsage: true, SilenceErrors: true, Version: constants.Version, Short: "🚅 Railway. Infrastructure, Instantly.", Long: "Interact with 🚅 Railway via CLI \n\n Deploy infrastructure, instantly. Docs: https://docs.railway.app", } func addRootCmd(cmd *cobra.Command) *cobra.Command { rootCmd.AddCommand(cmd) return cmd } // contextualize converts a HandlerFunction to a cobra function func contextualize(fn entity.HandlerFunction, panicFn entity.PanicFunction) entity.CobraFunction { return func(cmd *cobra.Command, args []string) error { ctx := context.Background() defer func() { // Skip recover during development, so we can see the panic stack traces instead of going // through the "send to Railway" flow and hiding the stack from the user if constants.IsDevVersion() { return } if r := recover(); r != nil { err := panicFn(ctx, fmt.Sprint(r), string(debug.Stack()), cmd.Name(), args) if err != nil { fmt.Println("Unable to relay panic to server. Are you connected to the internet?") } } }() req := &entity.CommandRequest{ Cmd: cmd, Args: args, } err := fn(ctx, req) if err != nil { // TODO: Make it *pretty* fmt.Println(err.Error()) os.Exit(1) // Set non-success exit code on error } return nil } } func init() { // Initializes all commands handler := cmd.New() loginCmd := addRootCmd(&cobra.Command{ Use: "login", Short: "Login to your Railway account", RunE: contextualize(handler.Login, handler.Panic), }) loginCmd.Flags().Bool("browserless", false, "--browserless") addRootCmd(&cobra.Command{ Use: "logout", Short: "Logout of your Railway account", RunE: contextualize(handler.Logout, handler.Panic), }) addRootCmd(&cobra.Command{ Use: "whoami", Short: "Get the current logged in user", RunE: contextualize(handler.Whoami, handler.Panic), }) addRootCmd(&cobra.Command{ Use: "init", Short: "Create a new Railway project", PersistentPreRunE: contextualize(handler.CheckVersion, handler.Panic), RunE: contextualize(handler.Init, handler.Panic), }) addRootCmd(&cobra.Command{ Use: "link", Short: "Associate existing project with current directory, may specify projectId as an argument", PersistentPreRunE: contextualize(handler.CheckVersion, handler.Panic), RunE: contextualize(handler.Link, handler.Panic), }) addRootCmd(&cobra.Command{ Use: "unlink", Short: "Disassociate project from current directory", RunE: contextualize(handler.Unlink, handler.Panic), }) addRootCmd(&cobra.Command{ Use: "delete [projectId]", Short: "Delete Project, may specify projectId as an argument", RunE: contextualize(handler.Delete, handler.Panic), Args: cobra.MinimumNArgs(1), }) addRootCmd(&cobra.Command{ Use: "disconnect", RunE: contextualize(handler.Unlink, handler.Panic), Deprecated: "Please use 'railway unlink' instead", /**/ }) addRootCmd(&cobra.Command{ Use: "env", RunE: contextualize(handler.Variables, handler.Panic), Deprecated: "Please use 'railway variables' instead", /**/ }) variablesCmd := addRootCmd(&cobra.Command{ Use: "variables", Aliases: []string{"vars"}, Short: "Show variables for active environment", RunE: contextualize(handler.Variables, handler.Panic), }) variablesCmd.AddCommand(&cobra.Command{ Use: "get key", Short: "Get the value of a variable", RunE: contextualize(handler.VariablesGet, handler.Panic), Args: cobra.MinimumNArgs(1), Example: " railway variables get MY_KEY", }) variablesCmd.AddCommand(&cobra.Command{ Use: "set key=value", Short: "Create or update the value of a variable", RunE: contextualize(handler.VariablesSet, handler.Panic), Args: cobra.MinimumNArgs(1), Example: " railway variables set NODE_ENV=prod NODE_VERSION=12", }) variablesCmd.AddCommand(&cobra.Command{ Use: "delete key", Short: "Delete a variable", RunE: contextualize(handler.VariablesDelete, handler.Panic), Example: " railway variables delete MY_KEY", }) addRootCmd(&cobra.Command{ Use: "status", Short: "Show information about the current project", RunE: contextualize(handler.Status, handler.Panic), }) addRootCmd(&cobra.Command{ Use: "environment", Short: "Change the active environment", RunE: contextualize(handler.Environment, handler.Panic), }) openCmd := addRootCmd(&cobra.Command{ Use: "open", Short: "Open your project dashboard", RunE: contextualize(handler.Open, handler.Panic), }) openCmd.AddCommand(&cobra.Command{ Use: "metrics", Short: "Open project metrics", Aliases: []string{"m"}, RunE: contextualize(handler.Open, handler.Panic), }) openCmd.AddCommand(&cobra.Command{ Use: "settings", Short: "Open project settings", Aliases: []string{"s"}, RunE: contextualize(handler.Open, handler.Panic), }) openCmd.AddCommand(&cobra.Command{ Use: "live", Short: "Open the deployed application", Aliases: []string{"l"}, RunE: contextualize(handler.OpenApp, handler.Panic), }) addRootCmd(&cobra.Command{ Use: "list", Short: "List all projects in your Railway account", RunE: contextualize(handler.List, handler.Panic), }) addRootCmd(&cobra.Command{ Use: "run", Short: "Run a local command using variables from the active environment", PersistentPreRunE: contextualize(handler.CheckVersion, handler.Panic), RunE: contextualize(handler.Run, handler.Panic), DisableFlagParsing: true, }) addRootCmd(&cobra.Command{ Use: "protect", Short: "[EXPERIMENTAL!] Protect current branch (Actions will require confirmation)", RunE: contextualize(handler.Protect, handler.Panic), }) addRootCmd(&cobra.Command{ Use: "version", Short: "Get the version of the Railway CLI", PersistentPreRunE: contextualize(handler.CheckVersion, handler.Panic), RunE: contextualize(handler.Version, handler.Panic), }) upCmd := addRootCmd(&cobra.Command{ Use: "up [path]", Short: "Upload and deploy project from the current directory", RunE: contextualize(handler.Up, handler.Panic), }) upCmd.Flags().BoolP("detach", "d", false, "Detach from cloud build/deploy logs") upCmd.Flags().StringP("environment", "e", "", "Specify an environment to up onto") addRootCmd(&cobra.Command{ Use: "logs", Short: "View the most-recent deploy's logs", RunE: contextualize(handler.Logs, handler.Panic), }).Flags().Int32P("lines", "n", 0, "Output a specific number of lines") addRootCmd(&cobra.Command{ Use: "docs", Short: "Open Railway Documentation in default browser", RunE: contextualize(handler.Docs, handler.Panic), }) addRootCmd(&cobra.Command{ Use: "add", Short: "Add a new plugin to your project", RunE: contextualize(handler.Add, handler.Panic), }) addRootCmd(&cobra.Command{ Use: "connect", Short: "Open an interactive shell to a database", RunE: contextualize(handler.Connect, handler.Panic), }) addRootCmd(&cobra.Command{ Hidden: true, Use: "design", Short: "Print CLI design components", RunE: contextualize(handler.Design, handler.Panic), }) addRootCmd(&cobra.Command{ Use: "completion [bash|zsh|fish|powershell]", Short: "Generate completion script", Long: `To load completions: Bash: $ source <(railway completion bash) # To load completions for each session, execute once: # Linux: $ railway completion bash > /etc/bash_completion.d/railway # macOS: $ railway completion bash > /usr/local/etc/bash_completion.d/railway Zsh: # If shell completion is not already enabled in your environment, # you will need to enable it. You can execute the following once: $ echo "autoload -U compinit; compinit" >> ~/.zshrc # To load completions for each session, execute once: $ railway completion zsh > "${fpath[1]}/_railway" # You will need to start a new shell for this setup to take effect. fish: $ railway completion fish | source # To load completions for each session, execute once: $ railway completion fish > ~/.config/fish/completions/railway.fish PowerShell: PS> railway completion powershell | Out-String | Invoke-Expression # To load completions for every new session, run: PS> railway completion powershell > railway.ps1 # and source this file from your PowerShell profile. `, DisableFlagsInUseLine: true, ValidArgs: []string{"bash", "zsh", "fish", "powershell"}, Args: cobra.ExactValidArgs(1), RunE: contextualize(handler.Completion, handler.Panic), }) } func main() { if _, err := os.Stat("/proc/version"); !os.IsNotExist(err) && runtime.GOOS == "windows" { fmt.Printf("%s : Running in Non standard shell!\n Please consider using something like WSL!\n", ui.YellowText(ui.Bold("[WARNING!]").String()).String()) } if err := rootCmd.Execute(); err != nil { if strings.Contains(err.Error(), "unknown command") { suggStr := "\nS" suggestions := rootCmd.SuggestionsFor(os.Args[1]) if len(suggestions) > 0 { suggStr = fmt.Sprintf(" Did you mean \"%s\"?\nIf not, s", suggestions[0]) } fmt.Println(fmt.Sprintf("Unknown command \"%s\" for \"%s\".%s"+ "ee \"railway --help\" for available commands.", os.Args[1], rootCmd.CommandPath(), suggStr)) } else { fmt.Println(err) } os.Exit(1) } }
true
a0942d18145b611b572a684c844ff37c8e4ba5a3
Go
roca/GO
/pluralsight/creating-web-apps/src/models/category.go
UTF-8
2,429
3.046875
3
[ "MIT" ]
permissive
[ "MIT" ]
permissive
package models import ( "errors" ) type Category struct { imageUrl string title string description string isOrientRight bool id int products []Product } func (this *Category) ImageUrl() string { return this.imageUrl } func (this *Category) Title() string { return this.title } func (this *Category) Description() string { return this.description } func (this *Category) IsOrientRight() bool { return this.isOrientRight } func (this *Category) Id() int { return this.id } func (this *Category) Products() []Product { return this.products } func (this *Category) SetImageUrl(value string) { this.imageUrl = value } func (this *Category) SetTitle(value string) { this.title = value } func (this *Category) SetDescription(value string) { this.description = value } func (this *Category) SetIsOrientRight(value bool) { this.isOrientRight = value } func (this *Category) SetId(value int) { this.id = value } func (this *Category) SetProducts(value []Product) { this.products = value } func GetCategories() []Category { result := []Category{ Category{ imageUrl: "lemon.png", title: "Juices and Mixes", description: `Explore our wide assortment of juices and mixes expected by today's lemonade stand clientelle. Now featuring a full line of organic juices that are guaranteed to be obtained from trees that have never been treated with pesticides or artificial fertilizers.`, isOrientRight: false, id: 1, products: GetJuiceProducts(), }, Category{ imageUrl: "kiwi.png", title: "Cups, Straws, and Other Supplies", description: `From paper cups to bio-degradable plastic to straws and napkins, LSS is your source for the sundries that keep your stand running smoothly.`, isOrientRight: true, id: 2, }, Category{ imageUrl: "pineapple.png", title: "Signs and Advertising", description: `Sure, you could just wait for people to find your stand along the side of the road, but if you want to take it to the next level, our premium line of advertising supplies.`, isOrientRight: false, id: 3, }, } return result } func GetCategoryById(id int) (Category, error) { for _, category := range GetCategories() { if category.Id() == id { return category, nil } } return Category{}, errors.New("Category Not Found") }
true
cc90a2e4d56ee36dc468c2c728fb2fe8c18c23cc
Go
akavel/ui
/listbox_unix.go
UTF-8
7,735
2.59375
3
[ "MIT" ]
permissive
[ "MIT" ]
permissive
// +build !windows,!darwin,!plan9 // 17 february 2014 package ui import ( "fmt" "unsafe" ) /* GTK+ 3.10 introduces a dedicated GtkListView type for simple listboxes like our Listbox. Unfortunately, since I want to target at least GTK+ 3.4, I need to do things the old, long, and hard way: manually with a GtkTreeView and GtkListStore model. You are not expected to understand this. if you must though: GtkTreeViews are model/view. We use a GtkListStore as a model. GtkTreeViews also separate selections into another type, but the GtkTreeView creates the selection object for us. GtkTreeViews can scroll, but do not draw scrollbars or borders; we need to use a GtkScrolledWindow to hold the GtkTreeView to do so. We return the GtkScrolledWindow and get its control out when we want to access the GtkTreeView. Like with Windows, there's a difference between signle-selection and multi-selection GtkTreeViews when it comes to getting the list of selections that we can exploit. The GtkTreeSelection class hands us an iterator and the model (for some reason). We pull a GtkTreePath out of the iterator, which we can then use to get the indices or text data. For more information, read https://developer.gnome.org/gtk3/3.4/TreeWidget.html http://ubuntuforums.org/showthread.php?t=1208655 http://scentric.net/tutorial/sec-treemodel-remove-row.html http://gtk.10911.n7.nabble.com/Scrollbars-in-a-GtkTreeView-td58076.html http://stackoverflow.com/questions/11407447/gtk-treeview-get-current-row-index-in-python (I think; I don't remember if I wound up using this one as a reference or not; I know after that I found the ubuntuforums link above) and the GTK+ reference documentation. */ // #include "gtk_unix.h" // /* because cgo seems to choke on ... */ // void gtkTreeModelGet(GtkTreeModel *model, GtkTreeIter *iter, gchar **gs) // { // /* 0 is the column #; we only have one column here */ // gtk_tree_model_get(model, iter, 0, gs, -1); // } // GtkListStore *gtkListStoreNew(void) // { // /* 1 column that stores strings */ // return gtk_list_store_new(1, G_TYPE_STRING); // } // void gtkListStoreSet(GtkListStore *ls, GtkTreeIter *iter, char *gs) // { // /* same parameters as in gtkTreeModelGet() */ // gtk_list_store_set(ls, iter, 0, (gchar *) gs, -1); // } // GtkTreeViewColumn *gtkTreeViewColumnNewWithAttributes(GtkCellRenderer *renderer) // { // /* "" is the column header; "text" associates the text of the column with column 0 */ // return gtk_tree_view_column_new_with_attributes("", renderer, "text", 0, NULL); // } import "C" func fromgtktreemodel(x *C.GtkTreeModel) *C.GtkWidget { return (*C.GtkWidget)(unsafe.Pointer(x)) } func togtktreemodel(what *C.GtkWidget) *C.GtkTreeModel { return (*C.GtkTreeModel)(unsafe.Pointer(what)) } func fromgtktreeview(x *C.GtkTreeView) *C.GtkWidget { return (*C.GtkWidget)(unsafe.Pointer(x)) } func togtktreeview(what *C.GtkWidget) *C.GtkTreeView { return (*C.GtkTreeView)(unsafe.Pointer(what)) } func gListboxNew(multisel bool) *C.GtkWidget { store := C.gtkListStoreNew() widget := C.gtk_tree_view_new_with_model((*C.GtkTreeModel)(unsafe.Pointer(store))) tv := (*C.GtkTreeView)(unsafe.Pointer(widget)) column := C.gtkTreeViewColumnNewWithAttributes(C.gtk_cell_renderer_text_new()) C.gtk_tree_view_column_set_sizing(column, C.GTK_TREE_VIEW_COLUMN_AUTOSIZE) C.gtk_tree_view_column_set_resizable(column, C.FALSE) // not resizeable by the user; just autoresize C.gtk_tree_view_append_column(tv, column) C.gtk_tree_view_set_headers_visible(tv, C.FALSE) sel := C.GTK_SELECTION_SINGLE if multisel { sel = C.GTK_SELECTION_MULTIPLE } C.gtk_tree_selection_set_mode(C.gtk_tree_view_get_selection(tv), C.GtkSelectionMode(sel)) scrollarea := C.gtk_scrolled_window_new((*C.GtkAdjustment)(nil), (*C.GtkAdjustment)(nil)) // thanks to jlindgren in irc.gimp.net/#gtk+ C.gtk_scrolled_window_set_shadow_type((*C.GtkScrolledWindow)(unsafe.Pointer(scrollarea)), C.GTK_SHADOW_IN) C.gtk_container_add((*C.GtkContainer)(unsafe.Pointer(scrollarea)), widget) return scrollarea } func gListboxNewSingle() *C.GtkWidget { return gListboxNew(false) } func gListboxNewMulti() *C.GtkWidget { return gListboxNew(true) } func getTreeViewFrom(widget *C.GtkWidget) *C.GtkTreeView { wid := C.gtk_bin_get_child((*C.GtkBin)(unsafe.Pointer(widget))) return (*C.GtkTreeView)(unsafe.Pointer(wid)) } func gListboxText(widget *C.GtkWidget) string { var model *C.GtkTreeModel var iter C.GtkTreeIter var gs *C.gchar tv := getTreeViewFrom(widget) sel := C.gtk_tree_view_get_selection(tv) if !fromgbool(C.gtk_tree_selection_get_selected(sel, &model, &iter)) { return "" } C.gtkTreeModelGet(model, &iter, &gs) return fromgstr(gs) } func gListboxAppend(widget *C.GtkWidget, what string) { var iter C.GtkTreeIter tv := getTreeViewFrom(widget) ls := (*C.GtkListStore)(unsafe.Pointer(C.gtk_tree_view_get_model(tv))) C.gtk_list_store_append(ls, &iter) cwhat := C.CString(what) defer C.free(unsafe.Pointer(cwhat)) C.gtkListStoreSet(ls, &iter, cwhat) } func gListboxInsert(widget *C.GtkWidget, index int, what string) { var iter C.GtkTreeIter tv := getTreeViewFrom(widget) ls := (*C.GtkListStore)(unsafe.Pointer(C.gtk_tree_view_get_model(tv))) C.gtk_list_store_insert(ls, &iter, C.gint(index)) cwhat := C.CString(what) defer C.free(unsafe.Pointer(cwhat)) C.gtkListStoreSet(ls, &iter, cwhat) } func gListboxSelectedMulti(widget *C.GtkWidget) (indices []int) { var model *C.GtkTreeModel tv := getTreeViewFrom(widget) sel := C.gtk_tree_view_get_selection(tv) rows := C.gtk_tree_selection_get_selected_rows(sel, &model) defer C.g_list_free_full(rows, C.GDestroyNotify(unsafe.Pointer(C.gtk_tree_path_free))) // g_list_length() is O(N), but we need the length below, alas len := C.g_list_length(rows) if len == 0 { return nil } indices = make([]int, len) for i := C.guint(0); i < len; i++ { path := (*C.GtkTreePath)(unsafe.Pointer(rows.data)) idx := C.gtk_tree_path_get_indices(path) indices[i] = int(*idx) rows = rows.next } return indices } func gListboxSelMultiTexts(widget *C.GtkWidget) (texts []string) { var model *C.GtkTreeModel var iter C.GtkTreeIter var gs *C.gchar tv := getTreeViewFrom(widget) sel := C.gtk_tree_view_get_selection(tv) rows := C.gtk_tree_selection_get_selected_rows(sel, &model) defer C.g_list_free_full(rows, C.GDestroyNotify(unsafe.Pointer(C.gtk_tree_path_free))) len := C.g_list_length(rows) if len == 0 { return nil } texts = make([]string, len) for i := C.guint(0); i < len; i++ { path := (*C.GtkTreePath)(unsafe.Pointer(rows.data)) if C.gtk_tree_model_get_iter(model, &iter, path) == C.FALSE { panic("gtk_tree_model_get_iter() failed getting Listbox selected texts; reason unknown") } C.gtkTreeModelGet(model, &iter, &gs) texts[i] = fromgstr(gs) rows = rows.next } return texts } func gListboxDelete(widget *C.GtkWidget, index int) { var iter C.GtkTreeIter tv := getTreeViewFrom(widget) ls := (*C.GtkListStore)(unsafe.Pointer(C.gtk_tree_view_get_model(tv))) if C.gtk_tree_model_iter_nth_child((*C.GtkTreeModel)(unsafe.Pointer(ls)), &iter, (*C.GtkTreeIter)(nil), C.gint(index)) == C.FALSE { panic(fmt.Errorf("error deleting row %d from GTK+ Listbox: no such index or some other error", index)) } C.gtk_list_store_remove(ls, &iter) } // this is a separate function because Combobox uses it too func gtkTreeModelListLen(model *C.GtkTreeModel) int { // "As a special case, if iter is NULL, then the number of toplevel nodes is returned." return int(C.gtk_tree_model_iter_n_children(model, (*C.GtkTreeIter)(nil))) } func gListboxLen(widget *C.GtkWidget) int { tv := getTreeViewFrom(widget) model := C.gtk_tree_view_get_model(tv) return gtkTreeModelListLen(model) }
true
d9c7d9644aa1254c6c0a160a3ab70e9f77c2a4a7
Go
alexclewontin/riverboat
/actions_test.go
UTF-8
11,220
3.078125
3
[ "BSD-2-Clause", "MIT" ]
permissive
[ "BSD-2-Clause", "MIT" ]
permissive
//* Copyright (c) 2020, Alex Lewontin //* All rights reserved. //* //* Redistribution and use in source and binary forms, with or without //* modification, are permitted provided that the following conditions are met: //* //* - Redistributions of source code must retain the above copyright notice, this //* list of conditions and the following disclaimer. //* - Redistributions in binary form must reproduce the above copyright notice, //* this list of conditions and the following disclaimer in the documentation //* and/or other materials provided with the distribution. //* //* THIS SOFTWARE IS PROVIDED 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 riverboat import ( "testing" ) func TestIntegration_Scenarios(t *testing.T) { t.Run("Scenario 1", func(t *testing.T) { g := NewGame() pn_a := g.AddPlayer() g.AddPlayer() g.AddPlayer() err := Deal(g, pn_a, 0) if err != ErrIllegalAction { t.Error("Test failed - Deal must return ErrIllegalAction as 0 players are marked ready.") } }) t.Run("Scenario 2", func(t *testing.T) { g := NewGame() pn_a := g.AddPlayer() g.AddPlayer() g.AddPlayer() err := ToggleReady(g, pn_a, 0) if err != ErrIllegalAction { t.Error("Test failed - ToggleReady must return ErrIllegalAction as player 0 has not bought in.") } }) t.Run("Scenario 3", func(t *testing.T) { var err error g := NewGame() pn_a := g.AddPlayer() pn_b := g.AddPlayer() pn_c := g.AddPlayer() err = BuyIn(g, pn_a, 100) if err != nil { t.Errorf("Test failed - Error buying in: %s", err) } err = BuyIn(g, pn_b, 100) if err != nil { t.Errorf("Test failed - Error buying in: %s", err) } err = BuyIn(g, pn_c, 100) if err != nil { t.Errorf("Test failed - Error buying in: %s", err) } err = ToggleReady(g, pn_a, 0) if err != nil { t.Errorf("Test failed - Error marking ready: %s", err) } err = ToggleReady(g, pn_b, 0) if err != nil { t.Errorf("Test failed - Error marking ready: %s", err) } err = ToggleReady(g, pn_c, 0) if err != nil { t.Errorf("Test failed - Error marking ready: %s", err) } err = Deal(g, pn_a, 0) if err != nil { t.Errorf("Test failed - error dealing: %s", err) } }) t.Run("Scenario 4", func(t *testing.T) { var err error g := NewGame() pn_a := g.AddPlayer() pn_b := g.AddPlayer() pn_c := g.AddPlayer() err = BuyIn(g, pn_a, 100) if err != nil { t.Errorf("Test failed - Error buying in: %s", err) } err = BuyIn(g, pn_b, 100) if err != nil { t.Errorf("Test failed - Error buying in: %s", err) } err = BuyIn(g, pn_c, 100) if err != nil { t.Errorf("Test failed - Error buying in: %s", err) } err = ToggleReady(g, pn_a, 0) if err != nil { t.Errorf("Test failed - Error marking ready: %s", err) } err = ToggleReady(g, pn_b, 0) if err != nil { t.Errorf("Test failed - Error marking ready: %s", err) } err = ToggleReady(g, pn_c, 0) if err != nil { t.Errorf("Test failed - Error marking ready: %s", err) } err = Deal(g, pn_b, 0) if err != ErrIllegalAction { t.Errorf("Test failed - must return ErrIllegalAction as pn_b is not the dealer") } }) t.Run("Scenario 5", func(t *testing.T) { var err error g := NewGame() pn_a := g.AddPlayer() pn_b := g.AddPlayer() pn_c := g.AddPlayer() err = BuyIn(g, pn_a, 100) if err != nil { t.Errorf("Test failed - Error buying in: %s", err) } err = BuyIn(g, pn_b, 100) if err != nil { t.Errorf("Test failed - Error buying in: %s", err) } err = BuyIn(g, pn_c, 100) if err != nil { t.Errorf("Test failed - Error buying in: %s", err) } err = ToggleReady(g, pn_a, 0) if err != nil { t.Errorf("Test failed - Error marking ready: %s", err) } err = ToggleReady(g, pn_b, 0) if err != nil { t.Errorf("Test failed - Error marking ready: %s", err) } err = ToggleReady(g, pn_c, 0) if err != nil { t.Errorf("Test failed - Error marking ready: %s", err) } err = Deal(g, pn_a, 0) if err != nil { t.Errorf("Test failed - error dealing: %s", err) } err = Bet(g, pn_a, 25) if err != nil { t.Errorf("Test failed - error betting: %s", err) } if g.players[pn_a].Bet != 25 { t.Errorf("Betting mechanic not working.") } }) t.Run("Scenario 6 simple", func(t *testing.T) { var err error g := NewGame() pn_a := g.AddPlayer() pn_b := g.AddPlayer() pn_c := g.AddPlayer() err = BuyIn(g, pn_a, 100) if err != nil { t.Errorf("Test failed - Error buying in: %s", err) } err = BuyIn(g, pn_b, 100) if err != nil { t.Errorf("Test failed - Error buying in: %s", err) } err = BuyIn(g, pn_c, 100) if err != nil { t.Errorf("Test failed - Error buying in: %s", err) } err = ToggleReady(g, pn_a, 0) if err != nil { t.Errorf("Test failed - Error marking ready: %s", err) } err = ToggleReady(g, pn_b, 0) if err != nil { t.Errorf("Test failed - Error marking ready: %s", err) } err = ToggleReady(g, pn_c, 0) if err != nil { t.Errorf("Test failed - Error marking ready: %s", err) } // Preflop err = Deal(g, pn_a, 0) if err != nil { t.Errorf("Test failed - error dealing: %s", err) } err = Bet(g, pn_a, 25) if err != nil { t.Errorf("Test failed - error betting: %s", err) } err = Bet(g, pn_b, 15) if err != nil { t.Errorf("Test failed - error betting: %s", err) } err = Bet(g, pn_c, 0) if err != nil { t.Errorf("Test failed - error betting: %s", err) } // Flop err = Bet(g, pn_b, 25) if err != nil { t.Errorf("Test failed - error betting: %s", err) } err = Bet(g, pn_c, 25) if err != nil { t.Errorf("Test failed - error betting: %s", err) } err = Bet(g, pn_a, 25) if err != nil { t.Errorf("Test failed - error betting: %s", err) } // Turn err = Bet(g, pn_b, 0) if err != nil { t.Errorf("Test failed - error betting: %s", err) } err = Bet(g, pn_c, 0) if err != nil { t.Errorf("Test failed - error betting: %s", err) } err = Bet(g, pn_a, 0) if err != nil { t.Errorf("Test failed - error betting: %s", err) } //River err = Bet(g, pn_b, 0) if err != nil { t.Errorf("Test failed - error betting: %s", err) } err = Bet(g, pn_c, 0) if err != nil { t.Errorf("Test failed - error betting: %s", err) } err = Bet(g, pn_a, 0) if err != nil { t.Errorf("Test failed - error betting: %s", err) } }) t.Run("Scenario 7 fold", func(t *testing.T) { var err error g := NewGame() pn_a := g.AddPlayer() pn_b := g.AddPlayer() pn_c := g.AddPlayer() err = BuyIn(g, pn_a, 100) if err != nil { t.Errorf("Test failed - Error buying in: %s", err) } err = BuyIn(g, pn_b, 100) if err != nil { t.Errorf("Test failed - Error buying in: %s", err) } err = BuyIn(g, pn_c, 100) if err != nil { t.Errorf("Test failed - Error buying in: %s", err) } err = ToggleReady(g, pn_a, 0) if err != nil { t.Errorf("Test failed - Error marking ready: %s", err) } err = ToggleReady(g, pn_b, 0) if err != nil { t.Errorf("Test failed - Error marking ready: %s", err) } err = ToggleReady(g, pn_c, 0) if err != nil { t.Errorf("Test failed - Error marking ready: %s", err) } // Preflop err = Deal(g, pn_a, 0) if err != nil { t.Errorf("Test failed - error dealing: %s", err) } err = Bet(g, pn_a, 25) if err != nil { t.Errorf("Test failed - error betting: %s", err) } err = Bet(g, pn_b, 15) if err != nil { t.Errorf("Test failed - error betting: %s", err) } err = Bet(g, pn_c, 0) if err != nil { t.Errorf("Test failed - error betting: %s", err) } // Flop err = Bet(g, pn_b, 25) if err != nil { t.Errorf("Test failed - error betting: %s", err) } err = Fold(g, pn_c, 0) if err != nil { t.Errorf("Test failed - error betting: %s", err) } err = Bet(g, pn_a, 25) if err != nil { t.Errorf("Test failed - error betting: %s", err) } // Turn err = Bet(g, pn_b, 0) if err != nil { t.Errorf("Test failed - error betting: %s", err) } err = Bet(g, pn_a, 0) if err != nil { t.Errorf("Test failed - error betting: %s", err) } //River err = Bet(g, pn_b, 0) if err != nil { t.Errorf("Test failed - error betting: %s", err) } err = Bet(g, pn_a, 0) if err != nil { t.Errorf("Test failed - error betting: %s", err) } }) t.Run("Scenario 8 reraise", func(t *testing.T) { var err error g := NewGame() pn_a := g.AddPlayer() pn_b := g.AddPlayer() pn_c := g.AddPlayer() err = BuyIn(g, pn_a, 100) if err != nil { t.Errorf("Test failed - Error buying in: %s", err) } err = BuyIn(g, pn_b, 100) if err != nil { t.Errorf("Test failed - Error buying in: %s", err) } err = BuyIn(g, pn_c, 100) if err != nil { t.Errorf("Test failed - Error buying in: %s", err) } err = ToggleReady(g, pn_a, 0) if err != nil { t.Errorf("Test failed - Error marking ready: %s", err) } err = ToggleReady(g, pn_b, 0) if err != nil { t.Errorf("Test failed - Error marking ready: %s", err) } err = ToggleReady(g, pn_c, 0) if err != nil { t.Errorf("Test failed - Error marking ready: %s", err) } // Preflop err = Deal(g, pn_a, 0) if err != nil { t.Errorf("Test failed - error dealing: %s", err) } err = Bet(g, pn_a, 25) if err != nil { t.Errorf("Test failed - error betting: %s", err) } err = Bet(g, pn_b, 15) if err != nil { t.Errorf("Test failed - error betting: %s", err) } err = Bet(g, pn_c, 0) if err != nil { t.Errorf("Test failed - error betting: %s", err) } // Flop err = Bet(g, pn_b, 25) if err != nil { t.Errorf("Test failed - error betting: %s", err) } err = Fold(g, pn_c, 0) if err != nil { t.Errorf("Test failed - error betting: %s", err) } err = Bet(g, pn_a, 50) if err != nil { t.Errorf("Test failed - error betting: %s", err) } err = Bet(g, pn_b, 25) if err != nil { t.Errorf("Test failed - error betting: %s", err) } // Turn err = Bet(g, pn_b, 0) if err != nil { t.Errorf("Test failed - error betting: %s", err) } err = Bet(g, pn_a, 0) if err != nil { t.Errorf("Test failed - error betting: %s", err) } //River err = Bet(g, pn_b, 0) if err != nil { t.Errorf("Test failed - error betting: %s", err) } err = Bet(g, pn_a, 0) if err != nil { t.Errorf("Test failed - error betting: %s", err) } }) }
true
2c6ed024286b5fe0e31e53901ee7806d052e4532
Go
RyanCarrier/GoBenchmarkTalk
/EverythingWillWOrk/main.go
UTF-8
314
2.875
3
[]
no_license
[]
no_license
package main import "fmt" func main() { set := []int{0, 1, 2, 3, 4, 5, 6} fmt.Println(set, len(set), cap(set)) set = set[0:5] set := append([]int{}, set[0:5]...) var set2 []int{} copy(set2,set[0:5]) fmt.Println(set, len(set), cap(set)) //fmt.Println(set[5]) clone := set[0:6] fmt.Println(clone[5]) }
true
2b3ef3cc1047826c676dc55326c228939ea7904c
Go
mobil-mit-stil/backend
/storage/memory/passenger.go
UTF-8
1,931
2.671875
3
[]
no_license
[]
no_license
package memory import ( "backend/storage" "fmt" "sync" ) var passengerStorage map[storage.SessionUUId]*storage.Passenger var passengerMutex sync.Mutex func initPassengerStorage() { passengerStorage = make(map[storage.SessionUUId]*storage.Passenger, 0) } func (m *Provider) SelectPassenger(passenger *storage.Passenger) error { passengerMutex.Lock() defer passengerMutex.Unlock() dbPassenger, ok := passengerStorage[passenger.Session.Id] if !ok { return fmt.Errorf("passenger not found") } *passenger = *dbPassenger return nil } func (m *Provider) SelectPassengers(passengers *[]*storage.Passenger) error { passengerMutex.Lock() defer passengerMutex.Unlock() for _, passenger := range passengerStorage { *passengers = append(*passengers, passenger) } return nil } func (m *Provider) InsertPassenger(passenger *storage.Passenger) error { passengerMutex.Lock() passengerStorage[passenger.Session.Id] = passenger passengerMutex.Unlock() drivers := make([]*storage.Driver, 0) err := m.SelectDrivers(&drivers) if err != nil { return err } for _, driver := range drivers { m.updateRoutine(driver, passenger) } return nil } func (m *Provider) UpdatePassenger(passenger *storage.Passenger) error { passengerMutex.Lock() passengerStorage[passenger.Session.Id] = passenger passengerMutex.Unlock() drivers := make([]*storage.Driver, 0) err := m.SelectDrivers(&drivers) if err != nil { return err } for _, driver := range drivers { m.updateRoutine(driver, passenger) } return nil } func (m *Provider) DeletePassenger(passenger *storage.Passenger) error { passengerMutex.Lock() defer passengerMutex.Unlock() err := m.deletePassengerAssociatedMappings(passenger.UserId) if err != nil { return err } user := storage.NewUser().WithUserId(passenger.UserId) err = user.Delete() if err != nil { return err } delete(passengerStorage, passenger.Session.Id) return nil }
true
68bb0e95ac0e46366ad811dde41876ae32bdcd3e
Go
dewey363/record
/src/record/log/log.go
UTF-8
676
2.984375
3
[]
no_license
[]
no_license
package log import ( "log" "os" "strconv" "time" ) var logs *log.Logger var Prefix = "[Debug]" func init() { if logs == nil { now := time.Now() logName := strconv.Itoa(now.Year()) + "-" + now.Month().String() + "-" + strconv.Itoa(now.Day()) fileInfo, err := os.Stat("log" + logName + ".log") if err == nil { file, _ := os.Open(fileInfo.Name()) logs = log.New(file, Prefix, log.Ltime) } else { file, _ := os.Create("log-" + logName + ".log") logs = log.New(file, Prefix, log.Ltime) } } } func SetPrefix(prefix string) { Prefix = prefix return } func Fatal(v interface{}) { logs.Fatalln(v) } func Info(v interface{}) { logs.Println(v) }
true
71a690ed638d67cc6af70da7cb47e5db72db0e10
Go
dickynovanto1103/GolangExperiments
/goconcurrency/main.go
UTF-8
2,510
3.171875
3
[]
no_license
[]
no_license
package main import ( "fmt" "log" "os" "runtime" "time" ) func exp1() { ch := make(chan int) go func() { fmt.Println("hello world1") ch <- 1 }() go func() { fmt.Println("hello world") }() go func() { fmt.Println("hello world2") }() //go func() { // fmt.Println("hello world3") //}() val := <-ch fmt.Println("val:", val) } func exp2() { fmt.Println("main start") go func() { i := 0 for { fmt.Println(i) i++ } }() time.Sleep(2*time.Millisecond) fmt.Println("main ends") time.Sleep(1*time.Second) } func CanWeDoParallelOperation() { now := time.Now() threads := runtime.GOMAXPROCS(0) bil := int32(0) ch := make(chan int, threads) for i := 0; i < threads; i++ { go func(threadNum int) { //log.Println("processong thread num:", threadNum) for i := 0; i < 100000000; i++ { //atomic.AddInt32(&bil, 1) bil++ } //log.Printf("thread num: %v done\n", threadNum) ch <- 1 }(i) } for i:=0;i<threads;i++ { log.Println("done: ", i) <-ch } log.Println("totBil: ", bil) log.Println("time elapsed: ", time.Since(now)) } func SerialAdd() { now := time.Now() var bil int32 = 0 threads := runtime.GOMAXPROCS(0) for i:=0;i<threads;i++ { for j:=0;j<100000000;j++ { //atomic.AddInt32(&bil, 1) bil++ } } log.Println("bil final: ", bil) log.Println("time elapsed: ", time.Since(now)) } var n = 100000000 var arr1 = make([]int, n) var arr2 = make([]int, n) var sum = make([]int, n) func SumParallel(n int) { now := time.Now() threads := runtime.GOMAXPROCS(0) ch := make(chan int) //wg := sync.WaitGroup{} //wg.Add(threads) for i:=0;i<threads;i++ { go func(awal, akhir int) { for i:=awal;i<akhir;i++ { sum[i] = arr1[i] + arr2[i] } ch <- 1 //wg.Done() }(i*n/threads, (i+1)*n/threads) } //wg.Wait() for i:=0;i<threads;i++ { <-ch } log.Println("parallel: ", time.Since(now)) } func SumSerial(n int) { now := time.Now() for i:=0;i<n;i++{ sum[i] = arr1[i] + arr2[i] } log.Println("serial: ", time.Since(now)) } func gen(n int) { for i:=0;i<n;i++ { arr1[i] = i arr2[i] = i } } func say(s string) { for i:=0;i<5;i++ { runtime.Gosched() fmt.Println(s) } } func GoShed() { runtime.GOMAXPROCS(0) val := os.Getenv("GOMAXPROCS") log.Println("GOMAXPROCS: ", val) go say("hello") say("world") //fmt.Println("hello") } func main() { //exp1() //exp2() gen(n) log.Println("done") SumSerial(n) SumParallel(n) //CanWeDoParallelOperation() //SerialAdd() //GoShed() }
true
8a74f5f874c2c63f07d76882c38582051d5d6beb
Go
YashishDua/go-bangalore-meetup-46
/context_two.go
UTF-8
1,208
3.546875
4
[]
no_license
[]
no_license
package main import ( "context" "fmt" "time" ) func main() { timeout := 3 * time.Second deadline := time.Now().Add(10 * time.Second) timeOutContext, _ := context.WithTimeout(context.Background(), timeout) cancelContext, cancel := context.WithCancel(context.Background()) deadlineContext, _ := context.WithDeadline(context.Background(), deadline) go contextDemo(context.WithValue(timeOutContext, "name", "[timeoutContext]")) go contextDemo(context.WithValue(cancelContext, "name", "[cancelContext]")) go contextDemo(context.WithValue(deadlineContext, "name", "[deadlineContext]")) // Wait for the timeout to expire <- timeOutContext.Done() fmt.Println("Cancelling the cancel context...") cancel() <- cancelContext.Done() fmt.Println("The cancel context has been cancelled...") <- deadlineContext.Done() fmt.Println("The deadline context has been cancelled...") } func contextDemo(ctx context.Context) { deadline, ok := ctx.Deadline() name := ctx.Value("name") for { if ok { fmt.Println(name, "will expire at:", deadline) } else { fmt.Println(name, "has no deadline") } time.Sleep(time.Second) } }
true
a3066b9d8eaf9cacee09d37bb2a9a8c82e2c937c
Go
jacoblai/gowxjqr
/src/wx/jiaMiJieMi.go
UTF-8
3,323
2.953125
3
[]
no_license
[]
no_license
package wx import ( "bytes" "compress/zlib" "crypto/aes" "crypto/cipher" "crypto/md5" "crypto/rand" "crypto/rsa" "encoding/hex" "fmt" "math/big" mrand "math/rand" "strings" "time" ) //RandomStr 随机生成字符串 func RandomStr(length int) []byte { str := "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" bytes := []byte(str) result := []byte{} r := mrand.New(mrand.NewSource(time.Now().UnixNano())) for i := 0; i < length; i++ { result = append(result, bytes[r.Intn(len(bytes))]) } return result } func GetMd5(src string) string { data := []byte(strings.TrimSpace(src)) has := md5.Sum(data) ret := fmt.Sprintf("%x", has) //将[]byte转成16进制 return ret } // 进行zlib压缩 func DoZlibCompress(src []byte) []byte { var in bytes.Buffer w := zlib.NewWriter(&in) w.Write(src) w.Close() return in.Bytes() } func fromBase10(base10 string) *big.Int { i, ok := new(big.Int).SetString(base10, 10) if !ok { return big.NewInt(0) } return i } func CheckErr(err error) { if err != nil { panic(err) } } func PKCS1v15(raw string, k *rsa.PrivateKey) { // 加密数据 encData, err := rsa.EncryptPKCS1v15(rand.Reader, &k.PublicKey, []byte(raw)) CheckErr(err) // 将加密信息转换为16进制 fmt.Println(hex.EncodeToString(encData)) // 解密数据 decData, err := rsa.DecryptPKCS1v15(rand.Reader, k, encData) CheckErr(err) fmt.Println(string(decData)) } // RSA算法加密 func RsaEncrypt(origData []byte) ([]byte, error) { pub := &rsa.PublicKey{ N: fromBase10("28451871049931367000280397980315941493900129515342596978911559687990314360389032587440776677027204713391568456885285049251487633608731647183467169168881911527826624481487591327384831906488048909401577611922812327263514418984933031922276030058409673698944286410157636442703854841054883577764295855609055424607908529646258978732803548772153882771376598661378357620270911570592259824592983240228765987019924029891220246156951679001803386278265765263294008064317769795655401414404284566271952991617207133906501324250043672867665318381453808219063463146255586300194092972814576468544100433701118961141427623372047206165351"), E: 65537, } return rsa.EncryptPKCS1v15(rand.Reader, pub, origData) } // 先压缩后RSA加密 func CompressAndRsaEnc(origData []byte) ([]byte, error) { compressData := DoZlibCompress(origData) return RsaEncrypt(compressData) } // AesCbc加密 func AesCbcEncrypt(plantText, key []byte) ([]byte, error) { block, err := aes.NewCipher(key) //选择加密算法 if err != nil { return nil, err } plantText = PKCS7Padding(plantText, block.BlockSize()) blockModel := cipher.NewCBCEncrypter(block, key) ciphertext := make([]byte, len(plantText)) blockModel.CryptBlocks(ciphertext, plantText) return ciphertext, nil } func PKCS7Padding(ciphertext []byte, blockSize int) []byte { padding := blockSize - len(ciphertext)%blockSize padtext := bytes.Repeat([]byte{byte(padding)}, padding) return append(ciphertext, padtext...) } // 先压缩后AES-128-CBC加密 func CompressAndAesEnc(plantText, key []byte) ([]byte, error) { compressData := DoZlibCompress(plantText) return AesCbcEncrypt(compressData, key) } /*func main() { encData, _ := CompressAndRsaEnc([]byte("0")) fmt.Println(encData) fmt.Println(hex.EncodeToString(encData)) return }*/
true
97c54de7696b409f2ae3b0d898b4571d41020f72
Go
fidellr/edu_malay
/teacher/delivery/http/profile.go
UTF-8
2,887
2.78125
3
[]
no_license
[]
no_license
package http import ( "context" "net/http" "strconv" "github.com/fidellr/edu_malay/model" teacherModel "github.com/fidellr/edu_malay/model/teacher" "github.com/fidellr/edu_malay/teacher" "github.com/fidellr/edu_malay/utils" "github.com/labstack/echo" ) type Handler struct { service teacher.ProfileUsecase } func NewTeacherProfileHandler(e *echo.Echo, service teacher.ProfileUsecase) { handler := &Handler{ service, } e.GET("/teachers", handler.FindAll) e.GET("/teacher/:id", handler.GetByID) e.POST("/teacher", handler.Create) e.PUT("/teacher/:id", handler.Update) e.POST("/teacher/:id", handler.Remove) } func (h *Handler) FindAll(c echo.Context) error { var num int var err error ctx := c.Request().Context() if ctx == nil { ctx = context.Background() } if c.QueryParam("num") != "" { num, err = strconv.Atoi(c.QueryParam("num")) if err != nil { return utils.ConstraintErrorf("%s", err.Error()) } } filter := &model.Filter{ Num: num, Cursor: c.QueryParam("cursor"), Search: c.QueryParam("search"), } teachers, nextCursor, err := h.service.FindAll(ctx, filter) if err != nil { return utils.ConstraintErrorf("%s", err.Error()) } c.Response().Header().Set("X-Cursor", nextCursor) return c.JSON(http.StatusOK, teachers) } func (h *Handler) Create(c echo.Context) error { ctx := c.Request().Context() if ctx == nil { ctx = context.Background() } t := new(teacherModel.ProfileEntity) if err := c.Bind(t); err != nil { return c.JSON(utils.GetStatusCode(err), model.ResponseError{Message: err.Error()}) } err := h.service.Create(ctx, t) if err != nil { return c.JSON(utils.GetStatusCode(err), model.ResponseError{Message: err.Error()}) } return c.NoContent(http.StatusOK) } func (h *Handler) GetByID(c echo.Context) error { ctx := c.Request().Context() if ctx == nil { ctx = context.Background() } t, err := h.service.GetByID(ctx, c.Param("id")) if err != nil { return c.JSON(utils.GetStatusCode(err), model.ResponseError{Message: err.Error()}) } return c.JSON(utils.GetStatusCode(err), t) } func (h *Handler) Update(c echo.Context) error { ctx := c.Request().Context() if ctx == nil { ctx = context.Background() } t := new(teacherModel.ProfileEntity) if err := c.Bind(t); err != nil { return c.JSON(utils.GetStatusCode(err), model.ResponseError{Message: err.Error()}) } err := h.service.Update(ctx, c.Param("id"), t) if err != nil { return c.JSON(utils.GetStatusCode(err), model.ResponseError{Message: err.Error()}) } return c.NoContent(http.StatusOK) } func (h *Handler) Remove(c echo.Context) error { ctx := c.Request().Context() if ctx == nil { ctx = context.Background() } err := h.service.Remove(ctx, c.Param("id")) if err != nil { return c.JSON(utils.GetStatusCode(err), model.ResponseError{Message: err.Error()}) } return c.NoContent(http.StatusOK) }
true
82b0b9d70fcf5f3441bfdcebbe12f9ccf65a231f
Go
cfstras/cfmedias
/db/item.go
UTF-8
1,381
2.53125
3
[ "BSD-2-Clause", "LicenseRef-scancode-unknown-license-reference" ]
permissive
[ "BSD-2-Clause", "LicenseRef-scancode-unknown-license-reference" ]
permissive
package db import ( "github.com/cfstras/cfmedias/core" "github.com/cfstras/cfmedias/util" ) func (db *DB) GetItem(args core.ArgMap) ([]Item, error) { // check if necessary args are there var err error title, err := util.GetArg(args, "title", true, err) artist, err := util.GetArg(args, "artist", true, err) album, err := util.GetArg(args, "album", false, err) album_artist, err := util.GetArg(args, "album_artist", false, err) //musicbrainz_id, err := util.GetArg(args, "musicbrainz_id", false, err) if err != nil { return nil, err } limit := map[string]interface{}{"title": title, "artist": artist} if album != nil { limit["album"] = album } if album_artist != nil && false { //TODO album-artists are not implemented yet limit["album_artist"] = album_artist } //TODO mbid is not implemented. If given, only search mbid. /*if musicbrainz_id != nil { limit["musicbrainz_id"] = musicbrainz_id }*/ tracks := make([]Item, 0) err = db.db.Where(limit).Find(tracks).Error if err != nil { return nil, err } return tracks, nil } func InterfaceToItemSlice(slice []interface{}) []Item { items := make([]Item, len(slice)) for i, v := range slice { items[i] = v.(Item) } return items } func ItemToInterfaceSlice(slice []Item) []interface{} { items := make([]interface{}, len(slice)) for i, v := range slice { items[i] = v } return items }
true
0fe964e351d8930a4f51714c3dd5373070b10338
Go
snoronha/pam
/lib/compare.go
UTF-8
10,636
2.59375
3
[ "MIT" ]
permissive
[ "MIT" ]
permissive
package lib import ( "bufio" "fmt" "log" "os" "regexp" "sort" "strconv" "strings" "time" ) func CompareAllAnomsWithEDNAAnoms() { oldLongForm := "2006-01-02 15:04:05+00:00" newLongForm := "2006-01-02 15:04:05 +0000 UTC" oldFileName := "/Users/sanjaynoronha/Desktop/all_anoms_feb2015.csv" newFileName := "/Users/sanjaynoronha/Desktop/edna_out.txt" // oldFileName := "/Users/sanjaynoronha/Desktop/all_anoms_811635.csv" // newFileName := "/Users/sanjaynoronha/Desktop/edna_811635.txt" oldMap := make(map[string]map[string]map[string]map[string]string) newMap := make(map[string]map[string]map[string]map[string]string) // create oldMap: oldMap[feederId][anomalyType][ts] = line startTime := time.Now() fdrRegexp, _ := regexp.Compile(`\.([0-9]{6})[\._]`) phaseRegexp, _ := regexp.Compile(`\.([ABC\-])_PH`) loc, _ := time.LoadLocation("America/New_York") goodCount, badCount := 0, 0 startTime = time.Now() if newFile, err := os.Open(newFileName); err == nil { defer newFile.Close() numLines := 0 newScanner := bufio.NewScanner(newFile) for newScanner.Scan() { line := newScanner.Text() lineComponents := strings.Split(line, ",") if len(lineComponents) >= 2 { numLines++ extendedId := lineComponents[1] anomalyType := lineComponents[0] feederIdMatches := fdrRegexp.FindStringSubmatch(extendedId) feederId := "" if len(feederIdMatches) > 0 { feederId = feederIdMatches[1] } phaseMatches := phaseRegexp.FindStringSubmatch(extendedId) phase := "-" if len(phaseMatches) > 0 { phase = phaseMatches[1] } ts, _ := time.Parse(newLongForm, lineComponents[3]) epochTs := strconv.FormatInt(ts.Unix(), 10) if _, ok := newMap[feederId]; !ok { newMap[feederId] = map[string]map[string]map[string]string{} } if _, ok := newMap[feederId][anomalyType]; !ok { newMap[feederId][anomalyType] = map[string]map[string]string{} } if _, ok := newMap[feederId][anomalyType][phase]; !ok { newMap[feederId][anomalyType][phase] = map[string]string{} } if _, ok := newMap[feederId][anomalyType][phase][epochTs]; !ok { newMap[feederId][anomalyType][phase][epochTs] = line } if numLines % 1000000 == 0 { fmt.Printf("%d: type:%s feederId:%s line:[%s] epochTs:%s\n", numLines, anomalyType, feederId, line, epochTs) } } } elapsed := time.Since(startTime) fmt.Printf("{numLines: %d, elapsed: %s}\n", numLines, elapsed) // check for errors if err = newScanner.Err(); err != nil { log.Fatal(err) } } else { log.Fatal(err) } if oldFile, err := os.Open(oldFileName); err == nil { defer oldFile.Close() numLines := 0 oldScanner := bufio.NewScanner(oldFile) for oldScanner.Scan() { line := oldScanner.Text() lineComponents := strings.Split(line, ",") if len(lineComponents) >= 7 { numLines++ extendedId := lineComponents[6] _ = extendedId anomalyType := lineComponents[1] phase := lineComponents[3] feederId := lineComponents[5] ts, _ := time.Parse(oldLongForm, lineComponents[7]) _, offset := ts.In(loc).Zone() ts = ts.Add(time.Duration(offset) * time.Second) // timestamps are ET, convert to UTC epochTs := strconv.FormatInt(ts.Unix(), 10) if _, ok := oldMap[feederId]; !ok { oldMap[feederId] = map[string]map[string]map[string]string{} } if _, ok := oldMap[feederId][anomalyType]; !ok { oldMap[feederId][anomalyType] = map[string]map[string]string{} } if _, ok := oldMap[feederId][anomalyType][phase]; !ok { oldMap[feederId][anomalyType][phase] = map[string]string{} } if _, ok := oldMap[feederId][anomalyType][phase][epochTs]; !ok { oldMap[feederId][anomalyType][phase][epochTs] = line } if _, ok := newMap[feederId][anomalyType][phase][epochTs]; ok { goodCount++ } else { badCount++ if badCount % 1 == 0 { // fmt.Printf("BAD: %d type:%s phase:%s [%s] epochTs:%s\n", numLines, anomalyType, phase, line, epochTs) } } if numLines % 1000000 == 0 { fmt.Printf("%d: type:%s [%s] epochTs:%s\n", numLines, anomalyType, line, epochTs) } } } elapsed := time.Since(startTime) fmt.Printf("{numLines: %d, goodCount: %d, badCount: %d, elapsed: %s}\n", numLines, goodCount, badCount, elapsed) var feederIds []string for feederId := range newMap { feederIds = append(feederIds, feederId) } sort.Strings(feederIds) for _, feederId := range feederIds { for fault := range newMap[feederId] { for phase := range newMap[feederId][fault] { oldCount := len(oldMap[feederId][fault][phase]) newCount := len(newMap[feederId][fault][phase]) var absDiff int = 0 if oldCount > newCount { absDiff = oldCount - newCount } else { absDiff = newCount - oldCount } if absDiff >= 100 { fmt.Printf("[%s][%s][%s] = {old:%d, new:%d]\n", feederId, fault, phase, oldCount, newCount) } } } } // check for errors if err = oldScanner.Err(); err != nil { log.Fatal(err) } } else { log.Fatal(err) } } // e.g. fileName = "/Users/<username>/edna_monthly", extension = ".csv" func SortMergeAnomalyFile(newFilePath string, newExtension string, oldFilePath string, oldExtension string) { var anomObjects []Anomaly numLines := 0 newLongForm := "2006-01-02 15:04:05 +0000 UTC" newFileName := newFilePath + newExtension oldLongForm := "2006-01-02 15:04:05+00:00" oldFileName := oldFilePath + oldExtension // Read, parse new file if newFile, err := os.Open(newFileName); err == nil { // make sure it gets closed defer newFile.Close() scanner := bufio.NewScanner(newFile) for scanner.Scan() { line := scanner.Text() lineComponents := strings.Split(line, ",") if len(lineComponents) >= 5 { anom := new(Anomaly) // 0,FCI_FAULT_ALARM,673113B,B,FCI,806731,IVES.806731.FCI.673113B.FAULT.B_PH,1,2013-12-05 15:41:26 +0000 UTC anom.Id = lineComponents[0] anom.Anomaly = lineComponents[1] anom.DeviceId = lineComponents[2] anom.DevicePhase = lineComponents[3] anom.DeviceType = lineComponents[4] anom.FeederId = lineComponents[5] anom.Signal = lineComponents[6] anom.Value = lineComponents[7] anom.Time = lineComponents[8] evntTs, _ := time.Parse(newLongForm, anom.Time) anom.EpochTime = evntTs.Unix() anomObjects = append(anomObjects, *anom) if numLines % 1000000 == 0 { fmt.Printf("%d\tnew %s epoch: %d\n", numLines, anom.Time, anom.EpochTime) } numLines++ } } } else { log.Fatal(err) } fmt.Printf("NumLines: %d\n", numLines) // Read, parse old file if oldFile, err := os.Open(oldFileName); err == nil { // make sure it gets closed defer oldFile.Close() scanner := bufio.NewScanner(oldFile) for scanner.Scan() { line := scanner.Text() lineComponents := strings.Split(line, ",") if len(lineComponents) >= 5 { anom := new(Anomaly) anom.Id = lineComponents[0] anom.Anomaly = lineComponents[1] anom.DeviceId = lineComponents[2] anom.DevicePhase = lineComponents[3] anom.DeviceType = lineComponents[4] anom.FeederId = lineComponents[5] anom.Signal = lineComponents[6] anom.Value = "0" anom.Time = lineComponents[7] evntTs, _ := time.Parse(oldLongForm, anom.Time) anom.EpochTime = evntTs.Unix() anom.Time = fmt.Sprintf("%s", evntTs) anomObjects = append(anomObjects, *anom) if numLines % 100000 == 0 { fmt.Printf("%d\told %s epoch: %d\n", numLines, anom.Time, anom.EpochTime) } numLines++ } } } else { log.Fatal(err) } sort.Slice(anomObjects, func(i, j int) bool { return anomObjects[i].EpochTime < anomObjects[j].EpochTime }) fmt.Printf("Sorting done!\n") // Write out sorted, merged files oFileName := newFilePath + "_merged" + newExtension var writer *bufio.Writer if ofile, err := os.Create(oFileName); err == nil { defer ofile.Close() writer = bufio.NewWriter(ofile) } else { log.Fatal(err) } line := "" for _, anom := range anomObjects { line = anom.Id + "," + anom.Anomaly + "," + anom.DeviceId + "," + anom.DevicePhase + "," + anom.DeviceType + "," + anom.FeederId + "," + anom.Signal + "," + anom.Value + "," + anom.Time writer.WriteString(fmt.Sprintf("%s\n", line)) } writer.Flush() }
true
d989e60be283d29219181e2ee5e46f8059813233
Go
ArtemBond13/hw2.3
/pkg/stats/stats.go
UTF-8
2,461
3.578125
4
[]
no_license
[]
no_license
package stats import ( "fmt" "sort" "sync" "time" ) // type Transaction struct { Id string From string To string Amount int64 Created int64 } // "Часть" хранит номер месяца и указатель на транкзакцию type part struct { monthTimestamp int64 // Метка времени месяца transactions []*Transaction } func Sum(transactions []int64) int64 { result := int64(0) for _, transaction := range transactions { result += transaction } return result } func SumConcurrently(transactions []int64, goroutines int) int64 { wg := sync.WaitGroup{} wg.Add(goroutines) total := int64(0) partSize := len(transactions) / goroutines for i := 0; i < goroutines; i++ { part := transactions[i*partSize : (i+1)*partSize] go func() { total += Sum(part) // FIXME: shared memory bug, discuss later wg.Done() }() } wg.Wait() return total } func SumConcurrentlyMonth(start, finish time.Time) int64 { // слайс с указателем на структуру part, len и cap = 0 months := make([]*part, 0) // Опрделить сколько месяцев next := start for next.Before(finish) { // пока next != finish months = append(months, &part{monthTimestamp: next.Unix()}) // добавить в мвссив отметку времени next = next.AddDate(0, 1, 0) // next прибавляем 1 месяц } months = append(months, &part{monthTimestamp: finish.Unix()}) // создаем для транкзаций transactions := make([]*Transaction, 0) // TODO: заполняете transactions for i, transaction := range transactions { // TODO: находите нужный месяц для совпадения month := months[i] month.transactions = append(month.transactions, transaction) } wg := sync.WaitGroup{} total := int64(0) for _, i := range transactions { wg.Add(1) i := i go func() { fmt.Println("start") total += i.Amount // FIXME: shared memory bug, discuss later wg.Done() }() } wg.Wait() return total } func SortSlice(transactions []int64) []int64 { sort.Slice(transactions, func(i, j int) bool { return transactions[i] > transactions[j] }) return transactions } func SortSliceStable(transactions []int64) []int64 { sort.SliceStable(transactions, func(i, j int) bool { return transactions[i] > transactions[j] }) return transactions }
true
666f81bd3623df2521d42600e5e4a048d71af217
Go
kangman/objinsync
/pkg/sync/dir.go
UTF-8
988
3.1875
3
[ "MIT" ]
permissive
[ "MIT" ]
permissive
package sync import ( "os" "path/filepath" "strings" ) // file list contains absolute path // it won't include directories in the returned map func listAndPruneDir(dirname string) (map[string]bool, error) { files := make(map[string]bool) dirsToDelete := make(map[string]bool) err := filepath.Walk(dirname, func(path string, info os.FileInfo, err error) error { if err != nil { return err } if info.IsDir() { if strings.Contains(path, "__pycache__") { // ignore python cache files for sync return filepath.SkipDir } // don't delete root even if it's empty if path != dirname { dirsToDelete[path] = true } } else { parentDir := filepath.Dir(path) if _, ok := dirsToDelete[parentDir]; ok { // mark dir as not empty delete(dirsToDelete, parentDir) } files[path] = true } return nil }) if err != nil { return nil, err } // delete empty dirs for d, _ := range dirsToDelete { os.Remove(d) } return files, nil }
true
708636a72a695a574188853ba404c4510109ce36
Go
sescobb27/GolangWebServer
/src/webserver/dbconnection/dbconnection.go
UTF-8
4,946
2.734375
3
[ "MIT" ]
permissive
[ "MIT" ]
permissive
package dbconnection import ( "crypto/md5" "database/sql" "errors" "fmt" _ "github.com/lib/pq" "io" "os" "time" "webserver/models" ) const ( db_name string = "webserver" connection_format string = "user=%s dbname=%s sslmode=disable password=%s host=%s" get_user string = "SELECT _id FROM users WHERE username=$1 AND password_hash=$2" insert_user string = "INSERT INTO users (username, password_hash, created_at) VALUES ($1,$2,$3) RETURNING _id" get_user_file string = `SELECT ut.title, ut.path FROM users_files as ut join ( file_tags as ft join tags as t on (ft.tag_id = t._id and t.name = $1) ) as jft on (jft.file_id = ut._id) LIMIT $2 OFFSET $3` insert_file string = "insert into users_files (title, path, user_id, size) values ($1,$2,$3,$4) returning _id" insert_tag string = "insert into tags (name) values ($1) returning _id" insert_file_tags string = "insert into file_tags (file_id, tag_id) values ($1,$2)" get_all_tags string = "select name from tags" get_tags string = "select * from tags" ) func stablishConnection() (*sql.DB, error) { user := os.Getenv("POSTGRESQL_USER") pass := os.Getenv("POSTGRESQL_PASS") host := os.Getenv("PGHOST") connection_params := fmt.Sprintf(connection_format, user, db_name, pass, host) db, err := sql.Open("postgres", connection_params) if err != nil { println("error open") return nil, err } return db, nil } func assertNoError(err error) { if err != nil { panic(err) } } func encryptPassword(password string) string { hash := md5.New() io.WriteString(hash, password) return fmt.Sprintf("%x", hash.Sum(nil)) } func VerifyUser(user *models.User) (int64, error) { db, err := stablishConnection() if err != nil { return 0, err } defer db.Close() var user_id int64 err = db.QueryRow(get_user, user.Username, encryptPassword(*user.Password)).Scan(&user_id) switch { case err == sql.ErrNoRows: return 0, errors.New("No user with that ID.") case err != nil: return 0, err } return user_id, nil } func InsertUser(user *models.User, callback func(int64)) error { db, err := stablishConnection() assertNoError(err) defer db.Close() var transaction *sql.Tx transaction, err = db.Begin() assertNoError(err) var id int64 err = transaction.QueryRow(insert_user, user.Username, encryptPassword(*user.Password), time.Now()).Scan(&id) assertNoError(err) transaction.Commit() if callback != nil { callback(id) } return nil } func InsertUserFile(file *models.UserFile) { db, err := stablishConnection() assertNoError(err) getTags := make(chan map[string]int64) go func() { var tags map[string]int64 tags = getTagsAsObjects() // send tags via channel for continue getTags <- tags }() defer db.Close() var transaction *sql.Tx transaction, err = db.Begin() assertNoError(err) var fid, tid int64 err = transaction.QueryRow(insert_file, file.Title, file.Path, file.UserId, file.Size).Scan(&fid) assertNoError(err) transaction.Commit() // wait for all the tags tags := <-getTags fmt.Println(tags) label: for _, tag := range file.Tags { transaction, err = db.Begin() for k, v := range tags { if tag == k { _, err = transaction.Exec(insert_file_tags, fid, v) assertNoError(err) transaction.Commit() continue label } } err = transaction.QueryRow(insert_tag, tag).Scan(&tid) assertNoError(err) _, err = transaction.Exec(insert_file_tags, fid, tid) assertNoError(err) transaction.Commit() } } func GetUsersFiles(limit, offset int, tag string) ([]*models.UserFile, error) { db, err := stablishConnection() assertNoError(err) if limit <= 0 { limit = 10 } if offset < 0 { offset = 0 } if tag == "" { tag = "animals" } defer db.Close() var rows *sql.Rows rows, err = db.Query(get_user_file, tag, limit, offset) assertNoError(err) f_arr := make([]*models.UserFile, 0, limit) var path, title string var u_file *models.UserFile for rows.Next() { if err = rows.Scan(&title, &path); err != nil { panic(err) } if path != "" && title != "" { u_file = &models.UserFile{Path: path, Title: title} f_arr = append(f_arr, u_file) } } return f_arr, nil } func GetTags() []string { db, err := stablishConnection() assertNoError(err) defer db.Close() var rows *sql.Rows rows, err = db.Query(get_all_tags) assertNoError(err) tags := make([]string, 0) var name string for rows.Next() { if err = rows.Scan(&name); err != nil { panic(err) } tags = append(tags, name) } return tags } func getTagsAsObjects() map[string]int64 { db, err := stablishConnection() assertNoError(err) defer db.Close() var rows *sql.Rows rows, err = db.Query(get_tags) assertNoError(err) tags := make(map[string]int64) var name string var id int64 for rows.Next() { if err = rows.Scan(&id, &name); err != nil { panic(err) } tags[name] = id } return tags }
true
767b8d708041dd012dae44bd1ab1ed3be12947df
Go
onflow/cadence
/runtime/ast/programindices.go
UTF-8
4,498
2.578125
3
[ "Apache-2.0" ]
permissive
[ "Apache-2.0" ]
permissive
/* * Cadence - The resource-oriented smart contract programming language * * Copyright Dapper Labs, 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 ast import ( "sync" ) // programIndices is a container for all indices of a program's declarations type programIndices struct { once sync.Once // Use `pragmaDeclarations` instead _pragmaDeclarations []*PragmaDeclaration // Use `importDeclarations` instead _importDeclarations []*ImportDeclaration // Use `interfaceDeclarations` instead _interfaceDeclarations []*InterfaceDeclaration // Use `compositeDeclarations` instead _compositeDeclarations []*CompositeDeclaration // Use `attachmentDeclarations` instead _attachmentDeclarations []*AttachmentDeclaration // Use `functionDeclarations()` instead _functionDeclarations []*FunctionDeclaration // Use `transactionDeclarations()` instead _transactionDeclarations []*TransactionDeclaration // Use `variableDeclarations()` instead _variableDeclarations []*VariableDeclaration } func (i *programIndices) pragmaDeclarations(declarations []Declaration) []*PragmaDeclaration { i.once.Do(i.initializer(declarations)) return i._pragmaDeclarations } func (i *programIndices) importDeclarations(declarations []Declaration) []*ImportDeclaration { i.once.Do(i.initializer(declarations)) return i._importDeclarations } func (i *programIndices) interfaceDeclarations(declarations []Declaration) []*InterfaceDeclaration { i.once.Do(i.initializer(declarations)) return i._interfaceDeclarations } func (i *programIndices) compositeDeclarations(declarations []Declaration) []*CompositeDeclaration { i.once.Do(i.initializer(declarations)) return i._compositeDeclarations } func (i *programIndices) attachmentDeclarations(declarations []Declaration) []*AttachmentDeclaration { i.once.Do(i.initializer(declarations)) return i._attachmentDeclarations } func (i *programIndices) functionDeclarations(declarations []Declaration) []*FunctionDeclaration { i.once.Do(i.initializer(declarations)) return i._functionDeclarations } func (i *programIndices) transactionDeclarations(declarations []Declaration) []*TransactionDeclaration { i.once.Do(i.initializer(declarations)) return i._transactionDeclarations } func (i *programIndices) variableDeclarations(declarations []Declaration) []*VariableDeclaration { i.once.Do(i.initializer(declarations)) return i._variableDeclarations } func (i *programIndices) initializer(declarations []Declaration) func() { return func() { i.init(declarations) } } func (i *programIndices) init(declarations []Declaration) { // Important: allocate instead of nil i._pragmaDeclarations = make([]*PragmaDeclaration, 0) i._importDeclarations = make([]*ImportDeclaration, 0) i._compositeDeclarations = make([]*CompositeDeclaration, 0) i._attachmentDeclarations = make([]*AttachmentDeclaration, 0) i._interfaceDeclarations = make([]*InterfaceDeclaration, 0) i._functionDeclarations = make([]*FunctionDeclaration, 0) i._transactionDeclarations = make([]*TransactionDeclaration, 0) for _, declaration := range declarations { switch declaration := declaration.(type) { case *PragmaDeclaration: i._pragmaDeclarations = append(i._pragmaDeclarations, declaration) case *ImportDeclaration: i._importDeclarations = append(i._importDeclarations, declaration) case *CompositeDeclaration: i._compositeDeclarations = append(i._compositeDeclarations, declaration) case *AttachmentDeclaration: i._attachmentDeclarations = append(i._attachmentDeclarations, declaration) case *InterfaceDeclaration: i._interfaceDeclarations = append(i._interfaceDeclarations, declaration) case *FunctionDeclaration: i._functionDeclarations = append(i._functionDeclarations, declaration) case *TransactionDeclaration: i._transactionDeclarations = append(i._transactionDeclarations, declaration) case *VariableDeclaration: i._variableDeclarations = append(i._variableDeclarations, declaration) } } }
true
fe0d3b75d2329bae893bc91be4f69c8b4782e672
Go
ronniegane/hackerrank-solutions
/algorithms/implementation/leaderboard/leaderboard_test.go
UTF-8
665
3.09375
3
[]
no_license
[]
no_license
package leaderboard import ( "reflect" "testing" ) type testCase struct { name string scores []int32 alice []int32 ans []int32 } var testCases = []testCase{ {"1", []int32{100, 100, 50, 40, 40, 20, 10}, []int32{5, 25, 50, 120}, []int32{6, 4, 2, 1}}, {"2", []int32{100, 90, 90, 80, 75, 60}, []int32{50, 65, 77, 90, 102}, []int32{6, 5, 4, 2, 1}}, } func TestClimbing(t *testing.T) { for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { got := climbingLeaderboard(tc.scores, tc.alice) // test list equality if !reflect.DeepEqual(got, tc.ans) { t.Errorf("Scores were %v\n\t\t\t expected %v", got, tc.ans) } }) } }
true
ace3ce9153dd9311d96dd0580cd53fafcdd99507
Go
lupes/leetcode
/question_601_700/question_661_670/662_maximum_width_of_binary_tree_test.go
UTF-8
670
2.515625
3
[]
no_license
[]
no_license
package question_661_670 import ( "testing" . "github.com/lupes/leetcode/common" ) func Test_widthOfBinaryTree(t *testing.T) { tests := []struct { root *TreeNode want int }{ {nil, 0}, {NewNode(1), 1}, {NewNode(1, NewNode(3)), 1}, {NewNode(1, NewNode(3, NewNode(5), NewNode(3)), NewNode(2, nil, NewNode(9))), 4}, {NewNode(1, NewNode(3, NewNode(5), NewNode(3)), NewNode(2, NewNode(9))), 3}, {NewNode(1, NewNode(3, NewNode(5), NewNode(3))), 2}, } for _, tt := range tests { t.Run("test", func(t *testing.T) { if got := widthOfBinaryTree(tt.root); got != tt.want { t.Errorf("widthOfBinaryTree() = %v, want %v", got, tt.want) } }) } }
true
2d9a09716ffdcd01336baa6722aeb779b5e6d40e
Go
psychoplasma/crypto-balance-bot
/filter.go
UTF-8
4,748
3.265625
3
[ "MIT" ]
permissive
[ "MIT" ]
permissive
package cryptobot import ( "bytes" "encoding/json" "fmt" "math/big" ) // FilterType represents types of filters type FilterType string // Defined filter types const ( Amount FilterType = "amount" AddressOn FilterType = "addressOn" AddressOff FilterType = "addressOff" ) // Filter represents a domain entity which decides // at what condition notifications will be published type Filter struct { c condition isMust bool t FilterType } // NewAmountFilter creates a new instance of Amount type of Filter func NewAmountFilter(amount string, must bool) (*Filter, error) { a, ok := new(big.Int).SetString(amount, 10) if !ok { return nil, fmt.Errorf("amount(%s) is not a valid number representation", amount) } return NewFilter(Amount, &amountCondition{Amount: a}, must), nil } // NewAddressOnFilter creates a new instance of AddressOn type of Filter func NewAddressOnFilter(address string, must bool) (*Filter, error) { if address == "" { return nil, fmt.Errorf("empty address") } return NewFilter(AddressOn, &addressOnCondition{Address: address}, must), nil } // NewAddressOffFilter creates a new instance of AddressOff type of Filter func NewAddressOffFilter(address string, must bool) (*Filter, error) { if address == "" { return nil, fmt.Errorf("empty address") } return NewFilter(AddressOff, &addressOffCondition{Address: address}, must), nil } // NewFilter creates a new instance of Filter func NewFilter(t FilterType, c condition, must bool) *Filter { return &Filter{ c: c, isMust: must, t: t, } } // CheckCondition checks whether or not the given conditions satisfy this filter func (f *Filter) CheckCondition(t *Transfer) bool { return f.c.CheckAgainst(t) } // IsMust returns true if this filter always must be satisfied to publish a notification // regardless of the other filters, false otherwise func (f *Filter) IsMust() bool { return f.isMust } // Type returns type property func (f *Filter) Type() FilterType { return f.t } // SerializeCondition serializes the condition data // which can be different for each type of condition func (f *Filter) SerializeCondition() ([]byte, error) { return f.c.Serialize() } // DeserializeCondition deserializes the given data to // the corresponding condition according to type of the filter func (f *Filter) DeserializeCondition(data []byte) error { switch f.t { case Amount: f.c = new(amountCondition) return f.c.Deserialize(data) case AddressOn: f.c = new(addressOnCondition) return f.c.Deserialize(data) case AddressOff: f.c = new(addressOffCondition) return f.c.Deserialize(data) default: return fmt.Errorf("unrecognized filter type: %s", f.t) } } // ToString returns human-readable string representation of this filter func (f *Filter) ToString() string { return fmt.Sprintf("filters any transfer whose %s. Is this a must? -> %v", f.c.ToString(), f.isMust) } // Condition represents condition parameters and // its condition check for a specific type of Filter type condition interface { CheckAgainst(t *Transfer) bool Serialize() ([]byte, error) Deserialize(data []byte) error ToString() string } type amountCondition struct { Amount *big.Int `json:"amount"` } func (c *amountCondition) CheckAgainst(t *Transfer) bool { return t.Amount.Cmp(c.Amount) > -1 } func (c *amountCondition) Serialize() ([]byte, error) { return json.Marshal(c) } func (c *amountCondition) Deserialize(data []byte) error { return decodeJSONStrictly(data, c) } func (c *amountCondition) ToString() string { return fmt.Sprintf("amount is greater than or equal to %s", c.Amount.String()) } type addressOnCondition struct { Address string `json:"address"` } func (c *addressOnCondition) CheckAgainst(t *Transfer) bool { return c.Address == t.Address } func (c *addressOnCondition) Serialize() ([]byte, error) { return json.Marshal(c) } func (c *addressOnCondition) Deserialize(data []byte) error { return decodeJSONStrictly(data, c) } func (c *addressOnCondition) ToString() string { return fmt.Sprintf("second-party address is equal to \"%s\"", c.Address) } type addressOffCondition struct { Address string `json:"address"` } func (c *addressOffCondition) CheckAgainst(t *Transfer) bool { return c.Address != t.Address } func (c *addressOffCondition) Serialize() ([]byte, error) { return json.Marshal(c) } func (c *addressOffCondition) Deserialize(data []byte) error { return decodeJSONStrictly(data, c) } func (c *addressOffCondition) ToString() string { return fmt.Sprintf("second-party address is different than \"%s\"", c.Address) } func decodeJSONStrictly(data []byte, i interface{}) error { d := json.NewDecoder(bytes.NewReader(data)) d.DisallowUnknownFields() return d.Decode(i) }
true
4e72708d7f8aafb6cdfc3008bad2cb1251ad5ce9
Go
lukebrady/ppgen
/main.go
UTF-8
3,296
2.625
3
[ "Apache-2.0" ]
permissive
[ "Apache-2.0" ]
permissive
package main import ( "fmt" "net/http" ) func statusRoute(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "Puppet Generator is running.\n") fmt.Fprintf(w, "The Resources available are:\nfile,\nuser,\ngroup,\npackage,\nmount") } func fileRoute(w http.ResponseWriter, r *http.Request) { file := "file { 'name':\n\tensure => file,\n\towner => owner,\n\tgroup => group,\n\tmode => mode,\n\tsource => 'puppet:///modules/class/file.txt';\n}\n" fmt.Fprintf(w, file) } func userRoute(w http.ResponseWriter, r *http.Request) { user := "user { 'name':\n\tcomment => 'First Last',\n\thome => '/home/name',\n\tensure => present,\n\t#shell => '/bin/bash',\n\t#uid => '501',\n\t#gid => '20',\n}\n" fmt.Fprintf(w, user) } func groupRoute(w http.ResponseWriter, r *http.Request) { group := "group { 'name':\n\tgid => 1,\n}\n" fmt.Fprintf(w, group) } func packageRoute(w http.ResponseWriter, r *http.Request) { pack := "package { 'name':\n\tensure => installed,\n}\n" fmt.Fprintf(w, pack) } func execRoute(w http.ResponseWriter, r *http.Request) { exec := "exec { 'name':\n\tcommand => '/bin/echo',\n\t# path => '/usr/bin:/usr/sbin:/bin:/usr/local/bin',\n\t# refreshonly => true,\n}\n" fmt.Fprintf(w, exec) } func cronRoute(w http.ResponseWriter, r *http.Request) { cron := "cron { 'name':\n\tcommand => '/path/to/executable',\n\t# user => 'root',\n\t# hour => 1,\n\t# minute => 0,\n\t}\n" fmt.Fprintf(w, cron) } func serviceRoute(w http.ResponseWriter, r *http.Request) { service := "service { 'name':\n\tensure => running,\n\tenable => true,\n\thasrestart => true,\n\thasstatus => true,\n\t# pattern => 'name',\n}\n" fmt.Fprintf(w, service) } func mountRoute(w http.ResponseWriter, r *http.Request) { mount := "mount { 'name':\n\tensure => present,\n\tdevice => 'device',\n\tfstype => 'fstype',\n\toptions => 'opts';\n}\n" fmt.Fprintf(w, mount) } func yumRepoRoute(w http.ResponseWriter, r *http.Request) { yum := "yumrepo { 'name':\n\tbaseurl => '',\n\tdescr => 'The repository',\n\tenabled => '1',\n\tgpgcheck => '1',\n\tgpgkey => 'file:///etc/pki/rpm-gpg/RPM-GPG-KEY-',\n\tmirrorlist => '',\n}\n" fmt.Fprintf(w, yum) } func ifRoute(w http.ResponseWriter, r *http.Request) { ifv := "if test {\n\t# enter puppet code\n}\n" fmt.Fprintf(w, ifv) } func elseifRoute(w http.ResponseWriter, r *http.Request) { elseifv := "elseif test {\n\t# enter puppet code\n}\n" fmt.Fprintf(w, elseifv) } func elseRoute(w http.ResponseWriter, r *http.Request) { elsev := "else {\n\t# enter puppet code\n}\n" fmt.Fprintf(w, elsev) } func caseRoute(w http.ResponseWriter, r *http.Request) { elsev := "case $variable {\n\t'value': {\n\t# code\n}\n\tdefault: {\n\t# code\n\t}\n}\n" fmt.Fprintf(w, elsev) } func main() { mux := http.NewServeMux() mux.HandleFunc("/", statusRoute) mux.HandleFunc("/file", fileRoute) mux.HandleFunc("/user", userRoute) mux.HandleFunc("/group", groupRoute) mux.HandleFunc("/package", packageRoute) mux.HandleFunc("/exec", execRoute) mux.HandleFunc("/cron", cronRoute) mux.HandleFunc("/service", serviceRoute) mux.HandleFunc("/mount", mountRoute) mux.HandleFunc("/yumrepo", yumRepoRoute) mux.HandleFunc("/if", ifRoute) mux.HandleFunc("/elseif", elseifRoute) mux.HandleFunc("/else", elseRoute) http.ListenAndServe(":8080", mux) }
true
8c827f7e68551aceae980a1812cd43dcba831dd8
Go
MyPureCloud/platform-client-sdk-cli
/build/gc/models/mergerequest.go
UTF-8
1,288
2.65625
3
[ "MIT" ]
permissive
[ "MIT" ]
permissive
package models import ( "encoding/json" "strconv" "strings" ) var ( MergerequestMarshalled = false ) // This struct is here to use the useless readonly properties so that their required imports don't throw an unused error (time, etc.) type MergerequestDud struct { } // Mergerequest type Mergerequest struct { // SourceContactId - The ID of the source contact for the merge operation SourceContactId string `json:"sourceContactId"` // TargetContactId - The ID of the target contact for the merge operation TargetContactId string `json:"targetContactId"` } // String returns a JSON representation of the model func (o *Mergerequest) String() string { j, _ := json.Marshal(o) str, _ := strconv.Unquote(strings.Replace(strconv.Quote(string(j)), `\\u`, `\u`, -1)) return str } func (u *Mergerequest) MarshalJSON() ([]byte, error) { type Alias Mergerequest if MergerequestMarshalled { return []byte("{}"), nil } MergerequestMarshalled = true return json.Marshal(&struct { SourceContactId string `json:"sourceContactId"` TargetContactId string `json:"targetContactId"` *Alias }{ Alias: (*Alias)(u), }) }
true
ca9fc556fb3d5040c7e9edacf0281cc57cafbebe
Go
lupes/leetcode
/question_501_600/question_501_510/506_relative_ranks.go
UTF-8
638
3.328125
3
[]
no_license
[]
no_license
package question_501_510 import ( "sort" "strconv" ) // 506. 相对名次 // https://leetcode-cn.com/problems/relative-ranks/ // Topics: 数组 排序 堆 func findRelativeRanks(nums []int) []string { var flag = make([][2]int, len(nums)) for i, n := range nums { flag[i] = [2]int{i, n} } sort.Slice(flag, func(i, j int) bool { return flag[i][1] > flag[j][1] }) var res = make([]string, len(nums)) for i, n := range flag { switch i { case 0: res[n[0]] = "Gold Medal" case 1: res[n[0]] = "Silver Medal" case 2: res[n[0]] = "Bronze Medal" default: res[n[0]] = strconv.Itoa(i + 1) } } return res }
true
e21b48f770b56bb4c0704febf503176b60e59478
Go
cybercase/google-forms-html-exporter
/cmd/formdress/form_test.go
UTF-8
2,671
2.828125
3
[ "BSD-3-Clause" ]
permissive
[ "BSD-3-Clause" ]
permissive
package main import ( "encoding/json" "io/ioutil" "log" "net/http" "net/http/httptest" "reflect" "testing" ) var urlTests = []struct { Url string Valid bool }{ {"not an url", false}, {"http://not.google.form.url.com/somepath", false}, {"https://docs.google.com/forms/d/1Z-_ewPdnRmbqYjSTk3_hEovJw-CCAOlHm8dOKiAOfvc/edit", false}, // private edit url {"https://docs.google.com/a/balsamiq.com/forms/d/e/1FAIpQLSfnPMNxYkElNjWoC-sAdxza2JXACLxQRmbPvfE0nJoBcFMLaw/viewform", true}, // company account {"https://docs.google.com/forms/d/e/1FAIpQLSdgHnrWlSYKOa6x26roquuVg5Z--4kUvnHh16rEPjgRpulJNQ/viewform", true}, // personal account } func TestURL(t *testing.T) { for _, urlTest := range urlTests { err := CheckURL(urlTest.Url) if err == nil != urlTest.Valid { t.Error( "URL", urlTest.Url, "EXPECTED", urlTest.Valid, "GOT", err == nil, ) } } } var formTests = []struct { Url string Status int Body string }{ { Url: "https://docs.google.com/forms/d/e/1FAIpQLSdjZK2A_L9zUprCxOJdvvjexmNmxwmZCN6vMmTXAIZhJqUg3w/viewform", Status: http.StatusOK, Body: ` { "title": "Short Test", "header": "Short Test", "desc": "description", "path": "/forms", "sectionCount": 1, "askEmail": false, "action": "e/1FAIpQLSdjZK2A_L9zUprCxOJdvvjexmNmxwmZCN6vMmTXAIZhJqUg3w", "fields": [ { "id": 10920109, "label": "Short", "desc": "Short Description", "typeid": 1, "widgets": [ { "id": "499896788", "required": false } ] } ] } `, }, } func TestFormHandler(t *testing.T) { for _, formTest := range formTests { req, err := http.NewRequest("GET", "/formdress?url="+formTest.Url, nil) if err != nil { log.Fatal(err) } rr := httptest.NewRecorder() FormDressHandler(rr, req) res := rr.Result() if res.StatusCode != formTest.Status { t.Error( "Status EXPECTED", formTest.Status, "GOT", res.StatusCode, ) } resJSON := &map[string]interface{}{} body, _ := ioutil.ReadAll(res.Body) if err := json.Unmarshal(body, resJSON); err != nil { log.Fatal(err) } formJSON := &map[string]interface{}{} if err := json.Unmarshal([]byte(formTest.Body), formJSON); err != nil { log.Fatal(err) } // Make sure the random attribute value match (*formJSON)["fbzx"] = (*resJSON)["fbzx"] if !reflect.DeepEqual(resJSON, formJSON) { resString, _ := json.MarshalIndent(resJSON, "", " ") formString, _ := json.MarshalIndent(formJSON, "", " ") t.Errorf("FOR: %s\nEXPECTED\n%s\nGOT\n%s", formTest.Url, formString, resString) } } }
true
7f135afc9812b14e8e1a2682a6939296fdf00dc3
Go
vitessio/vitess
/go/vt/sqlparser/rewriter_api.go
UTF-8
5,036
2.90625
3
[ "Apache-2.0" ]
permissive
[ "Apache-2.0" ]
permissive
/* Copyright 2019 The Vitess Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package sqlparser // The rewriter was heavily inspired by https://github.com/golang/tools/blob/master/go/ast/astutil/rewrite.go // Rewrite traverses a syntax tree recursively, starting with root, // and calling pre and post for each node as described below. // Rewrite returns the syntax tree, possibly modified. // // If pre is not nil, it is called for each node before the node's // children are traversed (pre-order). If pre returns false, no // children are traversed, and post is not called for that node. // // If post is not nil, and a prior call of pre didn't return false, // post is called for each node after its children are traversed // (post-order). If post returns false, traversal is terminated and // Apply returns immediately. // // Only fields that refer to AST nodes are considered children; // i.e., fields of basic types (strings, []byte, etc.) are ignored. func Rewrite(node SQLNode, pre, post ApplyFunc) (result SQLNode) { parent := &RootNode{node} // this is the root-replacer, used when the user replaces the root of the ast replacer := func(newNode SQLNode, _ SQLNode) { parent.SQLNode = newNode } a := &application{ pre: pre, post: post, } a.rewriteSQLNode(parent, node, replacer) return parent.SQLNode } // SafeRewrite does not allow replacing nodes on the down walk of the tree walking // Long term this is the only Rewrite functionality we want func SafeRewrite( node SQLNode, shouldVisitChildren func(node SQLNode, parent SQLNode) bool, up ApplyFunc, ) SQLNode { var pre func(cursor *Cursor) bool if shouldVisitChildren != nil { pre = func(cursor *Cursor) bool { visitChildren := shouldVisitChildren(cursor.Node(), cursor.Parent()) if !visitChildren && up != nil { // this gives the up-function a chance to do work on this node even if we are not visiting the children // unfortunately, if the `up` function also returns false for this node, we won't abort the rest of the // tree walking. This is a temporary limitation, and will be fixed when we generated the correct code up(cursor) } return visitChildren } } return Rewrite(node, pre, up) } // RootNode is the root node of the AST when rewriting. It is the first element of the tree. type RootNode struct { SQLNode } // An ApplyFunc is invoked by Rewrite for each node n, even if n is nil, // before and/or after the node's children, using a Cursor describing // the current node and providing operations on it. // // The return value of ApplyFunc controls the syntax tree traversal. // See Rewrite for details. type ApplyFunc func(*Cursor) bool // A Cursor describes a node encountered during Apply. // Information about the node and its parent is available // from the Node and Parent methods. type Cursor struct { parent SQLNode replacer replacerFunc node SQLNode // marks that the node has been replaced, and the new node should be visited revisit bool } // Node returns the current Node. func (c *Cursor) Node() SQLNode { return c.node } // Parent returns the parent of the current Node. func (c *Cursor) Parent() SQLNode { return c.parent } // Replace replaces the current node in the parent field with this new object. The use needs to make sure to not // replace the object with something of the wrong type, or the visitor will panic. func (c *Cursor) Replace(newNode SQLNode) { c.replacer(newNode, c.parent) c.node = newNode } // ReplacerF returns a replace func that will work even when the cursor has moved to a different node. func (c *Cursor) ReplacerF() func(newNode SQLNode) { replacer := c.replacer parent := c.parent return func(newNode SQLNode) { replacer(newNode, parent) } } // ReplaceAndRevisit replaces the current node in the parent field with this new object. // When used, this will abort the visitation of the current node - no post or children visited, // and the new node visited. func (c *Cursor) ReplaceAndRevisit(newNode SQLNode) { switch newNode.(type) { case SelectExprs: default: // We need to add support to the generated code for when to look at the revisit flag. At the moment it is only // there for slices of SQLNode implementations panic("no support added for this type yet") } c.replacer(newNode, c.parent) c.node = newNode c.revisit = true } type replacerFunc func(newNode, parent SQLNode) // application carries all the shared data so we can pass it around cheaply. type application struct { pre, post ApplyFunc cur Cursor }
true
c0558905d953ef3ea764d728ba566955cad413ba
Go
jasonish/suricata-verify
/tests/http-range-multiflows/client.go
UTF-8
1,821
2.875
3
[ "MIT" ]
permissive
[ "MIT" ]
permissive
package main import ( "fmt" "io" "io/ioutil" "net" "net/http" "strconv" "strings" "time" ) type httpRange struct { Start uint End uint } const step = 1000 const url = "http://127.0.0.1:8000/mqtt5_pub_jpeg.pcap" func main() { tr := &http.Transport{ //may not be needed MaxIdleConns: 10, MaxIdleConnsPerHost: 10, MaxConnsPerHost: 10, IdleConnTimeout: 30 * time.Second, DisableKeepAlives: false, DialContext: (&net.Dialer{ Timeout: 30 * time.Second, KeepAlive: 30 * time.Second, DualStack: true, }).DialContext, } client := &http.Client{Transport: tr} myranges := []httpRange{ {1000, 2000}, // out of order {0, 1000}, // order + resume previous {500, 1500}, // only overlap {1500, 2500}, // overlap + new data {5000, 6000}, // out of order {2500, 3500}, // order but no resume {4000, 5000}, // out of order insert in head {8000, 9000}, // out or order insert at tail {6000, 7000}, // out of order insert in the middle {6400, 8000}, // insert with overlap {3000, 4000}, // overlap + new data + resume multiple } filesize := 0 for i := range myranges { req2, _ := http.NewRequest("GET", url, nil) req2.Header.Set("Range", fmt.Sprintf("bytes=%d-%d", myranges[i].Start, myranges[i].End-1)) resp2, _ := client.Do(req2) filesize, _ = strconv.Atoi(strings.Split(resp2.Header["Content-Range"][0], "/")[1]) io.Copy(ioutil.Discard, resp2.Body) resp2.Body.Close() fmt.Printf("download %#+v %#+v\n", myranges[i].Start, step) } for o := 8000; o < filesize; o += step { req2, _ := http.NewRequest("GET", url, nil) req2.Header.Set("Range", fmt.Sprintf("bytes=%d-%d", o, o+step-1)) resp2, _ := client.Do(req2) io.Copy(ioutil.Discard, resp2.Body) resp2.Body.Close() fmt.Printf("download %#+v %#+v\n", o, step) } }
true
6099990b047d08391c3b5ee7d74202ffdb393369
Go
quay/goval-parser
/oval/resolution_test.go
UTF-8
1,044
2.515625
3
[ "BSD-2-Clause" ]
permissive
[ "BSD-2-Clause" ]
permissive
package oval import ( "encoding/xml" "os" "testing" "github.com/google/go-cmp/cmp" ) func TestAdvisory(t *testing.T) { f, err := os.Open("../testdata/RHEL-8-including-unpatched-test.xml") if err != nil { t.Fatal(err) } defer f.Close() var root Root if err := xml.NewDecoder(f).Decode(&root); err != nil { t.Fatal(err) } arr := root.Definitions.Definitions m := len(arr) if !cmp.Equal(m, 4) { t.Error("Definition list length is incorrect") } stateExample := [4]string{"Will not fix", "Will not fix", "Will not fix", "Affected"} componentLength := [4]int{1, 9, 1, 3} for i := 0; i < m; i++ { if !cmp.Equal(len(arr[i].Advisory.Affected.Resolutions), 1) { t.Fatal("Affected resolution list length is incorrect") } resolution := arr[i].Advisory.Affected.Resolutions[0] name := resolution.State if !cmp.Equal(name, stateExample[i]) { t.Fatal("Resolutions state is incorrect") } if !cmp.Equal(len(resolution.Components), componentLength[i]) { t.Fatal("Component list length is incorrect") } } }
true